texts:
I currently have this code to generate a discrete signal with random amplitudes, but a fixed frequency:

import matplotlib.pyplot as plt
import numpy as np

# constants
t_len = 0.5
freq = 10.0
dt = 0.001

# set the see for reproducible results
rng = np.random.RandomState(0)

# create the random values to interpolate between
assert dt < freq
white_size = int(t_len * freq)
white_vals = rng.uniform(low=-1, high=1, size=white_size)

# setup the interpolation
white_noise = np.zeros(int(t_len / dt))
assert white_size < white_noise.shape[0]

# how can I avoid using this for-loop?
for w_i in xrange(white_size):
    white_noise[int(w_i/freq/dt):int((w_i+1)/freq/dt)] = white_vals[w_i]

# plot the result for visual verificaition
plt.plot(white_noise)
plt.show()

It generates something like this:

Like it says in the code comments, how do I get rid of this for-loop and vectorize the operation? I feel like I should be using reshape to accomplish this, but I'm not sure how.


texts: Split coins into combinations of different denominations

texts:
I have 3 types of coins: Gold, Silver, Copper.
1 silver = 100 copper.
1 gold = 100 silver.

My input is always in coppers, and I want to be able to make it a bit more readable. So far my code is:

def api_wallet_translate_gold(value):
    """Translate a value into string of money"""
    if value >= 10000:  # Gold
        return ("{0} gold, {1} silver and {2} copper."
                .format(str(value)[:-4], str(value)[-4:-2], str(value)[-2:]))
    elif value >= 100:  # Silver
        return "{0} silver and {1} copper.".format(str(value)[-4:-2], str(value)[-2:])
    else:  # Copper
        return "{0} copper.".format(str(value)[-2:])

It works, but I am wondering how could it be improved. I think there was a way to format it like {xx:2:2} or something but I can't remember how to do it.

Note: We never know how many gold digits we have, it could be 999999 to 1


texts:
I'm trying to understand where my ruby implementation of this fails and hoping for an expert to shed some light on this situation.  I've tried to make this a very simple example with the idea that setup is minimal.

The Problem:

I need to be able to log very quickly, ideally over UDP.  Alternatively I can log to a file but I'd prefer not to for a variety of reasons but mainly logfile rotations, another dependency like a "forwarding" app, etc.

With the code below I am able to benchmark 100_000 [<= 16byte] log messages:

                            Logfile  UDP
 Time elapsed (in seconds)  1.36    24.48

Specifics on that code include:  ruby 2.0.0-p353 MRI

The Logfile Setup

require 'logger'
logger = Logger.new("logfile.log")

start_time = Time.now
100_000.times do |i|
  logger.info "#{i}"
end

puts "Elapsed time was #{Time.now - start_time}"

UDP

The server (run this first):

require 'socket'
s = UDPSocket.new
s.bind(nil, 1234)
loop do
  text, sender = s.recvfrom_nonblock(16)
  # puts text
end

The client:

require 'socket'
s = UDPSocket.new
before_time = Time.now
100_000.times do |i|
  s.send("#{i}", 0, 'localhost', 1234)
end
puts "Time elapsed was #{Time.now - before_time}"

Why UDP?  Well I was under the impression that UDP was a "fire and forget" protocol where the client would not wait for the server to say they received it.  Fire and forget is fine for me in this scenario, I care more about performance.

Issue 1

As outlined in "The Problem" area - why is UDP so much slower than writing to a file?

Issue 2

You'll notice I have a commented out puts statement in the server.  If you uncomment that, the client's benchmark approaches 40+ seconds which really makes me think the client is waiting for the server or the server is communicating with the client.  Either way I'm probably not understanding UDP correctly.


texts: Multiply a square matrix with only the diagonal and antidiagonal elements different from zero in vector

texts:
So I have a square matrix with the diagonal and antidiagonal elements different from zero in a vector
vector<int> matrix = {1,2,3,4,5,6,7,8};

The matrix:
1 0 0 5
0 2 6 0
0 7 3 0
8 0 0 4

I try to multiply this with another matrix
xmatrix is the class for matrices
I tried like this:
void xmatrix::operator*(const xmatrix& mat)
{
    if(matrixSize != mat.getmatrixSize()) throw "Diff size";
    int x;
    for(int i = 0;i < matrixSize;i++){
        for(int j = 0;j < matrixSize;j++){
            x = 0;
            for(int k = 0;k < matrixSize;k++){
                x += getElement(i,k) * mat.getElement(k,j);
            }
            setElementMul(i,j,x);
        }
    }
}

The var and func names clearly says it all
ATM this code works fine with the first half of the matrix (multiply with itself)
41 0 0 225
0 46 294 0
0 35 219 0
40 0 0 216

what other ways can work fine or how should i edit this code


texts:
I am trying to solve the following problem at HackerRank:

  XOR-Sequence

  An array, \$A\$, is defined as follows:

  \$A_0 = 0\$
  \$A_x = A_{x-1} \oplus x\$ for \$x>0\$, where \$\oplus\$ is the symbol for XOR

  You must answer \$Q\$ questions. Each \$i^{th}\$ question is in the form \$L_i\ R_i\$, and the answer is \$A_{L_i} \oplus A_{L_i+1} \oplus \ldots \oplus A_{R_i-1} \oplus A_{R_i}\$ (the Xor-Sum of segment \$[Li,Ri]\$).

  Print the answer to each question.

  Input Format

  The first line contains \$Q\$ (the number of questions).
  The \$Q\$ subsequent lines each contain two space separated integers, \$L\$ and \$R\$, respectively. Line \$i\$ contains \$L_i\$ and \$R_i\$.

  Constraints

  \$1 \le Q \le 10^5\$
  \$1 \le L_i \le R_i \le 10^{15}\$

My code is correct, but it's slow. It really starts slowing down once I reach numbers like 269 million for the array index. The max array index can be 1015, so it will be really slow. What things can I do to increase the speed?

#include <iostream>

int main() {
  int N;
  int64_t f_index, l_index;

  std::cin >> N;
  for (int i = 0; i < N; ++i) {
    std::cin >> f_index >> l_index;
    int64_t sum = 0;
    int64_t temp;
    for (int64_t index = f_index; index <= l_index; ++index) {
      if (index%4 == 0) {
        temp = sum^index;
        sum = temp;
      } else if (index%4 == 1) {
        temp = sum^1;
        sum = temp;
      } else if (index%4 == 2) {
        temp = sum^(index + 1);
        sum = temp;
      } else if (index%4 == 3) {
        temp = sum^0;
        sum = temp;
      }
    }
    std::cout << sum << std::endl;
  }
  return 0;
}


texts: Getting table cell contents in a row and displaying them as a concatenated tooltip on each cell

texts:
I have a JavaScript code that gets the inner text content of certain table cells in a row and displays them as a tooltip on mouseover. However, I am a novice at JavaScript and I do not know how to make the code more efficient and/or secure from exploits.

<!DOCTYPE html>

<meta charset='utf-8' />
<title>Test page</title>

Name
Population (2000)
Population (2005)

San Antonio
3,420
3,572

Green Valley
1,409
1,222


