texts: Is this a correct recursive Scala iterator creation?

texts:
I am diving into Scala (using 2.10) headfirst and am trying out a simple task of taking bulk data and then doing something with that stream. The first part is generating that stream. I have seem to be able to cobble together what seems to work, but I think I am missing shortcuts in scala. Any pointers or code cleanup recommendations are welcome! I feel like getInnerPolygons could be simplified using a match statement, but I haven't gotten my head around those yet.

So, the process: With gdal, you retrieve a dataset, then retrieve the layer. From the layer, you can iterate over the features. From those features, you can get the geometries from each feature. Now, most features are just one polygon. If it is, take the outer ring of that polygon and pass it up the line. If the polygon is multi-part (think the hawaii islands as one "feature" where each island is a polygon), retrieve the polygons, then split that into their individual outer rings (this is that recursive call into getInnerPolygons).

Again: any Scala best practices or shortcuts that I missed. I would love to hear about.

def getInnerPolygons(geometry: Geometry) : Iterator[Geometry] = {
    Iterator
        .range(0,geometry.GetGeometryCount())
        .flatMap(i=>{
            val innerGeometry = geometry.GetGeometryRef(i)
            if(innerGeometry.GetGeometryName().equals("LINEARRING"))
                Iterator.single(innerGeometry)
            else
                getInnerPolygons(innerGeometry)
       })
}

def getPolygons(layer : Layer) : Iterator[Geometry] = {
    Iterator.continually[Feature](layer.GetNextFeature())
        .takeWhile(_!=null)
        .flatMap(feature=>getInnerPolygons(feature.GetGeometryRef()))
}

def main(args: Array[String]){
    ogr.RegisterAll()

    val dataSet = ogr.Open("myshapefile.shp")
    val layer = dataSet.GetLayer(0)

    for(i <- getPolygons(layer)) println(i.GetGeometryName())

    println("Done")
}


texts: Selection and Insertion sorts from scratch in Java

texts:
I am trying to find a good, basic way to make selection and insertion sorts so that I can manipulate them for other sorting techniques. How do these look? Is there a simpler way to write them?

package javaapplication59;

public class JavaApplication59 {

public static void main(String[] args) {
    selectionSort ss = new selectionSort();
    insertionSort is = new insertionSort();
    int[] arr = {2, 3, 4, 65, 6, 7, 3, 45, 56, 23, 34, 5, 4, 34, 6, 2, 57, 4, 45, 345};
    arr = is.sort(arr);
    System.out.print("{");
    for (int el : arr) {
        System.out.print(el + ",");
    }
    System.out.println("\b}");
}

}

class insertionSort {

public int[] sort(int[] a) {
    int insrt, j;
    boolean keepGoing;
    for (int i = 1; i < a.length; i++) {
        insrt = a[i];
        j = i - 1;
        keepGoing = true;
        while ((j >= 0) && keepGoing) {
            if(insrt<a[j]){
                a[j+1] = a[j];
                j--;
                if(j==-1)
                    a[0] = insrt;
            }
            else{
                keepGoing = false;
                a[j+1] = insrt;
            }

        }

    }
    return a;
}

}

class selectionSort {

public int[] sort(int[] arr) {
    int min, minIndex;
    for (int i = 0; i < arr.length; i++) {
        min = arr[i];
        minIndex = i;
        for (int j = i + 1; j < arr.length; j++) {
            if (arr[j] < min) {
                min = arr[j];
                minIndex = j;
            }
        }
        arr[minIndex] = arr[i];
        arr[i] = min;
    }
    return arr;
}

}


texts:
I have attempted to a zebra puzzle in prolog and I was seeking some feedback as to the way I went about solving the puzzle.

Here is the puzzle:

  Two weeks ago, four enthusiasts made sightings of objects in the sky
  in their    neighborhood. Each of the four reported his or her
  sightings on a different day. The FBI came and was able to give each
  person a different explanation of what he or she had "really" seen.
  Can you determine the day (Tuesday through Friday) each person sighted
  the object, as well as the object that it turned out to be?

  Mr. K made his sighting at some point earlier in the week than the one who saw the balloon, but at some point later in the week, than the
  one who spotted the Kite (who isn't Ms. G).
  Friday's sighting was made by either Ms. Barn or the one who saw a plane (or both).
  Mr. Nik did not make his sighting on Tuesday.
  Mr. K isn't the one whose object turned out to be a telephone pole.

Here is a representation of how I found the solution to the problem:

I know K didn't spot the balloon (1) or the kite (2) or the telephone pole (6), so K spotted the plane. Also, K's day can't be Friday (1), so Friday was B's day (4).

I also know the kite wasn't spotted by K (2) or G (3). Nor was it spotted by B, since B's day was Friday and the kite can't have been spotted on Friday (2). So N spotted the kite. Also, we know kite day is two days before balloon day (1,2), so kite day must have been Tuesday or Wednesday; but N's day wasn't Tuesday (5), so kite day was Wednesday, which means K's day was Thursday (2) and balloon day was Friday (1).

And the rest I got by elimination. Summing up:

G spotted a telephone pole on Tuesday.
N spotted a kite on Wednesday.
K spotted a plane on Thursday.
B spotted a balloon on Friday.

And here is my prolog code:

before(X,Y,Ds) :-
    remainder(X,Ds,Rs),
    member(Y,Rs).

remainder(X,[X|Ds],Ds).
remainder(X,[_|Ds],Rs) :- remainder(X,Ds,Rs).

members([],_).
members([X|Xs],Ds) :-
member(X,Ds),
members(Xs,Ds).

puzzle :-
Days = [[tuesday,_,_],[wednesday,_,_],[thursday,_,_],[friday,_,_]],
before([_,mr_klien,_],[_,_,balloon],Days),
before([_,_,frisbee],[_,mr_klien,_],Days),
(member([friday,ms_barnum,_],Days);
    member([friday,_,clothesline],Days);
    member([friday,ms_barnum,clothesline],Days)),
members([[_,mr_klien,_],[_,ms_barnum,_],[_,ms_green,_],[_,mr_niven,_]],Days),
members([[_,_,balloon],[_,_,frisbee],[_,_,clothesline], [_,_,water_tower]],Days),
member([_,NOT_ms_green,frisbee],Days), NOT_ms_green \= ms_green,
member([tuesday,NOT_mr_niven,_],Days), NOT_mr_niven \= mr_niven,
member([_,NOT_mr_klien,water_tower],Days), NOT_mr_klien \= mr_klien,
write(Days),
nl,
fail.


texts:
For my application, I've opted to use Integrated Security with Windows Authentication to access the SQL database. I've created AD security groups for each role and given them GRANT permissions on the tables and views they need to do their job.

To further keep the end users from getting to the controls I'm checking the SQL permissions using HAS_PERMS_BY_NAME() and then disabling the relevant controls.

In a static class, I have defined astatic method to get a dictionary of permissions.

namespace PartDataManager
{
    public static class Globals
    {
        public static Dictionary<string,bool> GetPermissions()
        {
            Dictionary<string,bool> Permissions = new Dictionary<string,bool>();
            string query = "SELECT \r\n";
            foreach( string table in new string[]{"appearance","appearanceSpecs","cutTemplates","cutVinyl"} )
            {
                foreach( string perm in new string[]{"INSERT","UPDATE","DELETE"} )
                {
                    query += String.Format("\t{0}HAS_PERMS_BY_NAME('{1}','OBJECT','{2}') AS {1}_{2}\r\n",(query.Length>10?",":""),table,perm);
                }
            }
            try
            {
                using( SqlConnection sql = new SqlConnection(ConnectionString) )
                using( SqlCommand cmd = new SqlCommand(query,sql) )
                {
                    sql.Open();
                    using( SqlDataReader data = cmd.ExecuteReader() )
                    {
                        data.Read();
                        for( int i = 0; i < data.FieldCount; i++ )
                            Permissions.Add(data.GetName(i), data[i].Equals(1));
                    }
                }
            }
            catch
            {
                throw;
            }
            return Permissions;
        }

        // ...

    }
}

I then use the method on loading of the form to disable the relevant controls like so (wrapped in a try... catch)...

Dictionary<string, bool> Permissions = Globals.GetPermissions();
tsmiNewApprSpec.Enabled = Permissions["appearance_INSERT"];
tsmiNewCutTemplate.Enabled = Permissions["cutTemplates_INSERT"];
tsmiEditAppr.Enabled = Permissions["appearance_UPDATE"];
//...

Is this a solid approach to handling security? Is there room for improvement without increasing complexity?

Note: When I write code, I like to do things in as few lines as possible. I have a horrible memory, so when I go back and look at it, it's like I've never seen it before and I like to be able to see a significant chunk without scrolling, or matching braces, and be able to quickly tell what it does. So, any tips that reduce lines of code will definitely be appreciated and rewarded!


texts: P5 Isothermic Map Generator From Data Points

texts:
In my earth science class at school we had a lab where we went around the campus measuring the temperature at different place and marking it on a map. Afterword we were told to color the map using different colors for different temperatures like this:

~Isothermic map

As you can see there is never a jump that skips one of the temperature colors, if you have a data point of 30 near one of 32 you have to show whatever color 31 is between them. I asked the teacher if I could write some code where I can input the points and generate the map instead and they said yes. I wrote this in P5.js:

var dataPoints = [];
var num = 0;
var tempSlider;
var num2 = 0;
var num3 = 0;
var temps = [];
var load = false;
var text;

function setup() {
  createCanvas(500, 500);
  background(255);
  tempSlider = createSlider(32, 50, 40);
  tempSlider.position(20,20);
}

function draw() {
  clear();
  stroke(0);
  fill(0);
  line(0,0,width-1,0);
  line(0,height-1,width-1,height-1);
  line(0,0,0,height);
  line(width-1,0,width-1,height-1);
  textSize(20);
  text(tempSlider.value(),0,20);
  if(load==false){
  for (var i = 0; i < dataPoints.length; i++) {
    dataPoints[i].display();
  }
  }else{
  drawPixels();
  }
}

function mousePressed () {
  if(load == false){
  if(mouseX>170 || mouseY>55){
    dataPoints[num] = {
      x: mouseX,
      y: mouseY,
      temp: tempSlider.value(),
      display: function() {
        stroke(0+(((this.temp-32)/18))*255, 0, 255-(((this.temp-32)/18))*255);
        fill(0+(((this.temp-32)/18))*255, 0, 255-(((this.temp-32)/18))*255);
        ellipse(this.x, this.y, 5, 5);
      }
    }
  num++;
  }
  }
}

function keyPressed () {
  if(keyCode == ENTER){
    updateTemp();
    load = true;
  }
}

function updateTemp (){
  for(var y = 0; y < height; y++){
    for(var x = 0; x < width; x++){
      var posTemps = [];
      for(var j = 0; j < dataPoints.length; j++){
        var distance = sqrt((x-dataPoints[j].x**2)+(y-dataPoints[j].y**2));
        if(distance <=100){
          var impact = (100 - distance)/100;
          posTemps[num2] = impact*dataPoints[j].temp;
          num2++;
        }
      }
      for(var i = 0; i<posTemps.length; i++){
        temps[num3]+= posTemps[i];
      }
      temps[num3] = temps[num3]/posTemps.length;
      num3++;
    }
  }
}

function drawPixels (){
  for(var i = 0; i<temps.length; i++){
    stroke(0+(((temps[i]-32)/18))*255, 0, 255-(((temps[i]-32)/18))*255);
    fill(0+(((temps[i]-32)/18))*255, 0, 255-(((temps[i]-32)/18))*255);
    point(i%width,(i-(i%width))%height);
  }
}

The problem with this code is all those for loops, when I try running the program it works and I can input the points but the moment I press enter the tab either crashes or very slowly draws the first line of pixels then freezes.

If you want to run the code

So if anyone knows some other way of drawing the pixels that I can use that might be faster that would be great. Also other problems you find in the code would also be helpful to know about.


texts:
I have the following but it takes long time to run, it is a simple wherein the user select a file and data from Sheet1 is copied to another workbook.

Sub ImportApp(ByVal filepath_Report As String, file_name1 As String, wsOutput As Worksheet)
    Application.ScreenUpdating = False
    Set wbReport = Workbooks.Open(file_name1)
    Set wsReport = wbReport.Sheets(1)
    Select Case wsOutput.Name
        Case Is = "Downtilt Tracker"
            wsReport.Activate
            With Rows(1)
                Set d = .Find("Completed Date")
                If d Is Nothing Then
                    MsgBox "Invalid Down-Tilt Tracker." & vbNewLine & "Please import a valid Down-Tilt Tracker."
                    wbReport.Close False
                    Sheets("Control").Activate
                    Application.ScreenUpdating = True
                    Exit Sub
                End If
            End With
    End Select

    wsReport.Activate: wsReport.Cells.Copy: wsOutput.Activate: Cells(1, 1).Select: ActiveSheet.Paste: Cells.EntireColumn.AutoFit: wsOutput.Range("A1:AB" & 1048576).HorizontalAlignment = xlCenter
    wsOutput.Cells(1, 1).Select
    Application.CutCopyMode = False
    wbReport.Close False
End Sub


texts: What's the most idiomatic way to call a function an arbitrary number of times with the previous result?

texts:
Basically I have a function of the type 'a -> 'a (an optimization function on a AST) and I want to call it (passing the previous result) until it returns the same thing as the input.

Right now I have this:

let performOptimizations ast =
  Seq.initInfinite (fun _ -> 0)
  |> Seq.scan (fun last _ -> optimizeAst last) ast
  |> Seq.pairwise
  |> Seq.find (fun (first, second) -> first = second)
  |> fst

This seems really convoluted because it is created an infinite sequence of ints just so that the scan will continue until the ast is no longer modified. I realized that I could also do something like this:

let performOptimizations ast =
  let mutable newAst = optimizeAst ast
  let mutable lastAst = ast
  while newAst <> lastAst do
    lastAst <- newAst
    newAst <- optimizeAst newAst

  newAst

However, I would prefer to avoid mutation.

What's the functional, idiomatic way of doing this in F#?


texts: Find a number which equals to the total number of integers greater than itself in an array

texts:
I am solving interview questions from here.

  Problem : Given an integer array, find if an integer p exists in the array such that the number of integers greater than p in the array
  equals to p.  If such an integer is found return 1 else return -1

  Approach First remove all the negative numbers from the given array and then sort it. Now from the sorted array check for the given
  condition.

How can I optimize my solution :

def solve(A):
    p = -1
    sum_ind = 0
    sub_array = [x for x in A if x>=0]
    sub_array.sort()
    print sub_array
    for i in range(len(sub_array)):
        for j in range(i+1,len(sub_array)):

            if sub_array[j] > sub_array[i]:
                sum_ind += 1

        if sub_array[i] == sum_ind:
            p = 1
            break
        else:
            sum_ind = 0

    return p

Test Cases:

print solve([ ]) == (-1)
print solve([ -1, -2, 0, 0, 0, -3 ]) == (1)
print solve([4,7,8,9,11]) == (1)
print solve([-4, -2, 0, -1, -6 ]) == (1)
print solve([-4, -2, -1, -6 ]) == (-1)
print solve([6,7,5 ]) == (-1)
print solve([ 4, -9, 8, 5, -1, 7, 5, 3 ]) == (1)


texts:
I'm thinking about the usage of percent, example, in margins.

We can use overlay to separate our layout by DPI sizes, but why can't we use percentage?

Something like that:

Display display = getWindowManager().getDefaultDisplay();

float width = display.getWidth();
float height = display.getHeight();

//20% of left margin
float imageMarginLeft = ( width * 20 ) / 100;

And then set this margin to the image, or whatever element.

Is this bad?


texts:
I have a collection inside MongoDB with thousands of documents. A document should be processing depending on some logic. To make the point simple, I suppose here there is a field requiresProcessing indicating whether or not the document must be processed.

To do the processing I created a stream of objects from MongoDB to stream just the objects that must be processed. The code is as follows:

// MongoDB repository module
var config = require('./configurations.js');
var db = require('monk')(config.mongodb.connectionUrl);
var collection = db.get('collection');

var numForProcessing = 0;

var getNextForProcessing = function() {
    numForProcessing++;
    return collection.find({requiresProcessing: true}, {skip: numForProcessing - 1, limit: 1}).then(function(data) {
        return data[0];
    });
}

module.exports = {
    getNextForProcessing: getNextForProcessing
};

// Stream Definition Module
"use strict";

const Readable = require('stream').Readable;
const repository = require('./repository.js');

class StreamObjectsForProcessing extends Readable {

    constructor(options) {
        if (options === undefined) options = {};

        options.objectMode = true;
        super(options);
    }

    _read() {
        let self = this;

        repository.getNextForProcessing().then(function(data) {
            if (data === undefined) {
                self.push(null);
            } else {
                self.push(data);
            }
        }).catch(function(err) {
            console.log(err);
        });
    }
}

Then to use it, I simply do as usual:

var stream = new StreamObjectsForProcessing();
stream.on('data', function(data) {
    // processing here
});

Although it is working, I want a review for this. Is it a good approach? Or can it be improved?


texts:
I have a Windows Store and Windows Phone app, and in this app I have many pages like this:

<Grid Background="Transparent">
    <ScrollViewer Style="{StaticResource DataPage}">
        <StackPanel>
            <TextBlock>
                Some text here:
                <LineBreak/>
            </TextBlock>
            <Viewbox MaxHeight="112">
                <Border BorderBrush="Black" BorderThickness="1">
                    <Image Source="MyImage.png"/>
                </Border>
            </Viewbox>
        </StackPanel>
    </ScrollViewer>
</Grid>

These pages are loaded into a Frame to be displayed when needed.  Now, however, I have many pages, and I was wondering if there is a better way to do this.  I have been doing it like this so far because easy to make the page content dynamically reload to fit the screen/app size the best with VisualStates and because it is easy to use XAML markup to style my text, image borders (not always there), and layout perfectly, and any solution provided must support everything this does and work in both Windows Store and Phone apps.

Just for reference, this is the C# that loads this page into the frame:

DataFrame.Navigate(Data.Pages[Items.SelectedIndex]);

DataFrame is the Frame, obviously; Data.Pages is an ObservableCollection<Type> in my ViewModel (Data is an instance of the VM class); Items is the ListBox that contains the selectable options.

This image shows the context of what I am doing, with the content in one of these pages outlined in black:


texts: Checking if a number is palindrome or not in Java

texts:
Got this question in a technical interview and here is my solution:

public class Main {

  public static void main(String[] args) {

    Scanner in = new Scanner(System.in);

    if (!in.hasNextInt()) {
      System.out.println("not a number!");
    }

    int number = in.nextInt();

    System.out.println(isPalidrom(number));
  }

  private static String isPalidrom(int number) {

    String numberStr = Integer.toString(number);
    String reverseStr = new StringBuilder(numberStr).reverse().toString();

    if (reverseStr.equals(numberStr)) {
      return "palindrome";
    } else {
      return "not palindrome";
    }
  }
}

I was going to solve it with using modulus 10 and decided to do it by reverting the number to integer, was it a good idea?


texts: Good randomness in Python code for a lottery-like game

texts:
I'm trying to build a lottery-like game in Python 3.6 where a function selects a winner from a participant list where every participant has a winning chance weighted by the value of the tickets they bought. I'm using the SystemRandom class in order to avoid software-state-dependency. Is this a good practice regarding good enough randomness? How could this code be improved? Also, does the shuffling does add anything to the randomness?

import random

# Randomly selects an element from a choice list using weighted probabilities
def randomWeightedSelection(choices, weights):

    # Build index list
    indices = list(range(len(choices)))

    # Shuffle indices
    random.shuffle(indices)

    # Shuffle weights accordingly
    shuffled_weights = [weights[i] for i in indices]

    # Create random generator
    rng = random.SystemRandom()

    # Select element
    selected_index = rng.choices(indices, weights=shuffled_weights, k=1)[0]

    return [choices[selected_index], selected_index]


texts:
Firstly, have a good day to all,
I've been trying to learn PyQt5 nowadays. I wrote a code about check box state changing depends on other check box. It looks work. I wonder your feed back.
Thank you for your time.

from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import sys

class CheckBox(QWidget):

    def __init__(self):
        super(CheckBox, self).__init__()
        self.features()
        self.checkbox()

    def features(self):
        self.setWindowTitle("Check Box")
        self.setGeometry(500, 200, 200, 200)

        self.show()

    def checkbox(self):
        # Check Box
        self.check_box1 = QCheckBox("Alive")
        self.check_box2 = QCheckBox("Dead")
        self.check_box3 = QCheckBox("No Idea")
        # Check Box State
        self.check_box3.setChecked(True)
        self.check_box1.stateChanged.connect(self.onStateChange)
        self.check_box2.stateChanged.connect(self.onStateChange)
        self.check_box2.stateChanged.connect(self.onStateChange)
        # Button
        self.push_button1 = QPushButton("Send")
        self.push_button1.clicked.connect(lambda: self.sendmessage(self.check_box1.isChecked(),
                                                                self.check_box2.isChecked(),
                                                           self.check_box3.isChecked(), self.label1))
        # Label
        self.label1 = QLabel("")
        # Vertical Lay Out
        v_box1 = QVBoxLayout()
        v_box1.addWidget(self.check_box1)
        v_box1.addWidget(self.check_box2)
        v_box1.addWidget(self.check_box3)
        v_box1.addWidget(self.push_button1)
        v_box1.addWidget(self.label1)
        # Horizontal Lay Out
        h_box1 = QHBoxLayout()
        h_box1.addStretch()
        h_box1.addLayout(v_box1)
        h_box1.addStretch()
        # Set Lay Out
        self.setLayout(h_box1)

    def onStateChange(self, state):
        if state == Qt.Checked:
            if self.sender() == self.check_box1:
                self.check_box2.setChecked(False)
                self.check_box3.setChecked(False)
            elif self.sender() == self.check_box2:
                self.check_box1.setChecked(False)
                self.check_box3.setChecked(False)
            elif self.sender() == self.check_box3:
                self.check_box1.setChecked(False)
                self.check_box2.setChecked(False)

    def sendmessage(self, cbox1, cbox2, cbox3, lab):
        if cbox1:
            lab.setText("Check Box 1")
        elif cbox2:
            lab.setText("Check Box 2")
        elif cbox3:
            lab.setText("Check Box 3")
        else:
            lab.setText("No Selection")

app = QApplication(sys.argv)
checkbox = CheckBox()
sys.exit(app.exec_())


texts: Efficiently determine whether two arbitrarily-sized integers share a digit

texts:
My current algorithm creates two new integers initialized to 0 (one for each input), then sets the nth bit to 1 if the integer's corresponding input contains the digit n. The bitwise AND of these integers is then 0 if the inputs don't share a digit.

I'm pretty sure there's a way to make this function more efficient. Is there something I'm missing? Example implementation (in Java) below.

boolean shareDigits(long a, long b)
{
    int aBits=0, bBits=0;
    if(a==0) aBits=1;
    if(b==0) bBits=1;
    while(a!=0)
    {
        aBits |= (1 << (a % 10));
        a/=10;
    }
    while(b!=0)
    {
        bBits |= (1 << (b % 10));
        b/=10;
    }
    return (aBits & bBits) > 0;
}


texts: Removing any duplicate characters in a string

texts:
I have piece of code in C which removes any duplicate characters in a string.  But I am doing it in two loops and would like it to optimize it to one loop.

void removeDuplicates(char* ptr)
{
    int end = 1;
    int length = strlen(ptr);
    int current;
    int i;
    current = 1;

    for(end=1; end<length; end++)
    {
        for(i=0; i<end; i++)
        {
            if(ptr[end] == ptr[i])
            break;
        }

        if(i == end)
        {
            ptr[current] = ptr[i];
            current++;
        }
    }

    ptr[current] = 0;
}

int main(int argc, char** argv)
{
    char str[256] = {0,};
    gets(str);
    removeDuplicates(str);
    printf("%s\n", str);
    return 1;
}


texts:
I finally got my carousel to work in JavaScript, and I want to know what you guys think about it and what I can do better.

var reviews = document.getElementsByClassName('review');
var leftArrow = document.getElementsByClassName('arrow')[0];
var rightArrow = document.getElementsByClassName('arrow')[1];

var currentReview;
var nextReview;

function carousel(direction) {
  for (var i = 0; i < reviews.length; i++) {
    if (reviews[i].classList.contains("show")) {
      currentReview = reviews[i];
      if (direction == 'forward') {
        if (i + 1 > reviews.length - 1) {
          nextReview = reviews[0];
        } else {
          nextReview = reviews[i + 1];
        }
      } else {
        if (i - 1 < 0) {
          nextReview = reviews[reviews.length - 1];
        } else {
          nextReview = reviews[i - 1];
        }
      }
    }
  }

  currentReview.classList.remove("show");
  nextReview.classList.add("show");
}

leftArrow.onclick = function() {
  carousel('backward');
}
rightArrow.onclick = function() {
  carousel('forward');
}
* {
  font-family: Arial;
}

.carousel {
  display: flex;
  align-items: center;
  justify-content: center;
}

.review {
  display: none;
  text-align: center;
}

.show {
  display: block;
}

.arrow {
  margin-left: 25vw;
  margin-right: 25vw;
}

.arrow-left {
  width: 0;
  height: 0;
  border-top: 10px solid transparent;
  border-bottom: 10px solid transparent;
  border-right: 10px solid black;
}

.arrow-right {
  width: 0;
  height: 0;
  border-top: 10px solid transparent;
  border-bottom: 10px solid transparent;
  border-left: 10px solid black;
}

Title1

Title2

Title3

It can also be demonstrated in this JSFiddle


texts:
I was wondering if anyone had anything to recommend for how to clean up the code I made below. Essentially I am asking if my code is messy or not and if there are any recommendations for my improvement.

# Most basic fantasy combat simulator
import random

p_health = 5
g_health = 5
goblin_alive = True

def status():
    if g_health == 5:
        return "\nA menacing goblin stands before you..."
    elif g_health >= 3:
        return "\nThe goblin is looking a little tired, and is bleeding..."
    elif g_health >= 1:
        return "\nThe goblin is bleeding horribly and looks enraged..."

while goblin_alive:
    if g_health <= 0:
        goblin_alive = False
        print("\nCongrats you slayed the goblin!")
        again = input("Play again? Y/N: ")

        if again == 'y' or again == 'Y':
            goblin_alive = True
        elif again == 'N' or again == 'n':
            print("\nGoodbye")
            exit()
    if p_health <= 0:
        print("Oh dear you have died horribly and the goblin cuts your head off for a trophy...")
        again = input("Play again? Y/N: ")

        if again == 'y' or again == 'Y':
            p_health = 5
            g_heath = 5
            goblin_alive = True
        elif again == 'N' or again == 'n':
            print("\nGoodbye")
            exit()

    desc = status()
    print(desc)
    print("You have " + str(p_health) + ' hit points.')

    attack = input("Press enter to attack: ")
    if attack == '':
        print("\nYou swing your sword fiercely at the goblin!")
        hit_type = random.randint(1, 2)
        if hit_type == 1:
            damage = random.randint(1, 3)
            print("You deal a fierce blow for " + str(damage) + " damage to the goblin.")
            g_health = g_health - damage
        elif hit_type == 2:
            damage = random.randint(1, 3)
            print("The goblin slashes you for " + str(damage) + " damage, uh oh...")
            p_health = p_health - damage
    else:
        print("\nYou better do something...")


texts: Automating a set a of weekly reports, including graphs and delivery of reports

texts:
I have been writing code to automate some weekly reports. I had help over on Stack Overflow. I have code that works for the most part, however there are a few things that I just can't seem to fix.

In short, I loop through the data and create a dictionary of dataframes based on 'location' key unique values. I can use the dictionary to make summary reports for each location. I wanted to make another dictionary from this based on 'sublocation.' Instead with some advice, I make a list of each sublocation, access each item in the df-dict, loop to find corresponding sublocations and make plots.

My problems are as follows:

Code is slow
Graphs are not formatted properly (overlapping even with tight_layout)
For the reports in sublocation, I am having a hard time saving to the right folder. I think this has to do with the way I want to format the string in the savefig text. For each sublocation I want reference the name using value['location'], I think this is always updated every loop so it doesn't work.
I have the error exception because when looking to match subloc to loc. not every subloc will appear in the dict value dataframe

f = 'path'
d = pd.DataFrame()
d= pd.read_csv(f)
dfs = dict(tuple(d.groupby('location')))
for key, value in dfs.items():
    try:
        fig, axs = plt.subplots(2, 3);
        sns.countplot(y='ethnic', data=value, orient='h', palette ='colorblind', ax=axs[0,0]);
        sns.countplot(y='Ratio', data=value,orient='v', palette ='colorblind',ax=axs[1,0]);
        sns.countplot(y='site', data = value, ax=axs[0,1]);
        sns.countplot(y='STATUS', data = value, ax = axs[1,1])
        sns.countplot(y='Assessment', data = value, ax = axs[0,2])
        #pth = os.path.join(tmppath, '{0}'.format(key))
        for p in axs.patches:
            ax.text(p.get_x() + p.get_width()/2., p.get_width(), '%d' % int(p.get_width()),
            fontsize=12, color='red', ha='center', va='bottom')
        plt.tight_layout(pad=2.0, w_pad=1.0, h_pad=2.0);
        plt.set_title('{0}'.format(key)+'Summary')
        plt.savefig("basepath/testing123/{0}/{1}.pdf".format(key,key), bbox_inches = 'tight');
        plt.clf()

        #plt.show()
    except:
        plt.savefig("basepath/{0}/{1}.pdf".format(key,key), bbox_inches = 'tight');
        #plt.savefig("{0}.pdf".format(key), bbox_inches = 'tight');
        pass

#####Now for sublocations

dfss = dict(tuple(d.groupby('site')))

#%%

for key, value in dfss.items():
    a =(repr(value['school_dbn'][:1]))

    try:
        fig, axs = plt.subplots(2, 3);
        #tmppath = 'basepath/{0}'.format(key);
        sns.countplot(y='ethnic', data=value, orient='h', palette ='colorblind', ax=axs[0,0]);
        sns.countplot(y='Program]', data=value,orient='v', palette ='colorblind',ax=axs[1,0]);
        sns.countplot(y='AltAssessment', data = value, ax = axs[0,2])
        pth = os.path.join(tmppath, '{0}'.format(key))
        plt.tight_layout(pad=2.0, w_pad=1.0, h_pad=2.0);
        plt.set_title('{0}'.format(key)+'Summary')
        plt.savefig("basepath/{0}/{1}_{2}.pdf".format(value['location'][-6:],value['location'][-6:],key), bbox_inches = 'tight');
        plt.clf()

        #plt.show()
    except:
        plt.savefig("basepath/testing123/{0}/{1}_{2}.pdf".format(value['location'][-6:],value['location'][-6:],key), bbox_inches = 'tight');
        #plt.savefig("{0}.pdf".format(key), bbox_inches = 'tight');
        pass

The reason why I want to save like this is because each location has a folder with same name. Sublocation belongs to only one location, therefore I want to save as 'location_sublocation.pdf'.


texts:
I'm running MicroPython on an ESP32 relaying sensor data to my MQTT server for Home Assistant. I only want it to emit a message when state has changed and a motion detected state to hold for a minute before returning to a clear state. I see a lot of examples using sleep, but I don't like the blocking nature of sleep as I will be adding more sensors. Instead I've been using ticks_ms() and ticks_diff() to keep the state from fluttering on/off too much, but I can't help but think there's a better/more elegant way to do this that I'm not seeing.
There's some repetition and nesting that sticks out to me
from umqtt.robust import MQTTClient
from machine import Pin, unique_id
from time import ticks_diff, ticks_ms
from ubinascii import hexlify

#Config
MQTT_SERVER = "X.X.X.X"
MQTT_PORT = 1883
MQTT_USER = b"USER"
MQTT_PASSWORD = b"PASSWORD"
MQTT_CLIENT_ID = hexlify(unique_id())
MQTT_TOPIC = b"esp/motion"
mqtt = MQTTClient(MQTT_CLIENT_ID, MQTT_SERVER, MQTT_PORT, MQTT_USER, MQTT_PASSWORD)

ledPin = Pin(2, Pin.OUT)
motPin = Pin(15, Pin.IN)
previousState = 0
delay_ms = 60000
clock = ticks_ms()

def main():
    global clock, previousState, delay_ms

    try:
        mqtt.connect()

        while True:
            state = motPin.value()

            if state == 1:
                ledPin.on()

                if previousState == 0:
                    if ticks_diff(ticks_ms(), clock) >= 0:
                        print('motion_start')
                        mqtt.publish(MQTT_TOPIC, 'motion_start')
                        clock = ticks_ms() + delay_ms
                        previousState = state
                else:
                    clock = ticks_ms() + delay_ms

            else:
                ledPin.off()

                if previousState == 1:
                    if ticks_diff(ticks_ms(), clock) >= 0:
                        print('motion_stop')
                        mqtt.publish(MQTT_TOPIC, 'motion_stop')
                        previousState = state

    finally:
        ledPin.off()
        mqtt.publish(MQTT_TOPIC, 'motion_stop')
        mqtt.disconnect()

if __name__ == "__main__":
    main()


texts:
The task was to find the shortest path between P and K in a maze. You can move horizontally and vertically, where # is a wall and . is free space. I've had a lot of trouble passing on the int k, which is the path length. I had to make a pair which contains a pair of x and y coordinates and int k.

Could I have done this any better without too much change in the code, especially with the pairs and the while loop? And how good is my code overall?

#include <iostream>
#include <string>
#include <vector>

using namespace std;

int dfs(string g[30][30], pair<int, int> p)
{
    vector <pair<pair<int, int>, int> > v;
    int visited[30][30] = {0};
    int x, y, k = 0;
    pair <pair<int, int>, int> mj;
    pair <pair<int, int>, int> z;
    pair <int, int> l;
    z = make_pair(make_pair(p.first, p.second), 0);
    v.push_back(z);
    while(v.size() != 0)
    {
        mj = v.front();
        l = mj.first;
        x = l.first;
        y = l.second;
        k = mj.second;
        v.erase(v.begin());
        if(g[x][y] == "K")
            return k;
        if((g[x+1][y] == "." or g[x+1][y] == "K") and not(visited[x+1][y]))
        {
            v.push_back(make_pair(make_pair(x+1, y), k+1));
            visited[x+1][y] = 1;
        }
        if((g[x][y+1] == "." or g[x][y+1] == "K") and not(visited[x][y+1]))
        {
            v.push_back(make_pair(make_pair(x, y+1), k+1));
            visited[x][y+1] = 1;
        }
        if((g[x-1][y] == "." or g[x-1][y] == "K") and not(visited[x-1][y]))
        {
            v.push_back(make_pair(make_pair(x-1, y), k+1));
            visited[x-1][y] = 1;
        }
        if((g[x][y-1] == "." or g[x][y-1] == "K") and not(visited[x][y-1]))
        {
            v.push_back(make_pair(make_pair(x, y-1), k+1));
            visited[x][y-1] = 1;
        }
    }
}

int main()
{
    int n, m;
    pair <int, int> p;
    string s, g[30][30];
    cin >> n;
    cin >> m;
    for(int i = 0; i < n; i++)
    {
        cin >> s;
        for(int j = 0; j < s.size(); j++)
        {
            g[i][j] = s.substr(j, 1);
            if(g[i][j] == "P")
                p = make_pair(i, j);
        }
    }
    cout << dfs(g, p);
    return 0;
}

Sample input:

6
10
##########
#.P#.....#
##.#.K#..#
#..####..#
#........#
##########

Sample output:

14


texts: Custom React hook to store a sample window

texts:
I would like to record a list of the most recent values passed as props to a React component, including the current one. This list will be passed as props to a child component (a time series chart, which will show the last N values).

To do this, I made a custom hook useDataWindow:

const { useCallback, useRef, useState, useEffect } = React;

function useDataWindow(length) {
  return useCallback(
    (datum) => {
      const [data, setData] = useState([]);

      useEffect(
        () => {
          setData([...data, datum].slice(-length));
        },
        [datum, length]
      );

      return data;
    },
    [length]
  );
}

function App({ value }) {
  const dataWindow = useDataWindow(3);
  const items = dataWindow(value);
  return (

      {items.map((item, i) =>
{item}
)}

  );
}

for (let i = 1; i <= 4; ++i) {
  ReactDOM.render(<App value={i} />, document.getElementById("root"));
}

The <App /> component is passed the values 1, 2, 3, 4 and displays the 3 most recent values, so this appears to do what I want, but is this the "right way to do it"? It seems weird to call setData in every render (which I guess is triggering a re-render).

I tried to do it without useState, but this leaves me with the previous values, not including the current one:

const { useCallback, useRef, useState, useEffect } = React;

function useDataWindow(length) {
  return useCallback(
    (datum) => {
      const data = useRef([]);

      useEffect(
        () => {
          data.current = [...data.current, datum].slice(-length);
        },
        [datum, length]
      );

      return data.current;
    },
    [length]
  );
}

function App({ value }) {
  const dataWindow = useDataWindow(3);
  const items = dataWindow(value);
  return (

      {items.map((item, i) =>
{item}
)}

  );
}

for (let i = 1; i <= 4; ++i) {
  ReactDOM.render(<App value={i} />, document.getElementById("root"));
}

Is the first approach a good idea, and if not:

is there a way to fix the second approach to make it include the current value?
is there a more sensible way to do what I want which I have overlooked?


texts:
I was wondering if someone could review this simple bit of code that originally was in C++, but now converted to C# as practice in using bit-shifting and creating a sort of a quasi-array functionality. Consider the partition size as a size of our array which can only hold a specific size limit for said partition. It was assumed that input is always valid, and thus no fail safes were included.  The usage of unsigned integers is intentional as we want only positive values.

If you're wondering about the liberal usage of type casting, it is because it appears that C# is far stricter than C++ with respect to data types.

using System;

namespace bitShifting
{
    class Program
    {

        uint bitSize, shiftCount, mask, partionSize;

        void setValue(ref uint var, uint k, uint i, uint val)
        {

            bitSize = sizeof(uint) * 8;

            partionSize = (uint)(bitSize / k);
            shiftCount = partionSize * i;

            mask = (uint)~(((1 << (int)partionSize) - 1) << (int)shiftCount);
            var = var & mask;
            val = val << (int)shiftCount;
            var = var | val;

        }
        uint getValue(uint var, uint k, uint i)
        {
            bitSize = sizeof(uint) * 8;

            partionSize = (bitSize / k);
            shiftCount = partionSize * i;

            mask = (uint)(((1 << (int)partionSize) - 1) << (int)shiftCount);
            var = var & mask;
            var = (var >> (int)shiftCount);
            return var;
        }

        static void Main(string[] args)
        {
            Program p = new Program();

            uint k;
            uint value;
            uint maxValue;

            uint var = 0;

            Console.WriteLine("C++ Lab to C#, Practice Using Pass by Ref");

            Console.WriteLine("Valid Partition K size are: 1, 2, 4, 8, 16, 32.");
            Console.WriteLine("Enter Partition Size");

            k = Convert.ToUInt32(Console.ReadLine());

            maxValue = (uint)((1 << (int)(sizeof (uint) * 8 / k)) - 1);

            if(k == 1)
            {
                maxValue = 2147483647;
            }
            Console.WriteLine("Maximal Value for Partion of Size {0} is 0 to {1}", k, maxValue);

            bool getValue = true;
            for(uint i = 0; i < k; i++)
            {
                Console.WriteLine("Input a Value");
                value = Convert.ToUInt32(Console.ReadLine());

                if (k == 1)
                {
                    Console.WriteLine("Value at Index 0 is: {0}", value);
                    getValue = false;
                }
                else
                {
                    p.setValue(ref var, k, i, value);
                }
            }

            for(uint i = 0; i < k; i++)
            {
                if (getValue)
                {
                    value = p.getValue(var, k, i);
                        Console.WriteLine("Value At Index {0} is: {1}", i, value);
                }
            }

        }
    }
}


texts: Backbone/Marionette form with list of inputs

texts:
Using Backbone/Marionette, I'm building a simple widget that looks like:

I'm hoping to get some feedback on my approach because I think I may be doing it wrong.

jsfiddle

// widget/invites/person.js
var Person = Backbone.Model.extend({
    defaults: {
        name: ''
    }
});

// widget/invites/people.js
var People = Backbone.Collection.extend({
    model: Person
});

// widget/invites/personField.js
var PersonView = Marionette.ItemView.extend({
    template: _.template(...),
    hasSiblings: false,
    initialize: function(opts) {
        this.hasSiblings = opts.hasSiblings || false;
    },
    templateHelpers: function() {
        return {
            id: this.model.cid,
            showDel: this.hasSiblings
        }
    },
});

// widget/invites/form.js
var FormView = Marionette.CompositeView.extend({
    template: _.template(...),
    childView: PersonView,
    childViewOptions: function() {
        return {
            hasSiblings: (this.collection.length > 1)
        };
    },
    childViewContainer: '.values',
    ui: {
        'addBtn': '.add-name',
        'removeBtn': '.del-name',
        'wrap': '.values'
    },
    events: {
        'click @ui.addBtn': 'addFormRow',
        'click @ui.removeBtn': 'removeFormRow'
    },
    addFormRow: function(ev) {
        var name;
        ev.preventDefault();

        if (this.collection.length === 1) {
            // also rerender first input to include remove button
            name = this.ui.wrap.find('[name="person[]"]').get(0).value;
            this.collection.reset([{name: name}, {name: ''}]);
        }
        else {
            this.collection.add({name:''});
        }
    },
    removeFormRow: function(ev) {
        var id, model;
        ev.preventDefault();

        id = $(ev.currentTarget).data('id');
        model = this.collection.get(id);
        this.collection.remove(model);

        if (this.collection.length === 1) {
            // rerender first input so it doesn't have remove button
            name = this.ui.wrap.find('[name="person[]"]').get(0).value;
            this.collection.reset([{name: name}]);
        }
    }
});

Note, the list is saved by clicking a Submit button (not shown in mockup), as there will be other fields in the form as well.

The code works, but consider the following workflow:

User enters "John Doee" in first input

Collection: ['']

User clicks "add", and enters "Sally Something" in the second input

Collection: ['', '']

User realized they spelled "John Doe" (two e's) and fixes it

Collection: ['', '']

or consider an existing list being edited:

Collection: ['John Doe', 'Sally Something', 'Austin Powers']
User removes "Austin Powers"

Collection: ['John Doe', 'Sally Something']

User updates "John Doe" to "Dr. John Doe"

Collection: ['John Doe', 'Sally Something']

I'm using collection.add() and collection.remove() to trigger the view to update itself, but the collection doesn't always reflect the data on the screen. Is that okay?

Additionally, I did try adding a hook for blur which grabbed every value and reset the collection, but it seemed too brute force. Hence, my doubt about this approach.

Any thoughts or other approaches?


texts:
Made a very simple calculator in Python. The program has the following features:

All the basic operators can be used. '+', '-', '*', '**', '/', and '//'.
The user can start the program again.
The previous output is available for the user to use again.

def start(out='temp'):
    # Get the input from the user and pass all the values to verify.
    # Explicit test is used because the output can be zero.
    if out != 'temp':
        x = out
        print('\nFirst number: ', x)
    else:
        x = input('\nFirst number: ')
    op = input('Operator: ')
    y = input('Second number: ')
    verify(x, op, y)

def verify(x, op, y):
    # Check if the operator and the numbers entered are valid.
    # If any input is invalid call start and get input again.
    # If inputs are valid pass all the values to calc.
    ops = ['+', '-', '*', '**', '/', '//']
    if op in ops:
        try:
            x, y = int(x), int(y)
        except ValueError:
            print('Numbers are not valid.\n')
            start()
        else:
            calc(x, op, y)
    else:
        print('Please enter a valid operator.\n')
        start()

def calc(x, op, y):
    # Use eval to calculate the output and pass the output to
    # restart.
    out = eval(f'x {op} y')
    print('Output:', out)
    restart(out)

def restart(out):
    # User can start the process again. The previous output can be used as
    # the first number.
    re = input('Start again? (y/n): ')
    if re == 'y':
        use_out = input(
            'Use the previous output as the first number? (y/n): ')
        if use_out == 'y':
            start(out=out)
        else:
            start()
    else:
        print('Calc is now closed.')

start()

Here's a sample output.

First number: 5
Operator: *
Second number: 9
Output: 45
Start again? (y/n): y
Use the previous output as the first number? (y/n): y

First number:  45
Operator: //
Second number: 2
Output: 22
Start again? (y/n): n
Calc is now closed.

I am looking for ways to make the code more readable, minimize redundancy, improving the overall design, etc. Any help would be appreciated!


texts: Speeding up string splitting in Rcpp/Cpp

texts:
I'm looking to speed up an Rcpp function I have written.

The function takes in a string called vcfield, which takes the format od x:y:z. This string has 3 fields if you separate it by the :. It takes an int DSfield which tells us the index (0 based) field from vcfield which is the dosage. Dosage is always one double value.

It also takes in 2 ints called aa and bb

The program then returns the value of abs[(aa + bb) - dosage].

So calling ReturnUncertainty("1/1:1.88:0,0.12,0.88", 1, 1, 1) should return 0.12, as  abs[(1+1) - 1.88] = 0.12

We should presume that the number of characters in the different fields of vcfield might vary. So it should be also be capable of taking a value like "1/1/1/1:1.88999:0,0.12,0.88".

#include <Rcpp.h>
#include <bits/stdc++.h>

using namespace Rcpp;
using namespace std;

// [[Rcpp::export]]
double ReturnUncertainty(String vcfield, int DSfield, int aa, int bb) {

    string stdfield = vcfield;
    vector <string> tokensMain;
    stringstream checkMain(stdfield);
    string intermediate;

    while (getline(checkMain, intermediate, ':')) {
        tokensMain.push_back(intermediate);
    }

    std::string DS = tokensMain[DSfield];
    double DSf;
    std::istringstream(DS) >> DSf;

    double aaD = static_cast<double>(aa);
    double bbD = static_cast<double>(bb);

    double genoSum = aaD + bbD;
    return abs(genoSum - DSf);
}

QUESTION: As a total newbie to C++, I was wondering whether or not I am doing anything that is very inefficient / unecessary which might be slowing my code down?


texts: What is the fastest way to record the listed files in a directory in C?

texts:
I want to fill an array of dirent pointers with each entry of a specified directory. I either need to count the items before, allocate memory, then go over them again, or I will have to reallocate each iteration of the while loop. Both of these options seem slow. Surely there's a better way.
Are these my only option:
struct dirent **Entries;
DIR *Dir = opendir("Some dir path");
struct dirent *Entry;
unsigned int Count = 0;
while ((Entry = readdir(Dir))) {
    Count++;
}
Entries = malloc(Count*sizeof(struct dirent*));
rewinddir(Dir);
for (int i = 0; (Entry = readdir(Dir); i++) {
    Entries[i] = Entry;
}

Or
struct dirent **Entries;
DIR *Dir = opendir("Some dir path");
Dir = opendir("Some dir path");
struct dirent *Entry;
for (int i = 0; (Entry = readdir(Dir); i++) {
    Entries = realloc(Entries, i*sizeof(struct dirent*));
    Entries[i] = Entry;
}
closedir(Dir);

Or is there some faster way?


texts: scan activedirectory for all users and their groups in domain with c#

texts:
I wrote a method for a wpf app in .net core to get all users and their group by name if they are in a group from my active directory domaine.

public static void getGroupsWithUsers() {
    String currentDomain = Domain.GetCurrentDomain().ToString();

    using (PrincipalContext context = new PrincipalContext(ContextType.Domain, currentDomain))
    {
        using (PrincipalSearcher searcher = new PrincipalSearcher(new UserPrincipal(context)))
        {

            foreach (var result in searcher.FindAll())
            {
                DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
                var SID = WindowsIdentity.GetCurrent().User.ToString();

                // find a user
                UserPrincipal user = UserPrincipal.FindByIdentity(context, de.Properties["samAccountName"].Value.ToString());

                if (user != null)
                {
                    // get the user's groups
                    var groups = user.GetAuthorizationGroups();

                    foreach (GroupPrincipal group in groups)
                    {
                        Console.WriteLine("User: " + user + " is in Group: " + group);
                    }

                }
            }
        }
    }

}

The method takes 1.5 to 1.8 seconds for a small amount of data and Im afraid that the execution time takes forever for real world data amounts.


texts: python Chatroom/Codehelp through the terminal

texts:
I created a system that allows individuals to ask questions about code, and chat. I wanted to make this system smaller and better because this is easy to bypass for some reason.
The modules/packages I used for this chatroom project
import os
import time

Now the actual script that contains about 56 lines of code!
print("Codehelp || Question through a terminal.")
#### Codehelp Variables
chat = open('publiclogs.txt','r')
name = input("Enter Username: ")
crown = ""
owner = False
#### Codehelp Scripts
if name == "":
  print("\nINVALID! Name must not be Empty..\n")
  time.sleep(2)
  exit()
while True:
  with open('publiclogs.txt','a') as chat_txt:
    chat_txt.close()
  chat = open('chat.txt','r')
  print(chat.read())
  message = input("Enter Your message: ")
  os.system("clear")
  if message.lower() == "":
    os.system("clear")
    print("You must type something in order to send a message\n")
    input("Press enter to continue ")
    os.system("clear")
  elif message.lower() == ".ask":
    title = input("Enter title of Question. Also be specific: ")
    description = input("Enter description: ")
    tags = input("Enter TAGS. Seperate by ',': ")
    os.system("clear")
    with open('question.txt','a') as ask_txt:
      ask_txt.write(f'TITLE: {title}\n')
      ask_txt.write(f'DESCRIPTION: {description}\n')
      ask_txt.write(f'TAGS: {tags}\n')
      ask_txt.write(f'Written by {name}\n')
      ask_txt.write(f'-------------------\n')
      ask_txt.close()
    with open('publiclogs.txt','a') as chat_txt:
      chat_txt.write(f'New Question has been asked! View question.txt!\n')
      chat_txt.close()
  elif message.lower() == ".login":
    print("Welcome to the Admin log-in!")
    time.sleep(2)
    password = input("What's the Password: ")
    print("Removed from Codehelp Currently..")
  else:
      if owner == True:
        with open('chat.txt','a') as chat_txt:
          chat_txt.write(f'{crown} {name}:{message}\n')
          chat_txt.close()
      else:
        with open('chat.txt','a') as chat_txt:
          chat_txt.write(f'{name}: {message}\n')
          chat_txt.close()

What could I do to improve this code?


texts: Find common substring that starts a set of strings

texts:
How would you in a pythonic manner write a function that returns the common substring found at the beginning of a set of strings? This is my ugly attempt:

def common_start(s):
   l = len(s)
   if l == 0: return None
   elif l == 1: return next(iter(s))
   else:
     i = iter(s)
     start = next(i)
     while start != "":
       if all(ii.startswith(start) for ii in i):
           return start
       else:
         i = iter(s)
         start = start[:-1]
         next(i) # were comparing againt the first item, so we don't need it
     else:
       return ""

s = set(("abc1","abcd","abc","abc abc"))
common_start(s) # "abc"

s = set(("ab","abcd","abc","abc abc"))
common_start(s) # "ab"

s = set(("ab",))
common_start(s) # "ab"

s = set(("","abcd","abc","abc abc"))
common_start(s) # ""

s = set()
common_start(s) # None


texts: json2CSV fails because of lack of RAM memory

texts:
I run this code on my Heroku Node.js server in order to get CSV for few hundred rows, but it fails with R14 - Memory Quota Exceeded.
It worked fine when there were less rows in DB, even without writing to file, I was able to write CSV directly to HTTP response.
What can I do to solve this?

var mongoose = require("mongoose");
const fs = require('fs');
const path = require('path')
const Json2csvParser = require("json2csv").Parser;
var Follow = require("../models/follow");
const fields = ["brand", "handle", "title", "followDateTime", "posts", "followers", "following", "description", "link", "isPrivate"];

module.exports = function(app) {
    app.get("/csv", (req, res) => {
        Follow.find({}).exec(function(err, follows) {
            if (err) {
                res.status(500).send(err);
            } else {
                let csv;
                try {
                    const json2csvParser = new Json2csvParser({ fields });
                    csv = json2csvParser.parse(follows);
                } catch (err) {
                    return res.status(500).json({ err });
                }
                const dateTime = Date.now();
                const filePath = path.join(__dirname, "..", "public", "exports", "csv-" + dateTime + ".csv");

                fs.writeFile(filePath, csv, function (err) {
                    if (err) {
                      return res.json(err).status(500);
                    }
                    else {
                      setTimeout(function () {
                        fs.unlinkSync(filePath); // delete this file after 30 seconds
                      }, 30000)
                      return res.json("/exports/csv-" + dateTime + ".csv");
                    }
                  });
            }
        });
    });
};
```


texts: Determining average of integers using quicksort

texts:
I was attempting an online problem given on a programming website which asked us to tell us the number of integers in a given list which can be obtained as an average of any two other integers in that list, where one of them can be equal to the average (so the other is obviously equal too).

The server tells me that my program exceeded the time limit for the last two test cases. So I would like to make my algorithm faster.

I've tried both the inbuilt Java sort function as well as my own implementation of quicksort.  I tried the test data on my own computer and it gives the output within a second.

My program basically sorts the array first, and then searches for a pair in linear time.

import java.util.*;

public class Average {

public static void main(String[] args) {

        Scanner in = new Scanner(System.in);
        int n = in.nextInt();

        int[] a = new int[n];

        for (int i = 0; i < n; i++){
            a[i] = in.nextInt();

        }

        quickSort(a, 0, n - 1);

         int z = 0;

         for (int k = 0; k < n; k++){
             int s = 2 * a[k];
             int l = 0;
             int r = n-1;
             while (l < r){
                if (a[l] + a[r] == s){

                        z++;
                        break;

                }
                if (a[l] + a[r] < s){
                    l++;
                }else{
                    r--;
                }
             }

         }

         System.out.println(z);
         System.exit(0);
}

//QUICKSORT FUNCTION

private static void swap(int[] a, int i, int j) {
    // TODO Auto-generated method stub
    int temp = a[i];
    a[i] = a[j];
    a[j] = temp;
}

public static void quickSort(int[] a, int p, int r)
{
    if(p<r)
    {
        int q=partition(a,p,r);
        quickSort(a,p,q);
        quickSort(a,q+1,r);
    }
}

private static int partition(int[] a, int p, int r) {

    int x = a[p];
    int i = p-1 ;
    int j = r+1 ;

    while (true) {
        i++;
        while ( i< r && a[i] < x){
            i++;}
        j--;
        while (j>p && a[j] > x){
            j--;}

        if (i < j)
            swap(a, i, j);
        else
            return j;
    }
}

}


texts: A linear search implementation for any data type in C

texts:
I performed an "experiment" to test my understanding of pointers in C. I decided to write a linear search function that can work on any array provided there is an existing function to compare the elements of the array. Here are the files:

linear_search.h

#ifndef _LINEAR_SEARCH_H
#define _LINEAR_SEARCH_H

/*
 * Summary:
 *  Performs linear search on the given array using the given
 * comparator function. Returns the index of the matching array
 * element (< len), and -1 if the element is not found.
 *
 *  Parameters are independent of type and hence this function
 * can be used for arrays of all data-types, provided that the width
 * (i.e. size of the datatype in terms of bytes) is properly specified.
 *
 * Parameters:
 *  1. *base - the address of the array from whence we start searching.
 *  2. *x    - the address of the element to find in the array
 *  3. len   - the maximum number of elements we are willing to search against.
 *  4. width - the width of each element of the array (in bytes)
 *  5. compare(void*, void*)
 *           - the function which is used for comparison. Zero is taken to be equality.
 */
long long linear_search
    (
        const void *base, const void *x, const long long len, const int width,
        const int (*compare)(const void *, const void *)
    );

#endif

linear_search.c

long long linear_search
    (
        const void *base, const void *x, const long long len, const int width,
        const int (*compare)(const void *, const void *)
    )
{
    long long index = 0;
    // convert to a char * pointer in order to make the pointer arithmetic in terms of 1 byte
    char *base_ptr = (char *) base;
    for (; index < len; index++) {
        if ((*compare)((base_ptr + index * width), x) == 0)
            return index;
    }
    return -1;
}

main.c

#include <stdio.h>
#include <stdlib.h>
#include "linear_search.h"

const int compare(const void *a, const void *b)
{
    double *p = (double *) a;
    double *q = (double *) b;
    return *p - *q;
}

int main(int argc, char const *argv[])
{
    double *a;
    double x;
    int width;
    long long int index, len, i;
    width = sizeof(double);

    printf("Enter how many elements : ");
    scanf("%lld", &len);

    a = malloc(len * width);
    if (a == NULL) {
        printf("Error while trying to allocate memory.\n");
        return EXIT_FAILURE;
    }

    printf("Enter elements one-by-one:\n");
    for (i = 0; i < len; i++) {
        printf("%d : ", (i + 1));
        scanf("%lf", (a + i));
    }

    printf("Enter the element to look for : ");
    scanf("%lf", &x);
    index = linear_search(a, &x, len, width, compare);

    printf("Index is %lld\n", index);
    return EXIT_SUCCESS;
}

I would like to know if there's a better way to accomplish this task, or if I'm making any gross errors. While it's true that my program compiled without any errors or warnings, I am never sure when it comes to C. Suggestions (however small) and critique is welcome.


texts:
I am writing a code for Barabási–Albert(BA) model with specific node and edges.
The algorithm is almost like [1] as follows:

  1.Add m<N nodes to G.
  2.Connect nodes in G randomly until you get a connected graph.
  3.Create a new node i.
  4.Pick a node j uniformly at random from the graph G. Set p=k(j)/k_tot.
  5.Pick a real number r uniformly at random between 0 and 1.
  6.If r<p then add G(m+step_i,j)=G(j,m+step_i)=1
  7. repeat steps 4-6, k times until each new node has k edges.
  8. repeat steps 3-7 until we have N nodes.

*:The sum of elements of each row or column is the degree(number of edges connected to that node) of each node.

** : k_tot is the total degree of all nodes until step i.
and here is the my implementation in Fortran:

program BA
 implicit none
 integer, parameter :: N = 20
 integer, dimension(n,n) :: A
 double precision :: r,p,r2(2),pj
 integer :: m0,i,j,L0,N1,t,jnod,k,di
 integer :: edge_number,ii,ie,je, degree

 A = 0
 m0 = 5 ! initial nodes
 L0 = 4 ! initial edges
 ii = 0
 ! adding m0 nodes with random connections
 do while (ii < L0)
   do ie = 1, m0
     call random_number(r)
     je = r * (m0 - 1) + 1
     if (A(ie,je) == 0 ) then
       if(ii>=L0) exit
       A(ie,je) = 1
       A(je,ie) = 1
       ii = ii + 1
     endif
   enddo
 enddo

 edge_number = L0
 N1 = m0
 degree = m0
 ! adding remaining nodes with pereferential attachment
 do t = 1,N-m0
   di = 0
   N1 = m0 + t
   do while(di < degree)
     call random_number(r)
     jnod = r * (N1-2)+1
     pj = sum(A(jnod,1:N1-1))/dble(sum(A(1:N1-1,1:N1-1)))
     call random_number(r)
     if ( r<pj .and. A(N1,jnod)==0 ) then
        A(N1,jnod) = 1
        A(jnod,N1) = 1
        edge_number = edge_number + 1
        di = sum(A(N1,1:N1))
     endif
   enddo
 enddo

 do i = 1,N
    write(12,"(*(I5))") (A(i,j),j=1,N)
 enddo
end program

I think the is not efficient at all and as more nodes added, it takes more to get out of loops.Do you have a better idea to make it more efficient?


texts:
I am trying to calculate the number of partitions of numbers from 1 to 107. I am using the pentagonal number theorem to achieve that, which provides a way to calculate the number of partitions of \$n\$, let's call it \$P(n) = P(n-1) + P(n-2) - P(n-5) - P(n-7) + ...\$ So \$P(n)\$ depends on different \$P(n-x)\$, where \$x\$ goes from 1 to \$n\$. Anyway, long story short, I am using two loops, one that goes from 1 to 107 and the other one that uses the \$x\$'s defined and calculate after a specific formula. As you can imagine, the code goes quite slow. Is there any way I can improve the speed of these for loops?

P.S. I have tried using numpy arrays, but I am not really comfortable with them and unfortunately it made the code even slower.

def build_list(new_limit, k):
   list_of_p_minus = list()
   while k < new_limit:
      list_of_p_minus.append(k*(2*k-1))
      list_of_p_minus.append(k*(2*k+1))
      k = k+1
   return list_of_p_minus

def loop_through_numbers(limit, list_of_p_minus):
   p_dict = dict()
   p_dict[0] = 1
   p_dict[1] = 1
   aux = 2
   aux_index = 1
   for number in range(2, limit+1):
      if aux == number
          m = weird_index % 4
          if m == 1 or m == 2:
             p_dict[number] = -1
          else:
             p_dict[number] = 1
          aux = aux + (aux_index + 1) * 2
          aux_index += 1
      else:
          p_dict[number] = 0
      for element in range(0, len(list_of_p_minus)):
          if element % 4 == 0 or element % 4 == 1:
             try:
                p_dict[number] += p_dict[number-list_of_p_minus[element]]
             except KeyError:
                break
          else:
             try:
                p_dict[number] -= p_dict[number-list_of_p_minus[element]]
             except KeyError:
                break
   return


texts: Converting an object to an array of objects

texts:
I've written a method that takes an object whose keys are arrays and converts it to an array of objects.

I feel like the code is fairly complex, after waiting a week or so and revisiting it, I don't think anyone would be able to really understand what is going on, especially if they aren't used to this style of coding. [read: I had no idea what I did there.]

function zipObj(obj) {
  // First get keys from object.
  var keys = _.keys(obj);

  // For each key, grab the data
  var propertyArray = _.map(keys, function(k, i) { return obj[k] || undefined; });

  // "Shift" propertyArray around, so we can make into array of objects
  var zippedArray = _.zip.apply(_, propertyArray);

  // Set up function that will take an array,
  // Then use the keys variable to re-create.
  var createObject = function(d) {
    var rObj = {};

    _.each(keys, function(k, i) { rObj[k] = d[i]; });
    return rObj;
  };

  // For each item in zipped array, return an object
  return _.map(zippedArray, createObject);
}

From what I understand, a lot of people writing in a functional style would reduce this down to smaller functions, however I'm not 100% sure the best way of doing that would be in this example.  I don't think reducing each step of this into its own functionality would necessarily increase readability, especially with how many little things that are going on here.

(If you open this and click Run, it will alert you with the function's inputs/ outputs.)

var input = {
  key1: [ 'val1', 'val2', 'val3' ],
  key2: [ 'val4', 'val5', 'val6' ],
  key3: [ 'val7', 'val8', 'val9' ]
}

window.alert("INPUT:\n" + JSON.stringify(input, null, '  '));

function zipObj(obj) {
  var arr = _.zip.apply(_, _.map(_.keys(obj), function(k, i) { return obj[k] || undefined; }));
  return _.map(arr, function(d) {
    var rObj = {};

    _.each(_.keys(obj), function(k, i) { rObj[k] = d[i]; });
    return rObj;
  });
}

window.alert("OUTPUT:\n" + JSON.stringify(zipObj(input), null, '  '));
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js"></script>


texts:
Just looking for some feedback for one of my models I have for a project. I'm pretty happy with it but I was wondering if anyone had any optimization suggestions.

class ContactModel
{
    public function __construct($db)
    {
        try {
            $this->db = $db;
        } catch (PDOException $e) {
            exit('Database connection could not be established.');
        }
    }

    public function getBlastRecipients()
    {
        $sql = "SELECT Email FROM Contact WHERE Blast=?";
        $query = $this->db->prepare($sql);
        $query->execute(array('1'));
        return $query->fetchAll();
    }

    public function getBOLRecipients($custpoid)
    {
        $sql = "SELECT [CustPOID]
                          ,[POShipToRef]
                          ,cp.CarrId
                          ,cp.LoadID
                          ,c.CarrDesc
                          ,ct.Email
                          ,ct.ContactId
                      FROM [Sales].[dbo].[CustPO] as cp
                      LEFT OUTER JOIN Load as ld
                      on ld.LoadID = cp.LoadID
                      LEFT OUTER JOIN Carrier as c
                      on c.CarrId = cp.CarrId
                      LEFT OUTER JOIN Contact as ct
                      on c.CarrId = ct.CarrierId
                       WHERE CustPOID=?";
        $query = $this->db->prepare($sql);
        $query->execute(array($custpoid));
        return $query->fetchAll();
    }

    public function getDeliveryRequestEmailAddresses($custpoid)
    {
        //If a ShipToID is set, we want to return all email addresses associated with that customer, otherwise just return whatever email addresses are associated with the BillToID
        $sql = "SELECT
                       CASE
                        WHEN cp.CustShipToID IS NOT NULL THEN
                       c.Email
                       ELSE
                       cy.Email
                       END as Email
                         FROM CustPO cp
                         LEFT OUTER JOIN Contact as c
                         on cp.CustBillToID = c.CustId
                         LEFT OUTER JOIN Contact as cy
                         on cp.CustShipToID = c.CustId
                         WHERE CustPOID=?";
        $query = $this->db->prepare($sql);
        $query->execute(array($custpoid));
        return $query->fetchAll();
    }

    public function getEmailAddress($contact_id)
    {
        $sql = "Select Email FROM Contact WHERE ContactId=?";
        $query = $this->db->prepare($sql);
        $query->execute(array($contact_id));
        return $query->fetch();
    }
}


texts: Program that generates brainfuck code that outputs given text

texts:
I created program that generates brainfuck code that outputs given text.
Arguments for the program are input file with the text and output file where code will be generated to.
Here is the code:

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

#define ALLOCATION_ERROR 1
#define FILE_ERROR 2
#define OTHER_ERROR 3

static inline FILE*
get_file_pointer(const char* filename,const char* mode){
    FILE* file_pointer=fopen(filename,mode);
    if(file_pointer==NULL){
        fprintf(stderr,"Error: failed to open file %s\n",filename);
        exit(FILE_ERROR);
    }
    return file_pointer;
}
static inline char*
int_to_brainfuck(int difference){
    if(difference==0)
        return ".";
    else{
        char character_in_loop=difference>0?'+':'-';
        difference=difference>0?difference:-difference;
        const unsigned int loop_body_length=17;
        const unsigned int number_of_ones=(unsigned int)(difference%10);
        const unsigned int number_of_tens=(unsigned int)(difference/10);
        char* brainfuck_code=calloc(number_of_tens+loop_body_length+number_of_ones+2,sizeof*brainfuck_code);
        if(number_of_tens>0){
            brainfuck_code[strlen(brainfuck_code)]='>';
            memset(brainfuck_code+strlen(brainfuck_code),'+',number_of_tens);
            strcat(brainfuck_code+strlen(brainfuck_code),"[<");
            memset(brainfuck_code+strlen(brainfuck_code),character_in_loop,10);
            strcat(brainfuck_code+strlen(brainfuck_code),">-]<");
        }
        memset(brainfuck_code+strlen(brainfuck_code),character_in_loop,number_of_ones);
        brainfuck_code[strlen(brainfuck_code)]='.';
        return brainfuck_code;
    }
}
static inline void
generate_code(FILE* input_file,FILE* output_file){
    int current_char,last_char=0;
    while((current_char=fgetc(input_file))!=EOF){
        char* brainfuck_code=int_to_brainfuck(current_char-last_char);
        fputs(brainfuck_code,output_file);
        if(brainfuck_code[0]!='.')
            free(brainfuck_code);
        last_char=current_char;
    }
}
static inline void
parse_args(int argc){
    if(argc!=3){
        puts("Usage: bfgen <input> <output>");
        exit(OTHER_ERROR);
    }
}
int
main(int argc,char** argv){
    parse_args(argc);
    FILE* input_file=get_file_pointer(argv[1],"r");
    FILE* output_file=get_file_pointer(argv[2],"wb");
    generate_code(input_file,output_file);
    fclose(input_file);
    fclose(output_file);
    return 0;
}


texts:
Description:

The questions are being showed in the console tap with player's score.
It's questioning by prompt continually until the prompt input gets 'exit'.
If the answer for each question is right then player's scores are counting up.
But, if not then it shows the same question over and over until the answer is right.

var Question = function(question,answers,correctAnswer){
  this.question = question;
  this.answers = answers;
  this.correctAnswer = correctAnswer;
}
Question.prototype.score = 0;
Question.prototype.playersAnswer;

Question.prototype.logAll = function(){
  console.log(this.question);
  for(var i = 0; i < this.answers.length; i++){
    console.log(i + " : " + this.answers[i]);
  }
}
Question.prototype.askQuestions = function(){
    Question.prototype.playersAnswer = prompt(this.question);
}
Question.prototype.checkIfRight = function (){
  if(this.correctAnswer === Question.prototype.playersAnswer){
    console.log("Correct Answer!");
    Question.prototype.score++;
    Question.prototype.logScore();
  }
  else if(Question.prototype.playersAnswer === "exit"){return 0;}
  else {
    console.log("Wrong! Try again :)");
    Question.prototype.logScore();
    return 'w';
  }
}
Question.prototype.logScore = function(){
  console.log("Your Score : " + Question.prototype.score
  + "\n---------------------------------");
}

var q1 = new Question('What is the name of the course\'s teacher?',['John','Baek','Jonas'],'2');
var q2 = new Question('Is JavaScript the coolest language in the world?',['Yes','No'],'0');
var q3 = new Question('What language are you gonna learn about after?',
                      ['C++','C','Java','Python','Node.js'],'4');
var questions = [q1,q2,q3];
function init(){
  var n = Math.floor(Math.random() * 3);
  questions[n].logAll();
  questions[n].askQuestions();
  questions[n].checkIfRight();

}

do {
  var n = Math.floor(Math.random() * 3);
  questions[n].logAll();
  questions[n].askQuestions();
  while(questions[n].checkIfRight() === 'w'){
    questions[n].logAll();
    questions[].askQuestions();
  };
}
while (q1.playersAnswer !== "exit");

Can you review it for best coding practices?


texts: Reliability of flock mutex (LOCK_EX|LOCK_NB)

texts:
I would like to test reliability of system flock in a multi-threaded and concurrent environment as some suggest that they are not reliable (in comments).

Thus I wrote this code which requests non-blocking exclusive lock, with multiple threads at the same time (well, almost same time).

Is there better way to test flock mutex functionality, or how to be sure that it is always exclusive?

use strict;
use warnings;
use autodie;

use threads;
use Time::HiRes qw(time sleep);
use Fcntl qw(:flock);

sub fo{ my $fh; open($fh, ">", pop) && $fh }

my $t = time();
my $one = grep $_->join,
  map async {
    my $f = fo("/tmp/flock.test");
    sleep 2+$t-time();
    my $l = flock($f, LOCK_EX|LOCK_NB);
    sleep 1;
    return $l;
  }, 1..90;

# should always be 1
print "$one is 1\n";


texts:
Learn You a Haskell shows the words function.

  words and unwords are for splitting a line of text into words or
  joining a list of words into a text

Example:

ghci> words "hey these are the words in this sentence"
["hey","these","are","the","words","in","this","sentence"]
ghci> words "hey these           are    the words in this\nsentence"
["hey","these","are","the","words","in","this","sentence"]

Please critique my implementation.

words' :: String -> [String]
words' []  = []
words' xxs@(x:xs)
  | x == ' '  = words' xs
  | otherwise = ys : words' rest
                  where (ys, rest) = break (== ' ') xxs


texts: Time limit exceeded for Sherlock and Queries Hackerrank challenge

texts:
Here is my C solution for Sherlock and Queries @ Hackerrank.

  Watson gives to Sherlock an array: \$A_1, A_2, ..., A_N\$. He also gives to
  Sherlock two other arrays: \$B_1, B_2, ..., B_M\$ and \$C_1, C_2, ..., C_M\$.

  Then Watson asks Sherlock to perform the following program:

for i = 1 to M do
    for j = 1 to N do
        if j % B[i] == 0 then
            A[j] = A[j] * C[i]
        endif
    end do
end do

  Can you help Sherlock and tell him the resulting array A? You should
  print all the array elements modulo \$(10^9 + 7)\$.

  Input Format

  The first line contains two integer numbers \$N\$ and \$M\$. The next line
  contains \$N\$ integers, the elements of array A. The next two lines
  contains \$M\$ integers each, the elements of array B and C.

  Output Format

  Print \$N\$ integers, the elements of array A after performing the program
  modulo \$(10^9 + 7)\$.

  Constraints

  \$1 ≤ N, M ≤ 10^5\$
   \$1 ≤ B[i] ≤ N\$
   \$1 ≤ A[i], C[i] ≤ 10^5\$

  Sample Input

4 3
1 2 3 4
1 2 3
13 29 71

  Sample Output

13 754 2769 1508

How should I optimize it as it is showing teminated due to time out?

#include<stdio.h>

int main()

{

    int n,m,i,j;

    scanf("%d %d ",&n,&m);

    long int a[n+1],b[m+1],c[m+1];
    for(i=1;i<=n;i++)
        scanf("%ld",&a[i]);

    for(i=1;i<=m;i++)
        scanf("%ld",&b[i]);

    for(i=1;i<=m;i++)
        scanf("%ld",&c[i]);

    for(i=1;i<=m;i++)
    {
        for(j=1;j<=n;j++)
        {
            if(j%b[i]==0)
            {
                a[j]=(a[j]*c[i])%1000000007;
            }
        }

    }

    for(i=1;i<=n;i++)
        printf("%ld ",a[i]%1000000007);

        return 0;

}


texts:
I have a training dataset from which I want to draw samples in a random fashion such that all samples are used before getting randomly shuffled again. For this reason I implemented a simple random index generator.
For a dataset of 10 samples, the output looks something like this:
0 1 2 3 4 5 6 7 8 9
4 3 7 8 0 5 2 1 6 9
0 5 7 8 4 3 9 2 1 6
5 7 6 3 8 4 2 0 1 9
4 6 0 2 8 1 3 9 5 7
4 0 5 1 7 9 6 2 8 3
3 8 5 6 1 7 2 4 0 9
0 4 6 2 9 5 8 3 1 7
1 3 6 8 2 7 5 9 0 4
5 1 7 9 8 0 6 4 2 3

I would appreciate advice especially in the following areas:

Code style (readability, naming conventions, etc...)
Class design
Efficiency (how to avoid unnecessary complexity)
Reinventing the wheel (does the STL offer functionality that I should use?)
Are there perhaps bugs that I am not seeing right now?

Please be as hard as possible with this implementation and give me constructive feedback.
main.cpp
#include <iostream>
#include "random_index.hpp"

int main() {
    unsigned int size = 10;
    RandomIndex rand_idx(size);

    unsigned int n = 0;
    for (unsigned int i=0; i<100; ++i, ++n) {
        std::cout << rand_idx.get_index() << ' ';
        if ((n+1) % size == 0) {
            std::cout << '\n';
        }
    }

    std::cout << '\n';
}

random_index.cpp
#include "random_index.hpp"

RandomIndex::RandomIndex(unsigned int _size) {
    size = _size;
    index.resize(_size, 0);
    std::iota(index.begin(), index.end(), 0);
}

unsigned int RandomIndex::get_index() {
    if (counter < size) {
        return index[counter++];
    } else {
        counter = 0;
        std::random_shuffle(index.begin(), index.end());
        return index[counter++];
    }
}

random_index.hpp
#ifndef RANDOM_INDEX_H
#define RANDOM_INDEX_H

#include <vector>
#include <numeric>
#include <algorithm>

class RandomIndex {

    public:
        RandomIndex(unsigned int _size);
        unsigned int get_index();

    private:
        unsigned int size;
        unsigned int counter = 0;
        std::vector<unsigned int> index;

};

#endif

I compiled the code using the following command:
g++ -O -Wall main.cpp random_index.cpp


texts: Summing two objects without altering either

texts:
In the slow progress of the project that generated my all-but-tumbleweed previous question I've needed to make sum-unions (any better term?) of simple objects where key:value is sizeClass:tally -- I need the union of all sizeClasses, summing their values where they're the same.  I came up with this and I wonder whether anyone sees anything terrible about it or has a slicker way.

function mashObj(objA,objB) {
  var objC = {};
  var [ak,av] = deval(objA);
  var [bk,bv] = deval(objB);
  for (var i=0;i<ak.length;i++) {
    objC[ak[i]] = av[i];
  }
  for (i=0;i<bk.length;i++) {
    objC[bk[i]] = (objC[bk[i]] || 0) + bv[i];
  }
  return objC;
}
function deval(obj) {
  var ks = [];
  var vs = [];
  for (var k in obj) {
    ks.push(k);
    vs.push(Math.round(obj[k]));
  }
  return [ks, vs];
}

These functions are purpose-built, plenty of assumption about what's coming in, so there's been no attempt at generalizing.  I go through deval() rather than doing a for..in because I also need to preserve the original two objects -- I've been getting into a lot of trouble with the spooky-manipulation-at-a-distance problem.

By "sum-union" all I mean is that I might have something like:

plot1 = {2:4, 5:12, 7:3};
plot2 = {2:1, 4:3, 5:3};
  // and what I want to get is
total == {2:5, 4:3, 5:15, 7:3};

I assume that somewhere in math, logic or CS, probably all three, there's a proper term for this.


texts: Running SQL and mapping the reader to objects

texts:
I currently have a method in my repository that will run SQL and map the reader to objects:

protected IEnumerable<T> Query<T, TFactory>(string sql, List<IDbDataParameter> parameters = null) where TFactory : IFactory<T>
{
    List<T> list = new List<T>();

    var factory = Activator.CreateInstance<TFactory>();
    var connection = (Db == null) ? Connection : Db.Connection;

    using (var manager = new DbCommandManager(connection, sql))
    {
        if (parameters != null)
            foreach (var parameter in parameters)
                manager.AddParameter(parameter);

        using (var reader = manager.GetReader())
        {
            while(reader.Read())
                list.Add(factory.CreateTFromReader(reader));
        }
    }

    return list;
}

To use the following you simply do:

public IEnumerable<Code> GetCodeWType(string CodeType, string Code)
{
    var sql = @"Select CODE_TYPE, CODE, DESCRIPTION From Codes  Where (CODE_TYPE = :1) AND (CODE = :2)";

    var parameters = new List<IDbDataParameter>();
    parameters.Add(DbFactory.GetParameter(":1", CodeType, DbType.String));
    parameters.Add(DbFactory.GetParameter(":2", Code, DbType.String));

    return this.Query<Code, CodeFactory>(sql, parameters);
}

I would love to hear thoughts and feedback on how I can improve.


texts: benchmarking sorting algorithms: std::sort vs my naive radix

texts:
I'm comparing performance of two sorting algorithms applied to sort integers using google benchmark.
I'm quite surprised by the results so wanted to ask if you see some mistakes in the way I measure the performance. I would expect performance of my naive radix sort to be much worse that std::sort because it is supposed to be bandwidth bound.
#include <benchmark/benchmark.h>

#include <random>
#include <vector>
#include <array>
#include <algorithm>

#define TEST_SIZE DenseRange(50000, 1000000, 50000)

class SortingBmk : public benchmark::Fixture
{
public:
    using T = int32_t;
    std::vector<T> m_vals;

    void SetUp(const ::benchmark::State& state)
    {
        const auto n = state.range(0);
        m_vals.resize(n);
        std::iota(m_vals.begin(), m_vals.end(), 0);

        std::random_device rd;
        std::mt19937 g(rd());
        std::shuffle(m_vals.begin(), m_vals.end(), g);
    }

    void TearDown(const ::benchmark::State& state) {}
};

BENCHMARK_DEFINE_F(SortingBmk, StdSort)(benchmark::State& state)
{
    const auto n = state.range(0);

    std::vector<T> values(m_vals.size());
    for (auto _ : state)
    {
        std::copy(m_vals.begin(), m_vals.end(), values.begin());

        std::sort(values.begin(), values.end());
        benchmark::DoNotOptimize(values);
        benchmark::ClobberMemory();
    }
}
BENCHMARK_REGISTER_F(SortingBmk, StdSort)->Unit(benchmark::kMicrosecond)->TEST_SIZE;

inline int getBits(SortingBmk::T v, SortingBmk::T i) { return (v >> i)&0b11; }
void radixSort_count(std::vector<SortingBmk::T>& data, std::vector<SortingBmk::T>& buf) {
    const int n = data.size();
    std::array<int, 8> psum = {0};
    constexpr auto sz = sizeof(SortingBmk::T) * 8 - 2;
    for (SortingBmk::T i = 0; i < sz; i += 2) {
        //count sort
        for (int v : data) {
            auto bits = getBits(v, i);
            ++psum[bits];
        }
        for (int i = 1; i < 8; ++i)
            psum[i] += psum[i-1];
        for (int j = n - 1; j>= 0; --j) {
            auto bits = getBits(data[j], i);
            --psum[bits];
            assert(psum[bits] < buf.size());
            buf[ psum[bits] ] = data[j];
        }
        swap(buf, data);
        psum = {0};
    }
}

BENCHMARK_DEFINE_F(SortingBmk, NaiveRadixSort)(benchmark::State& state)
{
    const auto n = state.range(0);

    std::vector<T> values(m_vals.size());
    std::vector<T> buffer(m_vals.size());
    for (auto _ : state)
    {
        std::copy(m_vals.begin(), m_vals.end(), values.begin());

        radixSort_count(values, buffer);
        for (int i = 1; i < values.size(); ++i)
            assert(values[i-1] < values[i]);
        benchmark::DoNotOptimize(values);
        benchmark::ClobberMemory();
    }
}
BENCHMARK_REGISTER_F(SortingBmk, NaiveRadixSort)->Unit(benchmark::kMicrosecond)->TEST_SIZE;

BENCHMARK_MAIN();

UPD: X-axis is number of elements in the array, Y-axis is time spend on computations in average for all the times I run the code within for loop. It is in kMicrosecond.


texts: Is there a more-succinct way to employ null conditional operator followed by an awaitable with await?

texts:
It's known that something like this
await currentPage.NextPageRequest?.GetAsync();

will throw an NRE if NextPageRequest is null because you cannot await null.  The solution is to do something like this:
await (currentPage.NextPageRequest?.GetAsync(cancellationToken)
    ?? Task.FromResult(default(IUserMessagesCollectionPage)));

Is there a more-succinct way to do this, maybe in later versions of C#?


texts:
This code asks for letters and a number of letters per word and generates all possible permutations. Then compares those permutations with an English dictionary and creates a list with all the words that match with the dictionary. Finally, it prints the list on a new terminal. The problem is that when words are long (about 10 letters each) I run out of memory. Any suggestions to improve this code and to try to solve the memory problem?

EDIT: my aim is to get 'real' words after typing some letters (e.g input: wxtisneo; letters_per_word: 3; output: one, two, six...)

import os
import itertools
import string
import sys
from sets import Set

def check_files():
    if 'all_combinations_list.txt' in os.listdir('/tmp'):
        os.remove('/tmp/real_words.txt')

def factorial_formula(v):
    a = 1
    if v < 0:
        return 0
    elif v == 0:
        return 1
    else:
        for i in range(2, v+1):
            a = a*i
        return a

def combinations_formula():
    w = len(split_letters)
    x = factorial_formula(w)
    y = (w - number_input)
    z = factorial_formula(y)
    total = x / z
    return total

def possible_existing_words():
    dictionary = [i.strip() for i in open('/usr/share/dict/american-english').readlines()]
    raw_all_combinations = list(itertools.permutations(split_letters, number_input))
    all_combinations = [''.join(word) for word in raw_all_combinations]
    real = set(all_combinations).intersection(dictionary)
    real_2 = list(real)
    output_file = open('/tmp/real_words.txt', 'w')
    with open('/tmp/real_words.txt', 'w') as out:
        for e in real_2:
            separated_words = str(e)
            print >>out, separated_words
    os.system("gnome-terminal -e 'bash -c \"cat /tmp/real_words.txt; exec bash\"'")
    print ''' FINISHED
'''

if __name__ == "__main__":
    os.system('clear')
    check_files()
    letter_input = raw_input(' Type in letters: ')
    number_input = int(raw_input(' Letters per word: '))
    split_letters = list(letter_input)
    letter_input
    number_input
    if ' ' in split_letters:
        print '''
 ERROR: White space typed
 '''
        sys.exit()
    elif len(split_letters) < number_input:
        print '''
 ERROR: More letters in word than typed
 '''
        sys.exit()
    print '''

 Creating %s different combinations...''' % combinations_formula()
    print ' Detecting dictionary matches...'
    possible_existing_words()
    sys.exit()


texts: Recursively evaluate neighbors in a two dimensional grid

texts:
I'm creating a puzzle mini game where there is a board of gems, varying in color, and chosen at random.

This is what my code generates:

When you click on a gem the game should traverse the board and find all connecting gems of the same color. When you click the orange square all orange square neighbors are selected.

Here is my Board class. The locateNeighbors() method recursively searches adjoining grid tiles until it reaches a non-matching gem or the edge of the board.

public class Board {

    public int rows, columns;
    public int x, y;
    private GemPool pool;
    private Gem[][] board;

    public Board(int rows, int columns) {

        x = 0;
        y = 0;

        this.rows = rows;
        this.columns = columns;

        board = new Gem[rows][columns];
        pool = new GemPool(COLOR.BLUE, COLOR.RED, COLOR.YELLOW, COLOR.GREEN, COLOR.ORANGE, COLOR.PURPLE);

        for(int i = 0; i < rows; i++) {
            for(int j = 0; j < columns; j++) {
                board[i][j] = pool.grabGem();
            }
        }

    }

    public Gem at(int row, int column) {

        return board[row][column];

    }

    public void draw(SpriteBatch batch) {

        for(int i = 0; i < rows; i++) {
            for(int j = 0; j < columns; j++) {
                String color = board[i][j].getColorName();
                //I'm aware of the magic numbers here
                batch.draw(pool.grabTexture(color), (i * 72) + x, (j * 72) + y);
            }
        }

    }

    public void dispose() {

        pool.dispose();

    }

    public void click(Vector3 touchPos) {

            //I'm aware of the magic numbers here
            int x = (int)(touchPos.x / 72);
            int y = (int)(touchPos.y / 72);

            if(x < rows && y < columns) {
                Gem g = this.at(x, y);
                HashSet<Point> matches = new HashSet<Point>();
                locateNeighbors(x, y, g.getColor(), matches);
                System.out.println(matches.size() + " matches found.");
            }

    }

    private void locateNeighbors(int x, int y, COLOR color, HashSet<Point> matches) {

        Point p = new Point(x, y);

        if(matches.contains(p))
        {
            return;
        }
        else
        {
            matches.add(p);
        }

        //Check north
        if(y + 1 < columns)
        {
            if(this.at(x, y + 1).getColor() == color)
                locateNeighbors(x, y + 1, color, matches);
        }

        //Check east
        if(x + 1 < rows)
        {
            if(this.at(x + 1, y).getColor() == color)
                locateNeighbors(x + 1, y, color, matches);
        }

        //Check south
        if(y - 1 >= 0)
        {
            if(this.at(x, y - 1).getColor() == color)
                locateNeighbors(x, y - 1, color, matches);
        }

        //Check west
        if(x - 1 >= 0)
        {
            if(this.at(x - 1, y).getColor() == color)
                locateNeighbors(x - 1, y, color, matches);
        }

    }

}

I would love your opinions on optimizations that could be made to the recursive method.


texts: Displaying random "ads" from an XML document

texts:
I have an XML document that contains "ads" and includes information about the department name, image name, link to URL, and alt text.  I have a PHP function that accepts two arguments, department name and the number of "ads" to display.  It reads through the entire XML document, and stores the information in arrays if the department name matches what is passed to the argument or matches  "all".  What I have works, but it seems rather long and cumbersome.  Is there a way to shorten it and improve performance?

PHP

function rightAds($deptName, $displayNumber) {
  //load xml
  /* --- Original loading, left in for completeness
  $completeurl = "http://example.com/example.xml";
  $xml = simplexml_load_file($completeurl);
  --- */

  //Loading without an HTTP call, as per Corbin's point
  $xml = simplexml_load_file(dirname(__FILE__)."/smallAdsByDepartment.xml");

  $smallAds = $xml->smallAds;

  //number of ads that can be used for department
  $numberForDepartment = 0;

  //loop through xml document, save the ads that are "all" or the department name
  foreach($smallAds as $ad) {

    //get department name
    $departmentName = $ad->departmentName;

    //if it is a valid department, add info to corresponding arrays
    if((strpos($departmentName, $deptName) !== false) || (strpos($departmentName, "all") !== false)) {

      //PT exception.  If department name includes noPT, and provided name is pt, don't include the image
      if(($deptName == "pt" && strpos($departmentName, "noPT") !== false) || (strpos(dirname($_SERVER['PHP_SELF']), "pt") !== false && basename($_SERVER['REQUEST_URI']) == "admissions.php" &&  strpos($departmentName, "noPT") !== false )) {
        continue;
      }
      //CLS exception.
      if(($deptName == "cls" && strpos($departmentName, "noCLS") !== false)) {
        continue;
      }

      $name[$numberForDepartment] = $ad->name;
      $alt[$numberForDepartment] = $ad->alt;
      $linkTo[$numberForDepartment] = $ad->linkTo;
      $numberForDepartment++;
    }
  }

  //if $displayNumber is 1, or an invalid negative number, display random ad.
  if($displayNumber <= 1) {
    $randKeys = mt_rand(0, $numberForDepartment);
    echo "

";
  }
  else {
        //get a list of randomly selected keys from the array
        $randKeys = range(0, (count($name) - 1));
        shuffle($randKeys);

        $numberOfAds = 0;

        //loop through and display image/link for each
        foreach($randKeys as $adNumber) {
            echo "

";
            $numberOfAds++;
            if($numberOfAds == $displayNumber) { break; }
        }
   }
}

Example XML

<smallAds>
    <departmentName>all</departmentName>
    <name>smallAd3.jpg</name>
    <alt>Faculty Research</alt>
    <linkTo>http://example.com/research/index.php</linkTo>
</smallAds>
<smallAds>
    <departmentName>all, noPT</departmentName>
    <name>smallAd6.jpg</name>
    <alt>Advising</alt>
    <linkTo>http://example.com/advising.php</linkTo>
</smallAds>
<smallAds>
    <departmentName>all, noCLS</departmentName>
    <name>checkYouTube.png</name>
    <alt>Check us out on YouTube</alt>
    <linkTo>http://www.youtube.com/user/example</linkTo>
</smallAds>


texts: MySQL query to select messages related to a user

texts:
Could someone please check my query and the table structures and let me know if there is any way to improve it.

I would like some tips for my own personal development

Query in PHP:

// Load all records so can be displayed in list
function load_all($page = NULL, $chat_type = NULL){
    if(!$page)$page = 1;
    $start = ($page - 1) * ITEMS_PER_PAGE_ADMIN;

    $query = "";
    $query .= "SELECT direct_message.*, IFNULL(direct_message_group.staff_id, 0) as staff_id FROM `direct_message`
               LEFT JOIN direct_message_group ON direct_message_group.chat_id = direct_message.id
               INNER JOIN direct_message_thread ON direct_message_thread.chat_id = direct_message.id
               WHERE";

    $query .= " (
                    (
                        direct_message.recipient_id = '".addslashes(session::getAdministratorStaff()->id)."'
                        OR direct_message.creator_id = '".addslashes(session::getAdministratorStaff()->id)."'
                        OR (
                            direct_message_group.staff_id = '".addslashes(session::getAdministratorStaff()->id)."'
                            AND direct_message_group.active = '0'
                        )
                    )
                )";

    $query .= " AND direct_message.school_id = '".addslashes(session::getAdministratorStaffSchoolID())."'
                AND direct_message_thread.school_id = direct_message.school_id
                GROUP BY direct_message.id
                ORDER BY direct_message_thread.inserted DESC LIMIT $start, ".ITEMS_PER_PAGE_ADMIN;

    $rows = database::select($query);
    foreach($rows as $row){
        $holding = new direct_message();
        $holding->_populate($row);
        $this->direct_messages[] = $holding;
    }
}

Table structures:

---------------------------------------------------

---------------------------------------------------