texts:
I wanted to write my own code for md5 in javascript and learn its inner mechanics. (I know it is not trusted anymore, deprecated, ... but I'm just learning).
I didn't want to just copy the code that uses these like 60 repeated lines and over-complicated functions (like here), so I started writing my own implementation:
(Although I have just written this pseudocode in js)

function myMD5(string){
    /*bit rotation*/
    var rot = function(word, shift){return word << shift | word >>> (32 - shift);};
    /*unsigning also cuts to 32bit words*/
    var us = function(word){return word >>> 0;};
    /*function for unsigned adding words mod 2**32*/
    var add = function(wordsarr){
        var res = 0;
        for(var wr = 0; wr < wordsarr.length; wr++)
            res = us(res + us(wordsarr[wr]));
        return res;
    };
    /*converting string to utf8encoded string to bytes to 32bit-words to 512bit padded blocks*/
    var bytes = [];
    string = unescape(encodeURIComponent(string));
    for(var char = 0; char < string.length; char++)
        bytes[char] = string.charCodeAt(char);
    bytes.push(0x80);
    var words = [];
    for(var byte = 0; byte < bytes.length; byte += 4)
        words.push(bytes[byte + 3] << 24 | bytes[byte + 2] << 16 | bytes[byte + 1] << 8 | bytes[byte]);
    while(words.length % 16 != 14)
        words.push(0);
    words.push((bytes.length - 1) << 3);
    words.push((bytes.length - 1) >>> 29);
    /*initialization of the constants*/
    var K = [];
    for(var i = 1; i <= 64; i++)
        K.push(Math.floor(0x100000000 * Math.abs(Math.sin(i))));
    var shif = [0x07, 0x0c, 0x11, 0x16, 0x07, 0x0c, 0x11, 0x16, 0x07, 0x0c, 0x11, 0x16, 0x07, 0x0c, 0x11, 0x16,
                0x05, 0x09, 0x0e, 0x14, 0x05, 0x09, 0x0e, 0x14, 0x05, 0x09, 0x0e, 0x14, 0x05, 0x09, 0x0e, 0x14,
                0x04, 0x0b, 0x10, 0x17, 0x04, 0x0b, 0x10, 0x17, 0x04, 0x0b, 0x10, 0x17, 0x04, 0x0b, 0x10, 0x17,
                0x06, 0x0a, 0x0f, 0x15, 0x06, 0x0a, 0x0f, 0x15, 0x06, 0x0a, 0x0f, 0x15, 0x06, 0x0a, 0x0f, 0x15];
    var a0 = 0x67452301,
        b0 = 0xefcdab89,
        c0 = 0x98badcfe,
        d0 = 0x10325476;
    var F, ix;
    var chunk;
    var A, B, C, D;
    for(var pos = 0; pos < words.length; pos += 16){
        /*chunk = current 512bit block*/
        var chunk = words.slice(pos, pos + 16);
        A = a0;
        B = b0;
        C = c0;
        D = d0;
        for(var rnd = 0; rnd < 64; rnd++){
            /*round type*/
            if(rnd < 16){
                F = (B & C) | (~B & D);
                ix = rnd;
            }
            else if(rnd < 32){
                F = (B & D) | (C & ~D);
                ix = (5 * rnd + 1) % 16;
            }
            else if(rnd < 48){
                F = B ^ C ^ D;
                ix = (3 * rnd + 5) % 16;
            }
            else{
                F = C ^ (B | ~D);
                ix = (7 * rnd) % 16;
            }
            /*prepare for the next round, compute the temporary F*/
            F = add([F, A, K[rnd], chunk[ix]]);
            A = D;
            D = C;
            C = B;
            B = add([B, rot(F, shif[rnd])]);
        }
        /*add to the current state mod 2**32*/
        a0 = add([a0, A]);
        b0 = add([b0, B]);
        c0 = add([c0, C]);
        d0 = add([d0, D]);
    }
    /*return the state words as 16 bytes*/
    return [a0 >>> 24, a0 >>> 16 & 0xff, a0 >>> 8 & 0xff, a0 & 0xff,
            b0 >>> 24, b0 >>> 16 & 0xff, b0 >>> 8 & 0xff, b0 & 0xff,
            c0 >>> 24, c0 >>> 16 & 0xff, c0 >>> 8 & 0xff, c0 & 0xff,
            d0 >>> 24, d0 >>> 16 & 0xff, d0 >>> 8 & 0xff, d0 & 0xff];
};

However, It doesn't work as it should...
I already fixed some mistakes, but now I can't find anything wrong!
Could someone help me troubleshooting?


texts: String data manipulated given CSV variables

texts:
The Requirements:

List the expensable items sorted by date and location given two variables: 'categories' and 'expenses'. The Categories variable provides the following information in order: Category ID, Category Name, and whether the category is expensable (Y/N). The Expenses variable  provides the following information in order: Location, Date, Item Description, Cost, and Category Code. Each line should be displayed in the format "DATE: LOCATION - $TOTAL".

I put it together in a single JavaScript executable.

The code:

// Input Values
var categories = "CFE,Coffee,Y\nFD,Food,Y\nPRS,Personal,N";
var expenses = "Starbucks,3/10/2018,Iced Americano,4.28,CFE\nStarbucks,3/10/2018,Nitro Cold Brew,3.17,CFE\nStarbucks,3/10/2018,Souvineer Mug,8.19,PRS\nStarbucks,3/11/2018,Nitro Cold Brew,3.17,CFE\nHigh Point Market,3/11/2018,Iced Americano,2.75,CFE\nHigh Point Market,3/11/2018,Pastry,2.00,FD\nHigh Point Market,3/11/2018,Gift Card,10.00,PRS";

var AcceptableExpenses = GetAcceptableExpenses(GetAcceptableCategories(categories), expenses)

AcceptableExpenses.forEach (AcceptableExpense =>{
    console.log(AcceptableExpense.join(''))
})

function GetAcceptableExpenses(AcceptableCategories, expenses){
    var ExpensesList = expenses.split("\n")
    var AcceptableExpenseTotals = []
    var categoryIndex = 4
    var venderIndex = 0
    var dateIndex = 1
    var priceIndex = 3

    var venderDate = []
    ExpensesList.forEach(expense => {
        var expenseItemized = expense.split(',')

        if ((categoryIndex < expenseItemized.length) && IsExpenseItemAcceptable(AcceptableCategories, expenseItemized[categoryIndex])){
            venderDate = [expenseItemized[dateIndex], ": ", expenseItemized[venderIndex], " - $"].join('')

            if ( IsVenderDateIncluded(AcceptableExpenseTotals, venderDate) ){
                UpdatePrice(AcceptableExpenseTotals, venderDate, expenseItemized[priceIndex] )
            }
            else{
                AcceptableExpenseTotals.push([venderDate, expenseItemized[priceIndex] ])
            }
        }
    })
    return AcceptableExpenseTotals
}
function IsVenderDateIncluded(AcceptableExpenseTotals, venderDate){
    var venderDateIndex = 0
    var IsIncluded = false

    AcceptableExpenseTotals.forEach( AcceptableExpenseTotal =>{
        if (AcceptableExpenseTotal[venderDateIndex] === venderDate){
            IsIncluded = true
        }
    })

    return IsIncluded
}

function UpdatePrice(AcceptableExpenseTotals, venderDate, price ){
    var venderDateIndex = 0
    var priceIndex = 1
    AcceptableExpenseTotals.forEach( AcceptableExpenseTotal =>{
        if (AcceptableExpenseTotal[venderDateIndex] === venderDate){
            AcceptableExpenseTotal[priceIndex] = parseFloat( price) + parseFloat(AcceptableExpenseTotal[priceIndex])
            return
        }
    })
}

function IsExpenseItemAcceptable(AcceptableCategories, category ){
    var IsAcceptable = false
    AcceptableCategories.forEach(AcceptableCategory => {
        if (AcceptableCategory === category){
            IsAcceptable = true
        }
    })
    return IsAcceptable
}

function GetAcceptableCategories(categories){
    var categoryList = categories.split("\n")
    var AcceptableCategory = []

    for (i = 0; i < categoryList.length; i++){
        var categoryData = categoryList[i].split(',');
        var locationOf_IsExpensible = 2;
        var locationOf_Category = 0;
        if (locationOf_IsExpensible < categoryData.length ){
            if (categoryData[locationOf_IsExpensible]==="Y"){
                AcceptableCategory.push(categoryData[locationOf_Category])
            }
        }
    }
    return AcceptableCategory
}


texts:
In short, I need help simplifying and optimizing this code because now that I have switched to a tree widget from 2 list widgets, loading the tables has increased by roughly 3-4 seconds (used to be almost instant). I would also like to shorten this function if possible.

--- Background Info ---
self.tableData -- The table that the information is being displayed to
getItem() -- a function that when a table of a database is selected, returns the database name (var[0]) and the table name (var[1])
columnNames -- Returns the column names for the table
rows -- returns the total number of rows in the table
g -- index value for the row
h -- index value for the column the data will go in

-- forgot what i, j, k do because i was working on other parts of the program, but they are needed (been some time now)

Note: This code belongs to a class which I have not included

def LoadTable():
    self.tableData.clear()
    if getItem() != None:
        var = getItem()
        try:
            ccnnxx = mysql.connector.connect(user=self.uname.text(), password=self.upass.text(), host=self.uhost.text(), port=self.uport.text(), database = var[0])
            cursor = ccnnxx.cursor()
            self.tableData.setRowCount(0)
            self.tableData.setColumnCount(0)
            header = self.tableData.horizontalHeader()
            item = getItem()
            cursor.execute("SELECT * FROM " + var[1])
            rows = cursor.fetchall()
            self.tableData.setRowCount(cursor.rowcount)
            ccnnxx.close()
            self.tableData.setColumnCount(len(rows[0]))
            columnNames = [a[0] for a in cursor.description]
            g = 0
            h = 0
            i = 0
            j = 0
            k = 0
            counter = 0
            for items in columnNames:
                item = QtWidgets.QTableWidgetItem()
                self.tableData.setHorizontalHeaderItem(g, item)
                self.tableData.horizontalHeaderItem(g).setText(QtWidgets.QApplication.translate("MainWindow", columnNames[h], None, -1))
                header.setSectionResizeMode(g, QtWidgets.QHeaderView.ResizeToContents)
                g += 1
                h += 1
            for row in rows:
                counter += 1
                if i < counter:
                    while j != len(rows[0]):
                        item = QtWidgets.QTableWidgetItem()
                        self.tableData.setItem(i, k, item)
                        self.tableData.item(i, k).setText(QtWidgets.QApplication.translate("MainWindow", str(row[j]), None, -1))
                        k +=1
                        j +=1
                    else:
                        i +=1
                        k = 0
                        j = 0
                else:
                    k = 0
                    j = 0
        except IndexError:
            #print('This table has no information!')
            pass
        except TypeError:
            #double right-click protection
            pass
     else:
         pass


texts:
I have the following factory class, wonder if this code can be implemented in better way. I saw few discussions about spring factory bean, but don't find good examples.

@service
public CustomerSearchFactory{
  @Autowired
  private CustomerSearchByID searchById;
  @Autowired
  private CustomerSearchByName searcyByName;
  @Autowired
  private CustomerSearchBySSN searchBySSN;

  public CustomerSearch getInstance(Request param){
    if (StringUtils.isNotBlank(param.getID()){
        return searchById;
    }else if (StringUtils.isNotBlank(param.getName()){
        return searcyByName;
    }else if (StringUtils.isNotBlank(param.getSSN()){
        return searchBySSN;
    }
  }
}

@service
public CustomerSearchByID implements CustomerSearch{
  @Autowired
  private Service1 service1;
  public Response search(Request request){
   --
   --
   ReturnResponse rs = service1.performSearch(inputRequest);
   --
   return response;
 }
}

@service
public CustomerSearchBySSN implements CustomerSearch{
  @Autowired
  private Service2 service2;
  public Response search(Request request){
   --
   --
   ReturnResponse rs = service2.performSSNSearch(inputRequest);
   --enter code here`
   return response;
 }
}

caller code:

CustomerSearch customerSearch= customerSearchFactory.getInstance(param)
response = customerSearch.search(request);

I am using the spring 3.1 framework and want to know if this code can be optimized.


texts: Printing characters in a matrix as a string

texts:
I need to solve this problem in Python 3 (within 3 sec):

  A is a given (NxM) rectangle, filled with characters "a" to "z".
  Start from A[1][1] to A[N][M] collect all character which is only
  one in its row and column, print them as a string.

  Input:

  \$N\$, \$M\$ in first line (number of row and column \$1 \le N\$, \$M \le
> 1000\$). Next, \$N\$ lines contain exactly \$M\$ characters.

  Output:

A single string

  Sample input 1:

1 9
arigatodl

  Sample output 1:

rigtodl

  Sample input 2:

5 6
cabboa
kiltik
rdetra
kelrek
dmcdnc

  Sample output 2:

codermn

This is still not fast enough when \$N\$, \$M\$ = 1000. I'd like suggestions on improving the speed, or any other ways to solve the given problem, as long as the solution is in Python 3 and is faster than mine.

from operator import itemgetter
Words,Chars,answer=[],"abcdefghijklmnopqrstuvwxyz",""
N,M=[int(i) for i in input().split()]
for _ in range(N):
    Words.append(input())
                                    # got the inputs
for row,word in enumerate(Words):   # going through each words
    Doubts=[]                       # collect chars only one in its row.
    for char in Chars:
            if (word.count(char)==1):
                    Doubts.append((char,word.index(char)))
    for case in sorted(Doubts,key=itemgetter(1)):   #sorting by index
            doubtless=True                  #checking whether 1 in its column or not.
            for i in range(N):
                    if (Words[i][case[1]]==case[0] and i!=row):
                            doubtless=False
                            break
            if (doubtless):
                    answer+=case[0] #if char is one in its row and column, adds to answer.
print (answer)


texts:
I have found similar posts which has some optimizations on Winning-checking logic: React Tic Tac Toe

My primary focus for this post is about hook setters being asynchronous.  So to check if anyone wins, I used useEffect to listen to the board.

  useEffect(
    () => {
      if (winning()) {
        setMessage(`Player ${turn % 2 ? 1 : 2} wins!`);
        setGameState("stopped");
      } else {
        setTurn(turn + 1);
      }
    },
    [board]
  );

When the move is made, the turn number won't increase when the game is finished.

However this makes the initial "turn number" 0 (so the effect adds to it to get 1).

Should I make the board update synchronous before calling the setters? (like using a tempBoard = {...board, (new move)} and check there instead?

Full code (Click handler is step)

import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

function App() {
  const [turn, setTurn] = useState(0);
  const [message, setMessage] = useState("");
  const [gameState, setGameState] = useState("playing");
  const [board, setBoard] = useState({});

  const winning = _ => {
    return (
      (board[0] &&
        board[1] &&
        board[2] &&
        board[0] === board[1] &&
        board[1] === board[2]) ||
      (board[3] &&
        board[4] &&
        board[5] &&
        board[3] === board[4] &&
        board[4] === board[5]) ||
      (board[6] &&
        board[7] &&
        board[8] &&
        board[6] === board[7] &&
        board[7] === board[8]) ||
      (board[0] &&
        board[3] &&
        board[6] &&
        board[0] === board[3] &&
        board[3] === board[6]) ||
      (board[1] &&
        board[4] &&
        board[7] &&
        board[1] === board[4] &&
        board[4] === board[7]) ||
      (board[2] &&
        board[5] &&
        board[8] &&
        board[2] === board[5] &&
        board[5] === board[8]) ||
      (board[0] &&
        board[4] &&
        board[8] &&
        board[0] === board[4] &&
        board[4] === board[8]) ||
      (board[2] &&
        board[4] &&
        board[6] &&
        board[2] === board[4] &&
        board[4] === board[6])
    );
  };

  useEffect(
    () => {
      if (winning()) {
        setMessage(`Player ${turn % 2 ? 1 : 2} wins!`);
        setGameState("stopped");
      } else {
        setTurn(turn + 1);
      }
    },
    [board]
  );

  const step = (n, turn) => {
    if (gameState === "playing" && !board[n]) {
      setBoard({ ...board, [n]: turn % 2 ? "x" : "o" });
    }
  };

  return (

      Turn {turn}

        {[0, 1, 2, 3, 4, 5, 6, 7, 8].map(n => (

            <button onClick={_ => step(n, turn)}>{board[n] || " "}</button>

        ))}

      {message}

  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

CodeSandbox


texts:
I've finally finished my universal query preparation function. Any suggestions on making it better? I feel it could use some tweaking, but am not sure how I would go about it.

Variable examples/explanation

$db - The database connection
$query - Example: $query = "SELECT * FROM users WHEREusername=?"
$operation - The operation you wish to perform (number of rows, insert data)
$type - The variable types in mysqli_stmt_bind_param (example: $type = "ssi")
$variables - The variables to replace the question marks with

function manipulate($db, $query, $operation, $type, $variables)
{
    //Check Number of Variables inputted
    $numVars = (int)strlen($type);
    //Seperate variables into an array
    $var = explode(",",$variables);

    //Handle Statement
    $stmt = mysqli_stmt_init($db);
    if(mysqli_stmt_prepare($stmt, $query)) {
        echo "
 QUERY PREPARED
";
        $x = 0;
        if( $numVars == 1 ) {
            mysqli_stmt_bind_param($stmt, $type, $var[0]);
        } else if ( $numVars == 2 ) {
            mysqli_stmt_bind_param($stmt, $type, $var[0], $var[1]);
        } else if ( $numVars == 3 ) {
            mysqli_stmt_bind_param($stmt, $type, $var[0], $var[1], $var[2]);
        } else if ( $numVars == 4 ) {
            mysqli_stmt_bind_param($stmt, $type, $var[0], $var[1], $var[2], $var[3]);
        } else if ( $numVars == 5 ) {
            mysqli_stmt_bind_param($stmt, $type, $var[0], $var[1], $var[2], $var[3], $var[4]);
        }

        mysqli_stmt_execute($stmt);
        mysqli_stmt_store_result($stmt);

        if($operation == "numRows" || $operation == "num_rows") {
            $output = mysqli_stmt_num_rows($stmt);
        } else {
            echo "Operation not supported";
        }

        mysqli_stmt_close($stmt);
        return $output;

    } else {
        echo mysqli_stmt_error($stmt);
        echo "
 QUERY DENIED
";
    }
}


texts:
I made this code in python using Open Notify API, there is something that I could improve?
Im new to coding and I'm almost 4 hours understanding and coding this program that let you interact by some inputs and it can give you information about how many people are in space now, where is the ISS now and when it will go through a given coordinate.
import requests, json, os, datetime

clear = lambda: os.system('cls')
clear ()
def peopleInSpace():
    responseAstros = requests.get("http://api.open-notify.org/astros.json")
    astros = responseAstros.json()
    people = astros['people']

    peopleInSpa = []
    for d in people:
        peopleInSpa.append(d['name'])
    print('There are', astros['number'], 'people in space, and their names are:', (', '.join(peopleInSpa)))

def issNowF():
    responseIssNow = requests.get('http://api.open-notify.org/iss-now.json')
    issNow = responseIssNow.json()

    issNowLat = issNow['iss_position']['latitude']
    issNowLon = issNow['iss_position']['longitude']
    issNowTime = issNow['timestamp']
    print('The International Space Station is right now (', datetime.datetime.fromtimestamp(issNowTime), ' GMT -3) on these approximately coordinates:', issNowLat, issNowLon)

def issNextTime():
    clear()
    lat = input("What is the latitude?")
    lon = input('What is the longitude?')
    parameters = {"lat":lat, "lon":lon }
    responseIssNextTime = requests.get('http://api.open-notify.org/iss-pass.json', params=parameters)
    issNextTime = responseIssNextTime.json()['response']
    risetimes = []
    for d in issNextTime:
        time = d['risetime']
        risetimes.append(time)
    times = []

    print("The next 5 times ISS is going to go through the given coordinates is:")
    for rt in risetimes:
        time = datetime.datetime.fromtimestamp(rt)
        times.append(time)
        print(time)

clear()
print('Press 1 to see how many people are in space right now')
print('Press 2 for getting the coordinates of the ISS right now')
print('Press 3 for seeing when the ISS will go through certain coordinates')
r = input('')

if r == '1':
    clear()
    peopleInSpace()
elif r == '2':
    clear()
    issNowF()
elif r == '3':
    clear()
    issNextTime()
else:
    clear()
    print('Please open the program again and press only 1, 2 or 3')


texts:
First of all, I'm trying to learn OOP PHP, so any advise will be great.

My idea is to create some kind of MVC Framework CMS kind of thing, just to learn OOP PHP and MVC well.

Let's say that I've got this code (note: I will separate the code pieces in different files, but this was just for testing):

<?php

function printExtender($var) {
    $returnVal = '<pre>';
    $returnVal .= print_r($var, TRUE);
    $returnVal .= '</pre>';
    return $returnVal;
}

class Main_Controller {

    protected $_vars = array();
    protected static $_instance;

    private function __construct() {
    }

    public static function getInstance() {
        if (!isset(self::$_instance)) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    public function & __get($name) {
        return $this -> _vars[$name];
    }

    public function __set($name, $value) {
        $this -> _vars[$name] = $value;
    }

    public function loadDefaultClasses(){
        $main = Main_Controller::getInstance();
        $main -> config = Config::getInstance();
        $main -> sql = SQL::getInstance();
    }
}

class Config {
    protected $_vars = array();
    protected static $_instance;

    private function __construct() {
        $this-> db = array("localhost");
    }

    public static function getInstance() {
        if (!isset(self::$_instance)) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    public function & __get($name) {
        return $this -> _vars[$name];
    }

    public function __set($name, $value) {
        $this -> _vars[$name] = $value;
    }

}

class SQL{
    protected static $_instance;

    private function __construct() {
        $main = Main_Controller::getInstance();
        echo printExtender($main -> config -> db);
    }

    public static function getInstance() {
        if (!isset(self::$_instance)) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }
}

$main = Main_Controller::getInstance();
$main -> loadDefaultClasses();

The idea was to get the $main -> config -> .... thing working so I can use that later on. Am I doing this right, or is it awful? And do you have any tips?


texts:
I'm trying to make a function that asks for a string input and then validates it. If the answer is not correct, the function asks them again for valid input with a while loop.

In order to validate the string input, I'm using a string array with all the possible answers to the question.

Because I'm using a string array I need to pass it into the function as a pointer.

The problem I'm running into is that to call the function properly currently I have to type this:

std::string possibleAnswers[3] = { "0","1","2" };
//find the length of the possibleAnswers array
int length = sizeof(possibleAnswers) / sizeof(possibleAnswers[0]);
//create a pointer that points at the string array
std::string* pointerPossibleAnswers = possibleAnswers;

//call function to validate input
std::string response = checkInput(pointerPossibleAnswers, length);

You'll also notice that I used
sizeof(possibleAnswers)/sizeof(possibleAnswers[0] to find the length which I can't call within the function, because the pointer in the function points to an element in the array, not the entire array.
My function implementation is here:

std::string checkInput(std::string* pointerPossibleAnswers, int length)
{
    std::string input;
    //input = toLowerCase(input);
    //create a boolean to continue to ask for input
    bool isAsking = true;
    while (isAsking)
    {
        std::getline(std::cin, input);

        //for loop checks against possibleAnswer array
        for(int i = 0; i< length; i++)
        {
            // dereference possibleAnswers pointer to the
            //ith position of the array
            if (input == *pointerPossibleAnswers)
            {
                isAsking = false;
                //stop checking if a possible response is found
                //break from the loop on next iteration
                i = length;
            }
            //make the pointer point to the next spot
            pointerPossibleAnswers++;
        }
        if (isAsking == true)
        {
            std::cout << "Invalid response, please enter a valid response." << std::endl;
            //reset the pointer to point at original memory
            //location
            for (int i = 0; i < length; i++)
            {
                pointerPossibleAnswers--;
            }
        }
    }
    return input;
}

I was just wondering if there is an easier way to call the function, which is one or two lines something like:

std::string possibleAnswers[3] = { "0","1","2" };
std::string response = checkInput(pointerPossibleAnswers, length);

within two lines that's more efficient, because I have noticed that I'm copying and pasting a lot of code each time. I feel like there is a much more efficient way to do this with a class or a vector, given they have some built in methods for calling


texts: Sheet display in function of date and time on open and save

texts:
Here's a simple one for u guys,
The code is called upon workbook_open and BeforeSave, it displays the right sheet in function of date and time (Day vs night shift vs date). The code run trough the sheet and activate it if the date on sheet is the same as the actual date. Since there's 2 sheets with the same date (day and night shift) i had to add a time condition. The nights shifts are before the day one (look at image) so i had to split my loop in 2 to make it work (could maybe be one). Also, if we're not in the week of that report, so that no sheets has a date that fits, i wanted it to select Friday cause it has a report on it. Since its called often i wanted to make sure that it is optimal.

Code :
Sub selectiondequartauto()
' Code that display sheet in fucntion of date and time

    Dim count As Long        ' Counter
    Dim xSh As Worksheet
    Dim activation as Boolean
    Dim sheetdate As Date

    Dim limitpm As Variant
    Dim limitam As Variant
    limitpm = TimeValue("16:15:00")  ' Night shift Start
    limitam = TimeValue("3:00:00")   ' Night shift end

    For Each xSh In Worksheets                   ' Loop on every visible sheet
        If xSh.Visible Then
           sheetdate = xSh.Cells(4, 2).Value ' Gives sheetdate the date of the sheet in present loop

            If TimeValue(Now) < limitpm And TimeValue(Now) > limitam Then

                If count < 1 Then                ' If count is smaller than 1 (no sheet w same date as now yet)

                    If sheetdate = Date Then     ' Si Sheetdate = actual date
                        count = count + 1        ' Count = 1 and next sheet, because 2 sheet have sheetdate = actual date
                    End If
                ElseIf count = 1 Then            ' Si count = 1
                    Activation = True
                    xSh.Activate                 ' Activate curent loop sheet and quit
                    Exit For
                End If

            Else  ' If we are in night shift time frame

                If sheetdate = Date Then
                    Activation = True
                    xSh.Activate                ' Activate curent loop sheet and quit
                    Exit For
                End If
            End If
        End If

    Next
    If Activation = False Then
        Sheets("Vendredi jour").Activate
    End If
End Sub


texts: Checking whether an array contains all distinct values

texts:
This method returns true if any arrays element is equal to another element value, returns False otherwise.

public static boolean distinctValues(int[] tmp){

    for (int i = tmp.length - 1; i > 0; i--) {
        for (int j = 1; j < i; j++) {
             System.out.println(j + ". " + tmp[i] + " and " + tmp[j] +
                                " are " + (tmp[i] == tmp[j] ? "equal" : "not equal"));
             if (tmp[i] == tmp[j]) {
                 return true;
             }
        }
    }
    return false;
}

Do You think its efficient and/or readable way to implement this?
If not, what would You suggest?


texts: Querying all records from one table, add column from another with foreign key constraint

texts:
Apologies for the cryptic title, I don't quite know how to title this question. I'm asking here rather than StackOverflow since I've got a working query, I'm just wondering if it can be improved.

Anyway, I've got three tables, administration, mapping and used_mappings. Administration holds details of individual financial administrations, mapping is a "static" table holding details for all available financial mappings, used_mappings holds records of what mappings are used by what administration (not every administration uses every mapping). The used_mappings table also has a column, custom_name, so the columns look as follows;

Administration

| id | name    |
|----|---------|
| 1  | Admin 1 |
| 2  | Admin 2 |

Mapping

| id | name      |
|----|-----------|
| 1  | Mapping 1 |
| 2  | Mapping 2 |
| 3  | Mapping 3 |
| 4  | Mapping 4 |
| 5  | Mapping 5 |

Used mapping

| id | administration_id | mapping_id | custom_name       |
|----|-------------------|------------|-------------------|
| 1  | 1                 | 1          | Revenue           |
| 2  | 1                 | 3          | Cost of sales     |
| 3  | 2                 | 1          | Bar revenue       |
| 4  | 2                 | 3          | Cost of bar sales |
| 5  | 2                 | 4          | Wages             |

I now need to fetch all records from mapping, regardless of them being used, and where a custom_name is defined in used_mappings for a specific administration, add it on as an extra column (and have custom_name in the results be null if no custom_name exists.)

I first tried a simple LEFT JOIN;

SELECT  M.id,
        M.name,
        U.custom_name as customName
FROM    mapping M
LEFT JOIN used_mapping U ON U. = M.id
WHERE U.administration_id = 2;

And although it does fetch the correct custom_names, because of the WHERE U.administration_id = 1; it only fetches rows from used_mapping where that condition is met. In other words, in this example it fetches

| id | name         | customName        |
|----|--------------|-------------------|
| 1  | Mapping 1    | Bar revenue       |
| 3  | Mapping 3    | Cost of bar sales |
| 4  | Mapping 4    | Wages             |

rather than

| id | name      | customName        |
|----|-----------|-------------------|
| 1  | Mapping 1 | Bar revenue       |
| 2  | Mapping 2 | null              |
| 3  | Mapping 3 | Cost of bar sales |
| 4  | Mapping 4 | Wages             |
| 5  | Mapping 5 | null              |

I've got it working with a slightly more complex LEFT JOIN;

SELECT  id,
        name,
        custom_name
    FROM mapping
AS M
LEFT JOIN (
    SELECT custom_name,
            mapping_id
    FROM used_mappings
    WHERE administration_id = 2
) AS U ON U.mapping_id = M.id;

but it takes twice as long compared to fetching all rows from mapping (obviously because for every record in mapping, it runs a query on used_mappings as well). Hence my question, is there a way of making the query more efficient?


texts: Finding the missing value in a proportion

texts:
Basically, I'd like to be able to solve a proportion after entering in all but one term. Specifically, I'm working on creating a calculator for the Combined Gas Law.

$$\frac{P_1\cdot V_1}{T_1} = \frac{P_2\cdot V_2}{T_2}$$

Right now, what I have is a program that takes in two double arrays for the original and final values, and a String that represents which term to solve for. However, this seems really repetitive. Is there a way to solve for the "missing term" or even create a missing term directly without having to involve many "if" or "switch" statements? At least if I could do a "for-each loop" to find the specific term that I had to solve for, and then it would "fill-in the proportion"

    public static double CombinedGasLaw ( double [] original, double [] end, String query)
{
    double p1 = original[0];
    double v1 = original[1];
    double t1 = original[2];
    double p2 = end[0];
    double v2 = end[1];
    double t2 = end[2];
    switch (query.toLowerCase())
    {
        case "v":
            return p1*v1*t2/(t1*p2);
        case "p":
            return p1*v1*t2/(t1*v2);
        case "t":
            return p2*v2*t1/(p1*v1);
    }
}
   public static void main(String[] args)
{
    double p1 = 1;
    double v1 = 1;
    double t1 = 1;
    double [] original = {p1, v1, t1};
    double p2 = 1;
    double v2 = 1;
    double t2 = 1;
    double [] end = {p2, v2, t2};
    String search = "v";
    double fin = CombinedGasLaw(original, end, search);
    System.out.println("All of the original input except for the missing value");
    System.out.println("the missing value");
}

All in all, is there a way to create a similar program or improve this such that I ONLY need to enter necessary values, and the remaining value could be returned


texts: Abstract Person with Employees and Clients

texts:
I have a interface with the following implementation

public abstract class PersonInterface
{
       public abstract void Update(PersonModel person);
        public abstract void Delete(int id);

        public virtual PersonModel Find(int id)
        {
            return new List<PersonModel>().Find(x => x.Id == id);
        }

        public virtual IEnumerable<Models.Person.Person> GetAll()
        {
            return new List<Models.Person.Person>();
        }
}

Since the application will handle client and employee i take that class and implement it. This is because client have a diferrent way of updating its properties and the same goes from employee

public class Client : PersonInterface{
  public override void Update(PersonModel person)
        {
           // implementing the way of how the client is going to be update it

        }

        public override void Delete(int id)
        {
            // implementing the way of how the client is going to be delete it
        }
}

And employee implementation:

public class Employee: PersonInterface{
  public override void Update(PersonModel person)
        {
           // implementing the way of how the employee is going to be update it

        }

        public override void Delete(int id)
        {
            // implementing the way of how the employee ent is going to be delete it
        }
}

And my question is: is this the correct way that solve my problem when handling cases that some classes have somethings in common but there are 2 or 3 this that may vary?


texts:
class Youtube
{
    private $url = null;
    private $id;

    public function __construct($url)
    {
        $this->url = $url;
        $this->parseUrl($url);
    }

    protected function parseUrl($url)
    {

        if (preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $match)) {
            $this->id = $match[1];
        }
        else
        {
            throw new exception('Cannot find an ID!');
        }

    }

    public function getVideo($width='560', $height='315')
    {
        $video = <<<EOF
        <iframe width="$width" height="$height" src="//www.youtube-nocookie.com/embed/$this->id" frameborder="0" allowfullscreen></iframe>
EOF;

        return $video;
    }

}

$sistar = new Youtube('http://www.youtube.com/watch?v=JtVhwsACgTw');
print $sistar->getVideo();

$twoneone = new Youtube('http://www.youtube.com/watch?v=LUrUPzLm5SI');
print $twoneone->getVideo();

This is my first object-oriented script in PHP (I hope it's not too bad in general). I know I should do more validation and commenting within the code. Do you have any suggestions for improving the quality of the code?


texts:
My answer to Project Euler problem 4 (largest palindrome of product of two 3-digit numbers) is below.
Please suggest improvements, style changes, indentation, commenting, naming, ...
And nitpicks are welcome!
Other than general stuff about the code below, I'd like to ask specifically about

assert is good to use? Frowned upon? Has possible drawbacks?
progn looks like a 2nd class construct. Is the usage in the final function correct? Are there other (more Lispy-like) options?

(defun e004-digits (n &optional (base 10))
    "return a list with the digits of n"
    (assert (and (integerp n) (>= n 1)
                 (integerp base) (>= base 2)))
    (loop with remainder
          while (> n 0)
          do (setf (values n remainder) (floor n base))
          collect remainder))

(defun e004-palindrome6p (n6)
    "determine if the 6-digit number n6 is a palindrome (in base 10)"
    (assert (and (integerp n6) (>= n6 100000) (<= n6 999999)))
    (let ((dd (e004-digits n6)))
         (and (= (nth 2 dd) (nth 3 dd))
              (= (nth 1 dd) (nth 4 dd))
              (= (nth 0 dd) (nth 5 dd)))))

(defun e004-largest-palindrome-in-square (siz)
    "find maximum palindrome product"
    (do* ((a siz)
          (b siz)
          (nextb)
          (sum (+ siz siz))
          (p (* a b) (* a b)))
         ((e004-palindrome6p p) p)
       ;; following half diagonals ensures (proof needed?)
       ;; the first palindrome product found is the largest
       (setf a (+ a 1))
       (setf b (- b 1))
       (if (> a siz) ; start next diagonal
           (progn (setf (values a nextb) (floor sum 2))
                  (setf b (+ a nextb -1))
                  (setf sum (- sum 1))))))

(defun e004 ()
    (e004-largest-palindrome-in-square 999))

code also available on github


texts: My first program in C. A simple command-line calculator

texts:
I've recently started programming in C and as my first serious program I thought I'd create a simple calculator. To make it a bit more complex I decided not to use the functions included in math.h (like pow) but to create these functions by myself.
Let me know if there is something I can do to improve this code.
#include<stdio.h>

double power(double x, double y, double r)                                                       // This function calculates the power and takes numer1, number2 and the results
{
    r = 1;                                                                           // We need to initialize the results otherwise we can't store the partial result on line 11
    int c;
    for (c = y; c > 0; c--)                                  // putting c equal to y we can decrement c and obtain the precise number of operations needed to complete the power
    {
        int pow = y;                                  // that's a bit tricky: we can't apply the modulus operand in line 12 because y is a double, so we must convert y in an int
        r *= x;                                                             // this way result = 1 * number1, then number1 * number1, then number1 * number1 * number1 and so on
        if ((x < 0) && (pow % 2 == 1))    /* If the first number is negative, and we calculate the power of this number to 2 or multiples, the number resulting will be negative
                                                                to obtain the correct result (positive) we must multiply the result to -1, if the previous conditions are met */
        {
            x *= -1;
        }
    }
    printf("%0.1lf", r);
}

double root(double x, double y, double r)
{
    int c;
      if (x < 0)
      {
         puts("is impossible to calcultate the root of a negative number");
      }
    for (c = 1; c < x; c++)
    {
        int partRes = x;
        partRes /= c;
        if (partRes * partRes == x)
        {
            printf("The root of %0.1lf is: %0.1d\n", x, partRes);
            break;
        }
    }
}

int main()
{
    double num1, num2, res;
    char op;
    puts("Input number, operator and number");
    puts("operands permitted: + (addition), - (subtraction), * (multiplication), / (division), ^ (power), $ (square root)");
    scanf("%lf %c %lf", &num1, &op, &num2);
    if (op == '+')
    {
        res = num1 + num2;
        printf("%0.1lf", res);
    }
    else if (op == '-')
    {
        res = num1 - num2;
        printf("%0.1lf", res);
    }
    else if (op == '*')
    {
        res = num1 * num2;
        printf("%0.1lf", res);
    }
    else if (op == '/')
    {
        res = num1 / num2;
        printf("%0.1lf", res);
    }
    else if (op == '^')
    {
        power(num1, num2, res);
    }
    else if (op == '$')
    {
        root(num1, num2, res);
    }
    else
    printf("error, use a valid operand");
}


texts: Picking a random state from a set based on probabilities

texts:
I'm writing a Markov Chain implementation, and need to be able to pick a random state from a set of states, where each state has a different probability of being chosen. In my caffeine-high, I wrote this:

(defn random-state
  "Accepts a map mapping a state to the frequency that it will be chosen.
  Assumes that the frequencies add up to 100%. Will have undesired behavior if that isn't the case."
  [state-frequency-map]
  (let [r (rand)]
    (loop [[[state prob] & rest-states] (seq state-frequency-map)
           prob-sum 0
           last-sum 0]

      (let [new-sum (+ prob-sum prob)]
        (if (<= last-sum r new-sum)
          state
          (recur rest-states new-sum prob-sum))))))

I had very little idea of how I was going to achieve this going in, so I kind of cobbled it together. Basically, it works by maintaining a sum of probabilities, and checking if a randomly generated number (between 0 and 1) falls between the last and current probability sums. For example:

The probability map is {:a 0.3, :b 0.3, :c 0.4}.
The randomly drawn number is 0.7.
0.7 is greater than the sums of :a and :b's probabilities (0.6), but less than :c's, so :c is chosen this time.

This works, but like I said, I kind of just threw it together as I figured out what I was going to do, and now I'm in mind-lock and can't think of improvements for it. Is this optimal? Are there any ways of making this more idiomatic via better use of built-ins? I'm looking for any suggestions here. I'd also be open to suggestions of entirely different approaches of solving this.
A solution that isn't O(n) with respect to the number of states would be nice.

Example of its use showing that it does indeed pick the states with the correct frequencies:

(let [tries 1e7]
  (mapv (fn [[s f]] [s (/ f tries)]) ; Get the percentage occurrence
    (frequencies
      (for [n (range tries)]
        (random-state
          {\a 0.2
           \b 0.2
           \c 0.5
           \d 0.1})))))

=> [[\b 0.2000032] [\a 0.2000432] [\c 0.4999343] [\d 0.1000193]]


texts: Extends Scala iterator's drop method to allow for drop(x: Long)

texts:
I have a need to drop quantities of elements from an iterator beyond Int.MaxValue so I wrote a helper function that does just that. However, I can't help but feel like I'm doing this the dumb way - that there's got to be some built-in language construct or at least a more elegant way of tackling the problem.

/**
 * drops a Long's worth of elements from an Iterator[T] and returns the succeeding element.
 *
 * @param dropVal is the number of elements we want to drop
 * @param iteratorLong is the the iterator from which you want to drop lots-o-elements
 *
 * @return the value you need
 */
def dropLongAndGet[T](dropVal: Long, iteratorLong: Iterator[T]): T = {
    val dropCount = dropVal / Int.MaxValue
    val dropCountRemainder = (dropVal % Int.MaxValue).toInt

    var localIteratorReference = iteratorLong
    for (i <- 0L until dropCount) {
        localIteratorReference = iteratorLong.drop(Int.MaxValue)
    }

    return localIteratorReference.drop(dropCountRemainder)
                                 .next
}

Also, I am aware that the code will work w/o the return keyword - I use it because I'm used to seeing it from Java, it doesn't hurt anything to have it there, and I think it helps non-Scala programmers make sense of what's going on if/when they have to read my code.


texts:
These two methods do the exact same thing (or at least they are supposed to!).  They both pass a simple test based on a mock context.  Neither has been exposed to any integrated testing yet.

Would one of the methods be preferred over the other (and why)?
Does anyone see any glaring mistakes in the LINQ version (this is my
first real attempt at a LINQ query)?

As you can see the first method is using a repository to hit a database.  In order to get the data needed, it makes two db calls to two different tables.  The second method is an attempt to simplify the code, make it cleaner and more readable.  Performance is not a primary concern at this point.  It's really more of a learning exercise.

public string GetDealerEmail( string dealerId )
{
    var dealerAddressRepo = StagRepositoryFactory<DealerAddress>.GetRepository( _spcomContext );
    List<DealerAddress> dealerAddress = dealerAddressRepo.GetWhere( x => x.DealerId.Equals( dealerId ) ).ToList( );
    string addressId = dealerAddress.FirstOrDefault( item => item.AddressTypeCode.Equals( "dealer", StringComparison.CurrentCultureIgnoreCase ) ).AddressId;
    var addressRepo = StagRepositoryFactory<Address>.GetRepository( _spcomContext );
    Address address = addressRepo.GetSingle( x => x.AddressId.Equals( addressId ) );
    return address.Email;
}

public string GetDealerEmailWithLinq( string dealerId)
{
    ISpcomContext context = _spcomContext as ISpcomContext;
    var query = from dealerAddress in context.DealerAddresses
                where dealerAddress.DealerId.Equals( dealerId )
                where dealerAddress.AddressTypeCode.Equals( "dealer", StringComparison.CurrentCultureIgnoreCase )
                join address in context.Addresses
                    on dealerAddress.AddressId equals address.AddressId
                select address.Email;
    var emailAddress = query.FirstOrDefault( );
    return emailAddress;
}


texts: A simple game that keeps track of the number of questions asked

texts:
This is just a simple counter, i was able to code it in two different ways but i want to know which way is more efficient and which way is more readable.
and which set of code is more "correct" in broad-manner of speaking.
and if there is another entirely different set of code that does the same function ?

Game Rules

  This is a simple game , at first it asks the user if they want to go
  right or left .  if the user picks left ; the program ends and it
  displays the "You Win!" message. however if the user picks anything
  else other than left ( for example : right ) the program will start a
  counter 'z' and it will display a different message for each time the
  user chooses the wrong direction or input. i have set it to 4
  different messages and then one last message that keeps playing on
  repeat until the user picks the correct direction.

however i feel like that there must be better code to do this.
can you please help?

the first set of code :

#This is a simple game where if you pick left you win,
#but if you pick right you keep going through 4 different levels of
#'you lose' messages and then a last one keeps repeating in a loop.

z = 0
n = input ( "Go left or right? \n" )
while n not in ["left", "Left"]:
    if z == 0 :
        print ("You lose * 0 ")
        z = z+1
        n = input ( "Go left or right? \n" )
    elif z == 1 :
        print ("You lose * 1 ")
        z = z+1
        n = input ( "Go left or right? \n" )
    elif z == 2 :
        print ("You lose * 2 ")
        z = z+1
        n = input ( "Go left or right? \n" )
    elif z == 3 :
        print ("You lose * 3 ")
        z = " "
        n = input ( "Go left or right? \n" )
    else :
        while n not in ["left", "Left" ] :
            print ( "You Lose * Infinite" )
            n = input ( "Go left or right? \n" )
print ( "\nYou Win!" )

Second set of code :

#This is a simple game where if you pick left you win,
#but if you pick right you keep going through 4 diffrent levels of
#'you lose' messegses and then a last one keeps repeating on a loop.

v = 0
z = 0
u = 0
x = 0
n = 0

while x == 0 :
    n = input ("Go Left or Right?")
    while n not in ["left", "Left"] and u == 0 :
        if   z == 0:
            print ( " You lose * 0 ")
        elif z == 1:
            print ( " You lose * 1 ")
        elif z == 2:
            print ( " You lose * 2 ")
        elif z == 3:
            print ( " You lose * 3 ")
        else :
            print ( " You lose * Infinite " )
        u = " "
    while z < 4 and v == 0 :
        z = z + 1
        v = " "
    u = 0
    v = 0
    if n == "left" or n == "Left":
        x=" "

print ( " You Win! ")

final set of code :

user = input ("Go left or right?")
counter = 0

while user not in ["left", "Left"] :
    if counter == 0 :
        print ("You lose * 0")
    elif counter == 1 :
        print ("You lose * 1")
    elif counter == 2 :
        print ("You lose * 2")
    elif counter == 3 :
        print ("You lose * 3")
    else :
        print ("You lose * Infinite")
    counter = counter + 1
    user = input ("Go left or right?")

print ("You Win!")


texts: Feedback on a small PHP function that generates JSON data

texts:
I wrote a PHP function that generates JSON data to populate a line graph. Through jQuery, my code uses a GET request to the PHP script to fetch the JSON data. An example of the JSON data is as follows:

{"labels":[{"x":"2013-10-30","a":"1","b":"8"},{"x":"2013-10-31","a":"2","b":"14"},{"x":"2013-11-01","a":"5","b":"12"}]}

The data is used to generate a time graph showing two values per date:

x: date
a: value1
b: value2

I'm still a beginner programmer and want to have some peer review on the code I wrote. Please give me some feedback on how I can improve it, and fix any errors or inefficient methods if present.

Function

function generateGraphData($start, $end, $format, $api, $server, $pdo)
{
    //Fetch unique entries between the given dates
    $query = "SELECT DISTINCT DATE(traffic_date) FROM traffic WHERE traffic_date BETWEEN ? AND ? AND traffic_api = ? AND traffic_server = ? ORDER BY traffic_date DESC";
    $dbc = $pdo->prepare($query);
    $dbc->execute(array($start, $end, $api, $server));
    $results = $dbc->fetchAll(PDO::FETCH_ASSOC);

    //Count unique and total views for each result
    foreach ($results as $key => $value)
    {
        $date = "%".$value['DATE(traffic_date)']."%";

        $dbc = $pdo->prepare("SELECT count(*) FROM traffic WHERE traffic_date LIKE ? AND traffic_api = ? AND traffic_server = ?");
        $dbc->execute(array($date, $api, $server));
        $total = $dbc->fetchColumn();
        $dbc = null;

        $dbc = $pdo->prepare("SELECT count(*) FROM traffic WHERE traffic_date LIKE ? AND traffic_api = ? AND traffic_server = ? GROUP BY traffic_ip");
        $dbc->execute(array($date, $api, $server));
        $unique = $dbc->fetchColumn();
        $dbc = null;

        $data[$key]["x"] = $value['DATE(traffic_date)'];
        $data[$key]["a"] = $unique;
        $data[$key]["b"] = $total;
    }

    //Create filler dates
    $fillerDates = new DatePeriod(new DateTime($start), new DateInterval('P1D'), new DateTime($end));

    foreach($fillerDates as $date)
    {
        $filler_date_array[] = array('x' => $date->format("Y-m-d"), 'a' => '0', 'b' => '0');
    }

    $data = array_merge($data, $filler_date_array);

    //Remove filler dates if real date exists
    $filter_unique_array = array();
    $keysArray = array();

    foreach ($data as $innerArray)
    {
        if (!in_array($innerArray["x"], $keysArray))
        {
            $keysArray[] = $innerArray["x"];
            $filter_unique_array[] = $innerArray;
        }
    }

    //Sort by date
    array_sort_by_date($filter_unique_array, "date");

    //Format JSON
    $json = json_encode($filter_unique_array);
    $jsonlabel = '{"labels":'.$json.'}';
    echo $jsonlabel;
}


texts:
I'm writing a query to get the number of sessions created each day for the past 90 days. I'm currently using a prepared statement to do this - looks something like this:

for($n = 0; $n < 90; ++$n){
    $days[] = $n;
}

$st = $this->db->prepare("
    SELECT *
    FROM `sessions`
    WHERE DATE(sessionStart) = DATE_SUB(CURDATE(), INTERVAL :n DAY)
");

$bind = array(':n' => null);
$data = array();

foreach($days as $day){
    $bind[':n'] = $day;
    $st->execute($bind);
    $data[$day] = $st->rowCount();
}

Would my code perform better using either of these?

This code, which is essentially running 90 separate queries
Running one query to return everything from the sessions table and then sorting the results in PHP


texts: Need a better way to create subclass instances from a base class reference

texts:
FeatureMap contains features, derived classes have some mandatory features that the map should have, say keys (the mandatory part) are added and all the features are fetched from somewhere. Since clients interact with FeatureMap, a featuremap needs to be returned and the type is part of the actual object. Is there a better way to create instead of createFeatureMapWithMandatoryValues

import lombok.NonNull;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public abstract class FeatureMap {
    private Map<String, Object> features;
    public FeatureMap() {
        features = new HashMap<>();
    }
    void addFeature(@NonNull String name, @NonNull Object value) {
        features.put(name, value);
    }

    abstract FeatureMap createFeatureMapWithMandatoryValues(Map<String, Object> values);
}

class FoodFeatureMap extends FeatureMap {
    public static final String foodType = "foodType";

    public FoodFeatureMap(@NonNull String foodTypeValue) {
        addFeature(foodType, foodTypeValue);
    }

    @Override
    FeatureMap createFeatureMapWithMandatoryValues(Map<String, Object> values) {
        return new FoodFeatureMap((String) values.get(foodType));
    }
}

class HumanFeatureMap extends FeatureMap {
    public static final String name = "name";
    public static final String origin = "origin";

    public HumanFeatureMap(@NonNull String nameValue, @NonNull String originValue) {
        addFeature(name, nameValue);
        addFeature(origin, originValue);
    }

    @Override
    FeatureMap createFeatureMapWithMandatoryValues(Map<String, Object> values) {
        return new HumanFeatureMap((String)values.get(name), (String) values.get(origin));
    }
}

class Main {
    public static void main(String[] args) {
        FeatureMap featureMap = new FoodFeatureMap("Chinese");
        Map<String, Object> map = Collections.singletonMap(FoodFeatureMap.foodType, "Chinese");
        //assume this map contains more features fetched from somewhere given the earlier map having keys
        featureMap.createFeatureMapWithMandatoryValues(map);
    }
}


texts:
The main problem the following query is solving, is the following:

Each Offer has multiple Odds (Odds has foreignkey to Offer). For each offer I want the latest Odds (ORDER BY time).

I'm pretty sure this is too heavy, so any input would be great.

SELECT "odds_odds"."id", "odds_odds"."offer_id", "odds_odds"."time", "odds_odds"."o1", "odds_odds"."o2", "odds_odds"."o3", "odds_odds"."o4", MAX(T3."time") AS "max_time"
FROM "odds_odds"
LEFT OUTER JOIN "odds_offer" ON ( "odds_odds"."offer_id" = "odds_offer"."id" )
LEFT OUTER JOIN "odds_odds" T3 ON ( "odds_offer"."id" = T3."offer_id" )
GROUP BY "odds_odds"."id", "odds_odds"."offer_id", "odds_odds"."time", "odds_odds"."o1", "odds_odds"."o2", "odds_odds"."o3", "odds_odds"."o4"
HAVING "odds_odds"."time" =  MAX(T3."time")

This is constructed in Django using the following syntax:

Odds.objects.annotate(
    max_time=Max('offer__odds__time')
).filter(
    time=F('max_time')
)

This is my schema:

odds_offer
id (int), .....

odds_odds
id (int), time (datetime), offer_id(int), .....

Now what I want to retrieve The Odds row with the latest time for each Offer. There is a unique constraint on (time, offer_id). One Offer can have multiple odds (historic odds).


texts: using a cast in an overriden equals method should I use generics and if so, how?

texts:
here is my issue when trying to override my equals method.

this is what I have currently

 @Override
public boolean equals(Object o) {
 if (this.name.equals(((Animal) o).getName())) {
  System.out.println("True");
return true;
} else {
 System.out.println("False");
 return false;
 }

}

I'm trying to compare the names of objects which extend the Animal class is there a better way to create this equals method without the explicit casting to compare the names of each object?, I was messing around with Generics but just couldn't get it to work properly. below is what I attempted with generics but when I tried to pass an object in the parenthesis it was just using the super equals method. (The get method literally just returns the name)

public boolean equals(Class<? extends Animal>o) {
 if (this.name.equals(o.getName())) {
   System.out.println("True");
   return true;
} else {
   System.out.println("False");
   return false;
  }

}

any help is really appreciated.


texts:
I have a bunch of different ports I want to listen on and the iterate over the available data to send to a Dataflow pipeline. In total I'm listening on 14 ports. I'm looking for any advice on how to reduce the CPU usage of the following code.

I'm just passing in the ports to a method then adding them to a list:

   public static void AddPorts(Dictionary<int,string> ports)
{
    try
    {

            var NewEndPoints = new List<IPEndPoint>();
            foreach (var port in ports)
            {
                var endpoint = new IPEndPoint(IPAddress.Any, port.Key);
                NewEndPoints.Add(endpoint);
                if (!Endpoints.Contains(endpoint))
                {
                    Endpoints.Add(endpoint);
                    var client = new UdpClient(endpoint);
                    logger.Info("New Client added on port: {0}", endpoint.Port);
                    Clients.Add(client);

                }
                else
                {
                    if (IgnoredPorts.Contains(endpoint.Port))
                    {
                        logger.Info("Existing client enabled on port: {0}", endpoint.Port);
                        IgnoredPorts.Remove(port.Key);
                    }
                }
            }
            var differences = Endpoints.Except(NewEndPoints);
            differences.ToList().ForEach(d =>
            {
                if (!IgnoredPorts.Contains(d.Port))
                {
                    IgnoredPorts.Add(d.Port);
                    logger.Info("Client removed on port: {0}", d.Port);
                }
            });

    }
    catch (Exception ex)
    {
        logger.Error("Error creating udpclients", ex);
    }
}

I then iterate the sockets for any available data

 Task.Run(async delegate
    {

        while (Receive)
        {
            try
            {
                // get any channels that have data availble
                // Iterate over the the channels and send to Dataflow pipeline
                var readyChannels =
            (from channel in Clients
             where channel.Available > 0 && !ListenersDF.IgnoredPorts.Contains(((IPEndPoint)channel.Client.LocalEndPoint).Port)
             select channel);

                // Iterate over the the channels and send to Dataflow pipeline
                foreach (var channel in readyChannels)
                {
                    // await on the result of the task
                    await ReceiveAndRespond(channel);
                }

            }
            catch (Exception ex)
            {
                logger.Error("Error sending packet to bufferBlock", ex);
            }
        }
    });

And finally send it to the TPL Dataflow pipline

async Task ReceiveAndRespond(UdpClient channel)
{
    UdpReceiveResult? result = null;

    try
    {
        result = await channel.ReceiveAsync();
    }
    catch (Exception exc)
    {
        logger.Error("Error receiving from channel: " + exc.Message, exc);
    }

    if (result != null)
    {
        var device = (from d in Ports
                      where d.Key == ((IPEndPoint)channel.Client.LocalEndPoint).Port
                      select d.Value).FirstOrDefault();
        UdpData data = new UdpData() { Client = channel, Data = result.Value.Buffer, LocalPort = ((IPEndPoint)channel.Client.LocalEndPoint).Port, LocalIP = ((IPEndPoint)channel.Client.LocalEndPoint).Address, RemoteEndpoint = result.Value.RemoteEndPoint, Device = device };
        Flow.bufferBlock.Post(data);

        // for testing logs the hex string to a log file
        //logger.Warn(string.Format("Data received on port: {0} for device: {1} with data: {2}", data.LocalPort, data.Device, data.Data.ByteArrayToHexString()));
    }
}

Then CPU sits at 50% with hardly any traffic and I'm sure there is some performance to be gained just not sure where.


texts: Read Space Delimited Text File to Standardized Data Type

texts:
From the README.md
Introduction:
The purpose of data-in is to read all the lines from a text file and return the file's contents as a Clojure value in a standardized manner.
Specification:
Takes:

Filename

Assumes:

a space delimited text file

Returns:

Vector [L1,L2,...Ln] where Li:

represents a line in Filename
is a vector
contains EDN values

Example:
If my-file.txt contains:
3 9
5 4
6 5
3 2

then (data-in "./my-file.txt") returns:
[[3 9] [5 4] [6 5] [3 2]]
Comments:

To avoid executing arbitrary code, data-in reads values from files with clojure.edn/read-string.

The input is not read lazily. The assumption being that sorting or an equivalent operation will be performed. The basis for this assumption is the proximate use case: reading data files for Discreet Optimization @ Coursera.

The private function f is called f to match the argument f at the call site in the private function get-data. This reflects a personal preference for mathematical notation when invoking mathematical abstractions.

Code:
(ns data-in.core
  (:require [clojure.java.io :as io]
            [clojure.edn :as edn]))

(defn- get-data
  [data-file f]
  (with-open [rdr (clojure.java.io/reader data-file)]
        (doall (map f (line-seq rdr)))))

(defn- f
  [line]
  (vec (map (fn [x] (edn/read-string x))
            (clojure.string/split line #" "))))

(defn data-in
  [filename]
  (vec (get-data filename f)))


texts:
I find myself nesting a lot of grids inside grids in WPF. I just found myself 3 Grids deep, and stopped to think: "Should I be doing this?" Is there some kind of performance cost? Is it unmaintainable? (Kind of like heavily nested ifs maybe.)

I guess the alternative is to have one grid, and use a whole lot of column spans.

(You may ignore the use of Events, I am aware commands are prob a better idea)

<Grid Name="grid">
<Grid.ColumnDefinitions>
    <ColumnDefinition Width="*"/>
    <ColumnDefinition Width="*"/>
    <ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>

<Grid Grid.Column="1">
    <Grid.RowDefinitions>
        <RowDefinition Height="20"/>
        <RowDefinition/>
        <RowDefinition Height="20"/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
        <ColumnDefinition/>
        <ColumnDefinition/>
        <ColumnDefinition/>
    </Grid.ColumnDefinitions>

    <Button Grid.Row="0" Grid.Column="0" VerticalAlignment="Top"
        HorizontalAlignment="Left" Click="btnStart_Click"
        Content="New Game"/>
    <Button Grid.Row="0" Grid.Column="1" VerticalAlignment="Top"
        HorizontalAlignment="Center" Click="btnRun_Click"
        Content="Run"/>
    <Button Grid.Row="0" Grid.Column="2" VerticalAlignment="Top"
        HorizontalAlignment="Center" Click="btnUndo_Click"
        Content="Undo"/>
    <Button Grid.Row="0" Grid.Column="3" VerticalAlignment="Top"
        HorizontalAlignment="Right" Click="btnStep_Click"
        Content="Step"/>

    <Grid Grid.Row="1" Grid.ColumnSpan="4">
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <board:BoardView x:Name="boardView" Grid.Row="0"  Background="Firebrick"/>
        <GridSplitter  ResizeDirection="Rows" HorizontalAlignment="Stretch"
            VerticalAlignment="Bottom" />
        <TextBox Name="txtLog" Grid.Row="1"
            Text="{Binding Path=GameLog.Log, Mode=TwoWay}"
            VerticalScrollBarVisibility="Visible" FontFamily="Global Monospace"
            AcceptsReturn="True" Height="260" VerticalAlignment="Stretch"/>

    </Grid>

    <CheckBox Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="3"
        Content="Use Algebraic Notation"
        IsChecked="{Binding Path=UseAlgebraicNotation}"/>

</Grid>

<ContentControl Grid.Column="0"
                Content="{Binding Path=Game.BlackPlayer}"
                Margin="3"
                />

<ContentControl Grid.Column="3"
                Content="{Binding Path=Game.WhitePlayer}"
                Margin="3"
                />

</Grid>


texts: Parser for STL stereolithography data files

texts:
I'm parsing STL files to load the coordinates. My code is:

void Importer::scanFileSTL_ASCII(
    QVector<QVector3D> &vertices, // Coordinates to be filled
    const QUrl &url)
{
    QFile file;
    file.setFileName(url.toLocalFile());
    if (!file.open(QIODevice::OpenModeFlag::ReadOnly | QIODevice::OpenModeFlag::Text))
        return;

    while (!file.atEnd()) {
        QByteArray line_BA = file.readLine();
        QString line = QString::fromLatin1(line_BA);
        // Split line by spaces
        QStringList words = line.split(QRegExp("\\s+"), QString::SkipEmptyParts);
        if (words.isEmpty())
            continue; // Skip this line and jump to next iteration/line
        if (words[0] == "vertex") {
            assert (words.length() == 4 && "STL file format is wrong: vertex-line must have 4 strings");
            float x = words[1].toFloat();
            float y = words[2].toFloat();
            float z = words[3].toFloat();
            vertices.append(QVector3D(x, y, z));
        }
    }

    return;
}

The code is tested, it works fine. But it is by far slower than the STL loader of asset import library. More accurate comparisons in release mode:

Import of a 13MB ASCII STL file:

Assimp library: 03.58 seconds
Our code: 04.70 seconds

Import of 287MB ASCII STL file:

Assimp library: 05.72 seconds
Our code: 44.19 seconds

I wonder if something is noticeably wrong with my code. Thanks.


texts: Deck and Card classes and member-accessing with one header

texts:
Previous review of this project:

Card Deck class for a Poker game - version 2

This time, I considered combining both classes into one header file so that I can reduce my use of #include and to keep them together.  I also did this so that I can define my const std::string variables only once for both classes.  However, I decided to try using a namespace for these variables for easier access.  It makes more sense (to me) to keep them with Card and let Deck refer to them during the latter's construction, but I'm not sure how to do that.

Is this the proper thing to do, or could something be done differently?  Is there a need for extern somewhere?  The code below doesn't include class implementations, but I've kept them intact from the linked code.

Deck.h

#ifndef DECK_H
#define DECK_H

#include <iostream>
#include <string>
#include <array>

namespace rs
{
    const std::string RANKS = "A23456789TJQK";
    const std::string SUITS = "HDCS";
}

class Card
{
private:
    unsigned rankValue;
    char rank;
    char suit;

public:
    Card();
    Card(char r, char s);
    bool operator<(const Card &rhs) const {return (rankValue < rhs.rankValue);}
    bool operator>(const Card &rhs) const {return (rankValue > rhs.rankValue);}
    bool operator==(const Card &rhs) const {return (suit == rhs.suit);}
    bool operator!=(const Card &rhs) const {return (suit != rhs.suit);}
    friend std::ostream& operator<<(std::ostream &out, const Card &aCard)
        {return out << '[' << aCard.rank << aCard.suit << ']';}
};

class Deck
{
private:
    static const unsigned MAX_SIZE = 52;
    std::array<Card, MAX_SIZE> cards;
    int topCardPos;

public:
    Deck();
    void shuffle();
    Card deal();
    unsigned size() const {return topCardPos+1;}
    bool empty() const {return topCardPos == -1;}
    friend std::ostream& operator<<(std::ostream &out, const Deck &aDeck);
};

#endif


texts:
I have the following code, but I don't know how to make it run faster.

SELECT lot.order as lot_order,
    lot.title as lot_title,
    lot.id as lot_id,
    lot.id_auction,
    IF (
        (SELECT bid
            FROM bid
            WHERE lot.id = bid.id_lot
            ORDER BY bid.date DESC
            LIMIT 0,1) > lot.bid_minimum,
        (SELECT bid
            FROM bid
            WHERE lot.id = bid.id_lot
            ORDER BY bid.date DESC
            LIMIT 0,1),
        lot.bid_minimum
    ) AS bid,
    youtube,
    (SELECT path_image
        FROM lot_album
        WHERE lot_album.id_lot = lot.id
        AND order = 1) as image_featured
FROM lot
WHERE lot.excluded <> 1
AND lot.id_auction = 42
ORDER BY lot.order ASC

As you can see, I have the IF to check if the value of the select is > bid.minimum. The only way to improve this is check it on the programming language (PHP/.NET...) or there is another way?

"lot_album" is a table where you can have lots of images, but also
none. But only one image per lot will have order 1 so that image will
be the "image_featured".


texts:
I want to ask you if my PHP code is safe enough. I don't know if I should escape special characters in string after regex validation:

<?php

require_once '../../../wp-load.php';

$errors = [];

if (preg_match('/[^a-ząćęółśżźń ]/i', $_POST['name']) || strlen(trim($_POST['name'])) == 0 || strlen($_POST['name']) > 60) {
    $errors[] = "Invalid name";
}

if (empty($errors)) {
    echo json_encode(['status' => true]);
    $wpdb->query($wpdb->prepare("INSERT INTO people VALUES(null, %s)", $_POST['name']));
} else {
    echo json_encode(['status' => false, 'errors' => $errors]);
}

And what if i use PDO prepare instead of wordpress function?


texts:
Is there a better way to do what I'm doing? If not, I'd like just a general review of how I did it and the usability of it (how it works and functions, not artistically how it looks).

Here is the working JSFiddle.

JavaScript

$(document).ready(function () {
    // initlize panels
    $('.panel').each(function (i) {
        var $tab = $(this).children('.tab');
        $tab.css({ 'top': $tab.position().top + i * ($tab.height() + 5) });
    });
    $('.tab').click(function () {
        var $panel = $(this).parent();
        if ($panel.attr('data-open') == 'yes') {
            $panel.animate({
                left: '-=300'
            }, 1000, function () {
                // Animation complete.
            });
            $panel.attr('data-open', 'no');
        } else {
            $('.panel').css({ 'z-index': 0 });
            $panel.css({ 'z-index': 1 });
            $panel.animate({
                left: '+=300'
            }, 1000, function () {
                // Animation complete.
            });
            $panel.attr('data-open', 'yes');
        }
    });
});

CSS

body
{
    margin: 0px;
    padding: 0px;
    font-family: Arial;
}
.panel
{
    position:absolute;
    top: 0px;
    bottom: 0px;
    left: -300px;
    width: 299px;
    border-right: 1px solid black;
    background-color: White;
}

.tab
{
    position: absolute;
    top: 10px;
    width: 16px;
    right: -17px;
    height: 75px;
    border-top: 1px solid black;
    border-bottom: 1px solid black;
    border-right: 1px solid black;
    cursor: pointer;
    background-color: White;
}

.tab div
{
    position: relative;
    display: block;
    left: 1px;
    top: -15px; /* Same as height */
    width: 75px; /* Same as .tab height */
    height: 15px;
    font-size: 14px;
    font-weight:normal;
    line-height: 15px;
    text-align: center;
    -moz-transform:rotate(-270deg);
    -moz-transform-origin: bottom left;
    -webkit-transform: rotate(-270deg);
    -webkit-transform-origin: bottom left;
    -o-transform: rotate(-270deg);
    -o-transform-origin:  bottom left;
    filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=1);
    vertical-align: top;
}

CSS - in an IE-only CSS file

.tab div
{
    top: 0;
}

HTML

Tab A

Tab B

Tab C

Tab D


texts:
i have solved this problem https://leetcode.com/problems/find-eventual-safe-states/submissions/

import scala.collection.mutable

object Solution {
  def eventualSafeNodes(graph: Array[Array[Int]]): List[Int] = {
    val seen = mutable.HashSet[Int]()
    val safeNodes = mutable.ArrayBuffer[Int]()

    val  color_of = mutable.HashMap[Int, Int]().withDefaultValue(0)

    def is_safe(node: Int): Boolean = {
      color_of(node) = 1
      for (neb <- graph(node)) {
        if (color_of(neb) == 1) {
          return false;
        } else if (color_of(neb) == 0) {
          if (!is_safe(neb)) {
            return false;
          }
        }
      }
      color_of(node) = 2
      return true
    }
    for (i <- 0 until graph.size) {
      if (color_of(i) == 2) {
        safeNodes.append(i)
      } else if (color_of(i) == 0) {
        if (is_safe(i)) {
          safeNodes.append(i)
        }
      }
    }
    return safeNodes.toList
  }
}

I would love some pointers on idiomatic code!


texts: Determining the number of days from today

texts:
Today I've got a pretty simple snippet to be reviewed. The function is extremely simple, as all it does is retrieve some entities from Core Data and then compares the dueDate attribute to today. I'm here asking about two questions:

Is this code reliable?
Is this the most efficient way (less lines of code) to accomplish this task?

The output will be separated into different arrays as seen by the comments inside the various if statements. The categories include:

Greater than One Month
One Month
One Week
Tomorrow
Today

func fetchAssignments() {

    let appDelegate =
    UIApplication.sharedApplication().delegate as! AppDelegate

    let managedContext = appDelegate.managedObjectContext!

    let fetchRequest = NSFetchRequest(entityName:"Assignment")

    var error: NSError?

    let fetchedResults =
    managedContext.executeFetchRequest(fetchRequest,
    error: &error) as! [NSManagedObject]?

    if let results = fetchedResults {
        for item in results {
            let dueDate = item.valueForKey("dueDate") as! NSDate
            let todayDate = NSDate()

            let calendar: NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
            let calendarComponents: NSDateComponents = calendar.components(NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitDay, fromDate: todayDate, toDate: dueDate, options: .allZeros)
            println("Days: " + calendarComponents.day.description + " Months: " + calendarComponents.month.description)
            if calendarComponents.month > 0 && calendarComponents.day > 0 {
                // Greater Than One Month
                return
            } else if calendarComponents.day > 7 {
                // One Month
                return
            } else if calendarComponents.day > 1 {
                // One Week
                return
            } else if calendarComponents.day == 1 {
                // Tomorrow
                return
            } else {
                // Today
                return
            }
        }
    } else {
        println("Could not fetch \(error), \(error!.userInfo)")
    }
}


texts:
This code is actually pretty basic. Basically, I'm doing a large number of web calls. I currently do up to 3 Web Service calls simultaneously, one of which is below.

There were 3 errors I saw in testing: Bad Gateway, Gateway Timeout, and basically "Couldn't establish a secure connection" (not the exact error text). In each case, a single retry appears to have fixed the issue.

"Bad Gateway" and "Gateway Timeout" didn't result in an exception, but "Couldn't establish a secure connection" did.

If I get either of the first two errors, it'll wait 2 seconds and try again. If it still didn't work, it tries 7 seconds and tries again. After that, it "gives up" and just returns null. (I've never seen that happen in testing, and I've never even gotten to the second retry). The 2-second and 7-second delays are somewhat arbitrary.

The code is below:

public static async Task<Job> GetJob(string id)
{
    int attempts = 1;

    tryAgain:

    string jobJson;

    try
    {
        using (HttpClient client = HttpClientConstructor.GetHttpClient(false, "application/json"))
        {
            HttpResponseMessage response = await client.GetAsync("jobs/" + id);

            if (!response.IsSuccessStatusCode)
            {
                switch (response.StatusCode)
                {
                    case HttpStatusCode.BadGateway:
                    case HttpStatusCode.GatewayTimeout:
                        await Task.Delay(2000);
                        response = await client.GetAsync("jobs/" + id);

                        if (response.StatusCode == HttpStatusCode.BadGateway || response.StatusCode == HttpStatusCode.GatewayTimeout)
                        {
                            await Task.Delay(7000);
                            response = await client.GetAsync("jobs/" + id);
                        }
                        break;
                }

                if (!response.IsSuccessStatusCode)
                {
                    string errorMessage = "Failed I have. Reason: " + response.ReasonPhrase;
                    Console.WriteLine(errorMessage);

                    System.Diagnostics.Trace.TraceError(errorMessage);

                    // If multiple retries couldn't get it, just give up
                    return null;
                }
            }

            jobJson = await response.Content.ReadAsStringAsync();
        }

        Job job = JsonConvert.DeserializeObject<Job>(jobJson);

        return job;
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());

        System.Diagnostics.Trace.TraceError(e.ToString());

        // Go for two retries
        // This actually worked in my testing
        // In the rare case where I got exceptions, a retry worked
        if (attempts <= 3)
        {
            attempts++;

            // Is goto evil here?
            goto tryAgain;
        }

        return null;
    }
}

Obviously, this will be running asynchronously. As mentioned above, I will run up to 3 calls at once. It's fixed at 3 to avoid being "throttled" by rate limits on the API.

Is this a good way to solve this?

Could this code be improved?


texts:
My converter converts all CSV files in the subfolders of folders 1, 2 & 3 into Excel workbooks. As of now, I am converting using codes for each folders. I previously tried to combine those into one using for loop, but an error occurred, so I've rolled back to the working code I had before the loop.

Can anyone show me how to clean this up with a loop or another method?

Private Sub CommandButton1_Click()

 Dim CSVfolder As String, CSVfolder1 As String, CSVfolder2 As String
 Dim fname, fname1, fname2 As String
 Dim wBook As Workbook
 Dim colSF As Collection
 Dim vFile, vFile1, vFile2
 Dim bHadFiles As Boolean
 CSVfolder = "C:\Charts\1\"
 CSVfolder1 = "C:\Charts\2\"
 CSVfolder2 = "C:\Charts\3\"

 Set colSF = GetSubFolders(CSVfolder)
 For Each vFile In colSF
 fname = Dir(CSVfolder & vFile & "\" & "*.csv")
 Do While fname <> ""
    bHadFiles = True
    Application.ScreenUpdating = False
    Set wBook = Workbooks.Open(CSVfolder & vFile & "\" & fname, Format:=6, Delimiter:=",")
    wBook.SaveAs CSVFolder & vFile & "\" & Replace(fname, ".csv", ""), xlOpenXMLWorkbook
    Application.CutCopyMode = False
    wBook.Close False
 fname = Dir()
 Loop
 If bHadFiles Then Kill CSVfolder & vFile & "\" & "*.csv"
 Next

Set colSF = GetSubFolders(CSVfolder1)
For Each vFile1 In colSF
fname1 = Dir(CSVfolder1 & vFile1 & "\" & "*.csv")
Do While fname1 <> ""
    bHadFiles = True
    Application.ScreenUpdating = False
    Set wBook = Workbooks.Open(CSVfolder1 & vFile1 & "\" & fname1, Format:=6, Delimiter:=",")
    wBook.SaveAs CSVFolder1 & vFile1 & "\" & Replace(fname1, ".csv", ""), xlOpenXMLWorkbook
    Application.CutCopyMode = False
    wBook.Close False
fname1 = Dir()
 Loop
 If bHadFiles Then Kill CSVfolder1 & vFile1 & "\" & "*.csv"
 Next

Set colSF = GetSubFolders(CSVfolder2)
For Each vFile2 In colSF
fname2 = Dir(CSVfolder2 & vFile2 & "\" & "*.csv")
Do While fname2 <> ""
    Application.ScreenUpdating = False
    Set wBook = Workbooks.Open(CSVfolder2 & vFile2 & "\" & fname2, Format:=6, Delimiter:=",")
    wBook.SaveAs CSVFolder2 & vFile2 & "\" & Replace(fname2, ".csv", ""), xlOpenXMLWorkbook
    Application.CutCopyMode = False
    wBook.Close False
 fname2 = Dir()
 Loop
 If bHadFiles Then Kill CSVfolder2 & vFile2 & "\" & "*.csv"
 Next
 Application.ScreenUpdating = True
 End Sub

Function GetSubFolders(sPath As String) As Collection
    Dim col As New Collection, f
    f = Dir(sPath, vbDirectory + vbNormal)
    Do While f <> ""
        If GetAttr(sPath & f) And vbDirectory Then
            If f <> "." And f <> ".." Then col.Add f
        End If
        f = Dir()
    Loop
    Set GetSubFolders = col
End Function


texts: Tight coupling in using call back method

texts:
I am using below code and for result i am using interface for call back purposes.

@Override
public void onResult(String result) {

    if (this.mClient != null) {
        this.mClient.cancel();
        mProcessing = false;
    }

    try {
        JSONObject j = new JSONObject(result);
        JSONObject j1 = j.getJSONObject("status");
        int j2 = j1.getInt("code");
        if (j2 == 0) {
            JSONObject metadata = j.getJSONObject("metadata");
            //
            if (metadata.has("humming")) {
                JSONArray hummings = metadata.getJSONArray("humming");
                for (int i = 0; i < hummings.length(); i++) {
                    JSONObject tt = (JSONObject) hummings.get(i);
                    String title = tt.getString("title");
                    JSONArray artistt = tt.getJSONArray("artists");
                    JSONObject art = (JSONObject) artistt.get(0);
                    String artist = art.getString("name");
                    tres = tres + (i + 1) + ".  Title: " + title + "    Artist: " + artist + "\n";
                }
            }
            if (metadata.has("music")) {
                JSONArray musics = metadata.getJSONArray("music");
                for (int i = 0; i < musics.length(); i++) {
                    JSONObject tt = (JSONObject) musics.get(i);
                    String title = tt.getString("title");
                    JSONArray artistt = tt.getJSONArray("artists");
                    JSONObject art = (JSONObject) artistt.get(0);
                    String artist = art.getString("name");
                    tres = tres + (i + 1) + ".  Title: " + title + "    Artist: " + artist + "\n";
                }
            }
            if (metadata.has("streams")) {
                JSONArray musics = metadata.getJSONArray("streams");
                for (int i = 0; i < musics.length(); i++) {
                    JSONObject tt = (JSONObject) musics.get(i);
                    String title = tt.getString("title");
                    JSONArray channelId = tt.getJSONArray("channel_id");
                    tres = tres + (i + 1) + ".  Title: " + title + "    Channel Id: " + channelId + "\n";
                }
            }
            if (metadata.has("custom_files")) {
                JSONArray musics = metadata.getJSONArray("custom_files");
                for (int i = 0; i < musics.length(); i++) {
                    JSONObject tt = (JSONObject) musics.get(i);
                    String title = tt.getString("title");
                    //tres = tres + (i + 1) + ".  Title: " + title + "\n";
                    tres = tt.getString("acr_id");
                }
            }
            //tres = tres + "\n\n" + result;
            if (baseClass instanceof MainActivity)
                ((MainActivity) baseClass).onResultFound(tres);
        } else {
            tres = result;
            if (baseClass instanceof MainActivity)
                ((MainActivity) baseClass).onResultNotFound(tres);
        }

    } catch (JSONException e) {
        tres = result;
        e.printStackTrace();
        if (baseClass instanceof MainActivity)
            ((MainActivity) baseClass).onErrorFound(tres);
    }

    //mResult.setText(tres);

}

My question is that is it the right way of coding to give call back or it causes tight coupling issue using below code.

if (baseClass instanceof MainActivity)
            ((MainActivity) baseClass).onResultNotFound(tres);

Interface:

public interface IResultListener {

    /*
    * This is call back listener when acr starts recognition sound of audio/video
    * and methods are available according to result
    * */

    // result found successfully
    void onResultFound(String result);

    // result not found
    void onResultNotFound(String result);

    // some exception occurred
    void onErrorFound(String result);
}


texts: C binary number converter (Hex and Decimals)

texts:
I'm still new to C programming, but I'm playing around with it to ensure I progress. I just made the following converter that takes 8 numbers (0 and 1) as binary code then converts the binary value to decimal and hex values. Below is the full code.

Aside from perhaps adding loops to make my code less redundant (especially the printf() statements), is there something I could do to make my code look more professional.

#include <stdio.h>
#include <math.h>

int main() {
int b1, b2, b3, b4, b5, b6, b7, b8, decimal, hex1, hex2;
char convert1, convert2;

printf("Please enter the 1st bit of your binary number (0 or 1): ");
scanf("%i", &b1);

printf("Please enter the 2nd bit of your binary number (0 or 1) ");
scanf("%i", &b2);

printf("Please enter the 3rd bit of your binary number (0 or 1) ");
scanf("%i", &b3);

printf("Please enter the 4th bit of your binary number (0 or 1) ");
scanf("%i", &b4);

printf("Please enter the 5th bit of your binary number (0 or 1) ");
scanf("%i", &b5);

printf("Please enter the 6th bit of your binary number (0 or 1) ");
scanf("%i", &b6);

printf("Please enter the 7th bit of your binary number (0 or 1) ");
scanf("%i", &b7);

printf("Please enter the 8th bit of your binary number (0 or 1) ");
scanf("%i", &b8);

decimal = b1 * pow(2,7) + b2 * pow(2,6) + b3 * pow(2,5) + b4 * pow(2,4) + b5 * pow(2,3) + b6 * pow(2,2) + b7 * pow(2,1) + b8 * pow(2,0);

hex1 = b1 * 8 + b2 * 4 + b3 * 2 + b4 * 1;
hex2 = b5 * 8 + b6 * 4 + b7 * 2 + b8 * 1;

switch(hex1) {
case 10:
    convert1 = 'A';
    break;
case 11:
    convert1 = 'B';
    break;
case 12:
    convert1 = 'C';
    break;
case 13:
    convert1 = 'D';
    break;
case 14:
    convert1 = 'E';
    break;
case 15:
    convert1 = 'F';
    break;
}

switch(hex2) {
case 10:
    convert2 = 'A';
    break;
case 11:
    convert2 = 'B';
    break;
case 12:
    convert2 = 'C';
    break;
case 13:
    convert2 = 'D';
    break;
case 14:
    convert2 = 'E';
    break;
case 15:
    convert2 = 'F';
    break;
}

printf("\nThe decimal value of your binary number is %i\n\n", decimal);
printf("The hexadecimal value of your binary number is: ");
if(hex1 >= 10 && hex2 < 10) {
    printf("%c%i\n", convert1, hex2);
}
else if (hex1 <10 && hex2 >= 10) {
    printf("%i%c\n", hex1, convert2);
}
else if (hex1 >= 10 && hex2 >=10) {
    printf("%c%c\n", convert1, convert2);
}
else {
    printf("%i%i\n", hex1, hex2);
}

return 0;
}


texts:
Wrote a simple script to implement Linear regression and practice numpy/pandas. Uses random data, so obviously weights (thetas) have no significant meaning. Looking for feedback on

Performance
Python code style
Machine Learning code style

# Performs Linear Regression (from scratch) using randomized data
# Optimizes weights by using Gradient Descent Algorithm

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

np.random.seed(0)

features = 3
trainingSize = 10 ** 1
trainingSteps = 10 ** 3
learningRate = 10 ** -2

randData = np.random.rand(trainingSize, features + 1)
colNames = [f'feature{i}' for i in range(1, features + 1)]
colNames.append('labels')

dummy_column = pd.Series(np.ones(trainingSize), name='f0')
df = pd.DataFrame(randData, columns=colNames)

X = pd.concat([dummy_column, df.drop(columns='labels')], axis=1)
y = df['labels']
thetas = np.random.rand(features + 1)

cost = lambda thetas: np.mean((np.matmul(X, thetas) - y) ** 2) / 2
dJdtheta = lambda thetas, k: np.mean((np.matmul(X, thetas) - y) * X.iloc[:, k])
gradient = lambda thetas: np.array([dJdtheta(thetas, k) for k in range(X.shape[1])])

# J(theta) before gradient descent
print(cost(thetas))

# Perform gradient descent
errors = np.zeros(trainingSteps)
for step in range(trainingSteps):
    thetas -= learningRate * gradient(thetas)
    errors[step] = cost(thetas)

# J(theta) after gradient descent
print(cost(thetas))

# Plots Cost function as gradient descent runs
plt.plot(errors)
plt.xlabel('Training Steps')
plt.ylabel('Cost Function')
plt.show()


texts: Effective & Secure Method to populate Access Token for authorization header in Rest Template

texts:
I am trying to consume a REST endpoint by using the RestTemplate Library provided by the spring framework.
The endpoint also demands a Bearer Access Token as its authorization header, which is only obtained as the response from a user authentication endpoint, which in turn expects an encoded Basic Auth in its Header.

This is the high-level implementation that I have done thus far.

HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    headers.setBearerAuth(fetchAccessToken());
    HttpEntity<String> entity = new HttpEntity<String>("parameters",headers);
    ResponseEntity<?> result = this.restClient.exchange(urlToConsume, HttpMethod.GET, entity, String.class);

The 'fetchAccessToken' Method is implemented as follows

HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    headers.setBasicAuth(externalDestination.getClientId(),
            externalDestination.getClientSecret());
    HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);

    ResponseEntity<?> result = restClient.exchange(authUrl, HttpMethod.GET, entity, String.class);
    //And Thereby fetching 'access_token' from the successful fetch.

I Want to know whether there is any cleaner way to replicate the above task of dealing with multiple Rest calls to accomplish a single task.
Also, I want to know whether I am missing out any essential validations from a security point of view.