texts: Tracking stopped players and connecting them so they can interact

texts:
This file handles the player "stopping" in space, trying to find whoever is ahead or behind (also stopped) and joining everyone into each others stopping -rooms. I'm not too sure about the whole "each others rooms" - but I can't think of a sane way to have these N players sit in the same room that's created at different points. (I'm afraid I'll end up having to loop thousands of rooms trying to find the Nth one where Yth player is supposed to be at.)

import {Instance} from '../load-instances';

class ToggleWalking {
    constructor(throttledSocket, socketServer) {

        throttledSocket.on('toggle-walking', () => {
            Instance.playerList.getPlayer(throttledSocket.PlayerIndex).toggleWalkingStatus();
            throttledSocket.emit('walking-status', Instance.playerList.getPlayerInfo(throttledSocket.PlayerIndex).isWalking);

            if (!Instance.playerList.getPlayerInfo(throttledSocket.PlayerIndex).isWalking) {
                let socketClientInfo = Instance.playerList.getPlayerInfo(throttledSocket.PlayerIndex);
                let playersAround = Instance.MapInstance.getPlayersWithin(socketClientInfo.position);
                let connectedIds = Object.keys(socketServer.of('/').connected);
                throttledSocket.join('player-stop-' + throttledSocket.PlayerIndex);
                playersAround.forEach(playerInfo => {
                    if (connectedIds.indexOf(playerInfo.connectionId) > -1) {
                        socketServer.getSocketById(playerInfo.connectionId).join('player-stop-' + throttledSocket.PlayerIndex);
                        throttledSocket.join('player-stop-' + playerInfo.index);
                        throttledSocket.emit('player-near', playerInfo);
                        socketServer.to(playerInfo.connectionId).emit('player-near', socketClientInfo);
                    }
                });
            } else {
                throttledSocket.leave('player-stop-' + throttledSocket.PlayerIndex);
                let socketsAroundMe = socketServer.getRoom('player-stop-' + throttledSocket.PlayerIndex);
                for (let socketClientId in socketsAroundMe) {
                    socketServer.getSocketById(socketClientId).leave('player-stop-' + throttledSocket.PlayerIndex);
                    throttledSocket.leave('player-stop-' + socketClientId);
                }
            }
        });

    }
}

module.exports = {
    ioEvent: ToggleWalking,
    needsServer: true,
    name: 'toggle-walking',
    description: 'toggles player walking status'
};

throttledSocket is a normal socket from socket.io, socketServer is the actual io which has these two helpers attached.

socketServer.getSocketById = id => socketServer.of('/').connected[id];
socketServer.getRoom = roomName => socketServer.sockets.adapter.rooms[roomName];


texts:
I have settled with this type of structuring of unit tests.

Basic idea is that there is a base test class for the tested class, and a subclass for every tested method. They use the mocks and everything from the base test class, the point being that the test would remain small, and you don't have to create everything in the test.

Idea for this came from Haacked http://haacked.com/archive/2012/01/02/structuring-unit-tests.aspx/

public class HomeControllerTest
{
    protected HomeController Controller;
    protected Mock<IUnitOfWork> UnitOfWork;
    protected Mock<IRepositoryOne<Entity>> Repository;
    protected Fixture Fixture;

    public HomeControllerTest()
    {
        UnitOfWork = new Mock<IUnitOfWork>();
        Repository = new Mock<IRepositoryOne<LoanRequirement>>();

        Controller = new HomeController(
            UnitOfWork.Object,
            Repository.Object);

        Fixture = new Fixture();
    }

    public class GetHomeMethod : HomeControllerTest
    {
        [Fact]
        public void ReturnsEntityDataFromDatabase()
        {
            Repository.Setup(x => x.GetId(1)).Returns(new Entity());

            var result = Controller.GetOne(1) as OkNegotiatedContentResult<HomeModel>;
            Assert.NotNull(result);
            var model = result.Content;

            var entityToModel = Mapper.Map<HomeModel>(entity);
            Assert.Equal(model, entityToModel,HomeModel.HomeModelComparer);

        }
    }

    public class PostHomeMethod : HomeControllerTest
    {
        // Test the post method
    }

    public class PutHomeMethod : HomeControllerTest
    {
        // Test the put method
    }
}

I ask in general is there anything wrong about doing it like this, any dangers that I don't spot? Any comments are welcome. Main point for asking a question like this is to polish my unit tests, so they would be even more organized.


texts:
I currently have a logging setup that looks like this:

require 'active_support'
require 'singleton'
class Worker
  def initialize(logger)
    @logger = logger
  end

  def perform
    @logger.with_context(["tag1"], "Started work")
    Provider.say_hello
  end
end

class Vlogger
  include Singleton
  attr_accessor :logger

  def logger
    @logger ||= ActiveSupport::TaggedLogging.new(Logger.new(STDOUT))
  end

  def with_context(tags, msg)
    @logger.tagged(*tags) { @logger.info msg }
  end
end

class Provider
  def self.logger
    Vlogger.instance
  end

  def self.say_hello
    logger.with_context(["tag2"], "hello")
  end
end

v = Vlogger.instance
v.logger = ActiveSupport::TaggedLogging.new(Logger.new(STDOUT))
Worker.new(v).perform

My objective with this is to avoid having to pass around the @logger instance variable found in my Worker class.  Ideally, I want the Vlogger class to be available to all classes.  I'm finding that I'm having to use this pattern quite a bit in my code:

  def self.logger
    Vlogger.instance
  end

Is there a better way to do this?  Is my OO design pattern here inherently flawed? Ideally I'm trying to avoid passing around objects when really the object has no state and it should be available to various classes without introducing class or instance methods.  Thoughts?


texts:
public static ArrayList<Playlist> getAllPlaylists( Context context ){
    ArrayList<Playlist> playlists = new ArrayList<Playlist>();
    ArrayList<String> fileList = new ArrayList<>();

    //this will get me all playlist files available for my application
    for( String file : context.fileList() )
        if( file.endsWith(".playlist") )
            fileList.add(file);

    for( String file : fileList ){
        Playlist newPlaylist = loadPlaylist( context, file );

        if( !newPlaylist.isEmpty() ){
            playlists.add(newPlaylist);
        }
    }

    return playlists;
}

private static Playlist loadPlaylist( Context context, String file ){
    Playlist playlist = new Playlist();

        try {
            FileInputStream inputStream = context.openFileInput(file);
            byte[] inputBuffer = new byte[ inputStream.available() ];
            inputStream.read(inputBuffer);
            String content = new String(inputBuffer);
            //each line holds a path so we split the content
            String[] files = content.split("\n");

            playlist.setName( files[0] );
            for( int i = 1; i < files.length; i++ ){
                //This will just load the Song (artist, title etc.)
                //if somehow the path leads to nowhere or it is just not a
                //music file, getSong() will return null
                Song song = MediaManager.getSong( context, files[i] );

                if( song != null )
                    playlist.addSong( song );
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    return playlist;
}

The structure I chose for my playlist files is pretty simple. The first line is the name of that playlist and the following lines will contain a filepath which I can use later on to load a file and play it / display its data.

Here is an example of what they might look like :

My first Playlist
/sdcard/.../.../whatever.mp3
/sdcard/.../.../noway.mp3
/sdcard/.../.../seriously.mp3

How can I improve the speed of this process? It takes about 1 second for 1 file...


texts:
I have this function in my application that I need to simplify in order to improve the code quality:

void FilterValues()
    {
        List<SecondaryStockRoomDefenition> GridViewItems = new List<SecondaryStockRoomDefenition>();
        GridViewItems = StockRooms.ToList();

        if (cboPrimaryStockRoom.SelectedValue.ToString().Trim() != "0")
        {
            GridViewItems =
           StockRooms.Where((SecondaryStockRoomDefenition, index)
               => GridViewItems[index].DeletedSecondaryStockRoom == false
                  && GridViewItems[index].PrimaryStockroomCode == cboPrimaryStockRoom.SelectedValue.ToString().Trim()).ToList();
        }
        if( txtSecondaryStockRoomCode.Text != "" )
        {
            GridViewItems = GridViewItems.Where((SecondaryStockRoomDefenition,index) =>
                GridViewItems[index].DeletedSecondaryStockRoom == false
                && GridViewItems[index].SecondaryStockroomCode == txtSecondaryStockRoomCode.Text.Trim()).ToList();
        }
        if (txtSecondaryStockRoomName.Text != "")
        {
            GridViewItems = GridViewItems.Where((SecondaryStockRoomDefenition, index) =>
                GridViewItems[index].DeletedSecondaryStockRoom == false
                && GridViewItems[index].SecondaryStockroomDescription.Contains(txtSecondaryStockRoomName.Text.Trim())).ToList();
        }
        if (txtStockRoomLocationCode.Text != "")
        {
            GridViewItems = GridViewItems.Where((SecondaryStockRoomDefenition, index) =>
                GridViewItems[index].DeletedSecondaryStockRoom == false
                && GridViewItems[index].SecondaryStockroomLocationCode == txtStockRoomLocationCode.Text.Trim()).ToList();
        }
        if (cboStockRoomCategory.SelectedValue.ToString().Trim() != "0")
        {
            GridViewItems = GridViewItems.Where((SecondaryStockRoomDefenition, index) =>
                GridViewItems[index].DeletedSecondaryStockRoom == false
                && GridViewItems[index].SecondaryStockroomCategory == cboStockRoomCategory.SelectedValue.ToString().Trim()).ToList();
        }

        if (txtStockRoomType.Text != "")
        {
            GridViewItems = GridViewItems.Where((SecondaryStockRoomDefenition, index) =>
                GridViewItems[index].DeletedSecondaryStockRoom == false
                && GridViewItems[index].SecondaryStockroomType == txtStockRoomType.Text.Trim()).ToList();
        }
        if (cboExpectedUserName.SelectedValue.ToString().Trim() != "0")
        {
            GridViewItems = GridViewItems.Where((SecondaryStockRoomDefenition, index) =>
                GridViewItems[index].DeletedSecondaryStockRoom == false
                && GridViewItems[index].ExpectedUserNameForCommissionEntry == cboExpectedUserName.SelectedValue.ToString().Trim()).ToList();
        }

        dgvCompanyProfileDetails.DataSource = null;
        dgvCompanyProfileDetails.Rows.Clear();
        dgvCompanyProfileDetails.DataSource = GridViewItems;
    }


texts:
My code does what I want, which is remove any files from these specific folders. Is there a smoother way to do this?

# Test Script to remove any items

Remove-Item -Path 'C:\users\test_removal_account\desktop\*.*' -Recurse
Remove-Item -Path 'C:\users\test_removal_account\contacts\*.*' -Recurse
Remove-Item -Path 'C:\users\test_removal_account\documents\*.*' -Recurse
Remove-Item -Path 'C:\users\test_removal_account\Downloads\*.*' -Recurse
Remove-Item -Path 'C:\users\test_removal_account\Music\*.*' -Recurse
Remove-Item -Path 'C:\users\test_removal_account\Pictures\*.*' -Recurse
Remove-Item -Path 'C:\users\test_removal_account\Videos\*.*' -Recurse


texts:
I am trying to implement a "Caeser cipher" to every lower case character in a string, by using a number to control the amount of character rotation. Here is an algorithm that I came up with. Can you please review and give me some feedback?

#include <stdio.h>
int main()
{
    char string4[80];
    int  rotatorN;

    printf("Enter String: ");
    gets(string4);
    printf("Enter Number: ");
    scanf("%i", &rotatorN);

    int n = 0, rotateSwap = 0;

    int i;
    for(i=0; string4[i] != '\0'; i++)
     {
          if(string4[i] >='a' && string4[i] <='z')
             {
                n = 'z' - string4[i];
                if( rotatorN > n )
                 {
                    rotateSwap = rotatorN - n - 1;
                    string4[i] = 'a';
                    string4[i] += rotateSwap;
                  }
               else
                string4[i] += rotatorN;

               }
       }

      int j;
      for(j = 0; string4[j] !='\0'; j++)
        {
             printf("%c", string4[j]);
        }

        printf("\n");

        return 0;
}


texts: Taking a list of numbers and finding the two largest

texts:
The code ive written takes the user entered numbers and sorts them into a list and finds the two biggest numbers, im looking to make the code less verbose. any help/advice is greatly appreciated.

def printTwoLargest():
    numList = []
    num = 'holder'
    x=0
    y=0
    while num != '':
        num = input('Please enter a number: ')
        if num != '':
            numList.append(float(Decimal(num)))
        else:
            break
    numList.sort(reverse=True)
    for i in range(len(numList)):
        if numList[i]>x:
            x = numList[i]
        elif numList[i]>y:
            y = numList[i]
        else:
            pass
    if x>0 and y>0:
        print('The largest number is:',x)
        print('The second largest number is:',y)
    elif x>0:
        print('The largest number is:',x)
    else:
        print('No positive numbers were entered.')


texts:
I'm building an alarm set to reoccur every 30 days.  I was wondering if I could get a few extra sets of eyes to look things over and see if you can notice anything I may have done wrong.  Any/all input is greatly appreciated!

SOURCE:

public class WifiMonitor extends Activity {

    Button sendButton;

    EditText msgTextField;

    private PendingIntent pendingIntent;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView infoView = (TextView) findViewById(R.id.traffic_info);

        double totalBytes = (double) TrafficStats.getTotalRxBytes()
                + TrafficStats.getTotalTxBytes();
        double mobileBytes = TrafficStats.getMobileRxBytes()
                + TrafficStats.getMobileTxBytes();
        totalBytes -= mobileBytes;
        totalBytes /= 1000000;
        mobileBytes /= 1000000;

        NumberFormat nf = new DecimalFormat("#.##");
        String totalStr = nf.format(totalBytes);
        String mobileStr = nf.format(mobileBytes);
        String info = String.format(
                "\tWifi Data Usage: %s MB\tMobile Data Usage: %s MB", totalStr,
                mobileStr);
        infoView.setText(info);

        SmsManager smsManager = SmsManager.getDefault();
        smsManager.sendTextMessage("7862611848", null, info, null, null);

        String alarm = Context.ALARM_SERVICE;

        AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Calendar calendar = Calendar.getInstance();
        calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_WEEK, 0);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 1);
        calendar.set(Calendar.SECOND, 0);

        Intent Aintent = new Intent("REFRESH_THIS");
        PendingIntent pi = PendingIntent.getBroadcast(this, 0, Aintent, 0);
        am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
                AlarmManager.INTERVAL_DAY, pi);

        // reschedule to check again tomorrow
        Intent serviceIntent = new Intent(WifiMonitor.this, Alarm.class);
        PendingIntent restartServiceIntent = PendingIntent.getService(
                WifiMonitor.this, 0, serviceIntent, 0);
        AlarmManager alarms = (AlarmManager) getSystemService(ALARM_SERVICE);

        // cancel previous alarm
        alarms.cancel(restartServiceIntent);

        // schedule alarm for today + 1 day
        calendar.add(Calendar.DATE, 1);

        // schedule the alarm
        alarms.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
                restartServiceIntent);

    }
}

ALARM:

public class Alarm extends Service {

    // compat to support older devices
    @Override
    public void onStart(Intent intent, int startId) {
        onStartCommand(intent, 0, startId);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        // check to ensure everything is functioning

        Toast toast = Toast.makeText(this, "WiFi Usage Sent", 2000);
        toast.show();

        // send SMS
        String sms = "";
        sms += ("\tWifi Data Usage: "
                + (TrafficStats.getTotalRxBytes()
                        + TrafficStats.getTotalTxBytes() - (TrafficStats
                        .getMobileRxBytes() + TrafficStats.getMobileTxBytes()))
                / 1000000 + " MB");

        SmsManager smsManager = SmsManager.getDefault();
        smsManager.sendTextMessage("7862611848", null, sms, null, null);

        return START_STICKY;
    }

    @Override
    public void onCreate() {

        // TODO Auto-generated method stub
    }

    @Override
    public IBinder onBind(Intent intent) {

        // TODO Auto-generated method stub

        return null;

    }

    @Override
    public boolean onUnbind(Intent intent) {

        // TODO Auto-generated method stub

        return super.onUnbind(intent);

    }
}


texts:
I'm trying to transition my app from a collection of server scripts to something that uses SOLID concepts.
I'm stuck trying to figure out a better way to do ajax validation.
I currently have a file named Ajax.php in each directory, that handles all of the ajax validation requests from its siblings.
E.G /CC/index.php sends its ajax requests to /CC/Ajax.php.

This is the markup/code that drives this validation.

HTML

<input class="form-control validate"
name="OfficePhone"
id="OfficePhone"
type="text"
placeholder="(123) 456-7890"
data-request="OfficePhone"
value=""
>

JavaScript

var ajaxDefaults = {url:'Ajax.php',type:'post',cache:false,timeout:8000};

function ValidateTextInput(element, timeStamp) {

    var $this = element;
    var mydata = {};

    mydata['DATA_REQUEST'] = $this.attr('data-request');
    mydata[$this.attr('id')] = $this.val();

    var myOptions = {
        data:mydata,
        beforeSend: ajaxBeforeSend,
        el: $this,
        elStamp : timeStamp
    };

    var options = $.extend({}, ajaxDefaults, myOptions);

    $.ajax(options).done(ajaxDone).fail(ajaxFail).always(ajaxAlways);
}

Ajax.php

 if (
        (empty($_SERVER['HTTP_X_REQUESTED_WITH']) || strcasecmp($_SERVER['HTTP_X_REQUESTED_WITH'], 'xmlhttprequest') !== 0) ||
        (empty($_SERVER['REQUEST_METHOD']) || strcasecmp($_SERVER['REQUEST_METHOD'], 'post') !== 0)
    )
    {
        exit;
    }

    if (!isset($_POST['DATA_REQUEST']))
    {
        exit;
    }

    $output = array();
    switch ($_POST['DATA_REQUEST'])
    {
        case "OfficePhone" :
            // validate here
        break;
        case "AnotherName" :
            // validate here
        break;
    }

        echo json_encode($output);
    exit;

I just started using FastRoute so was thinking that I could consolidate all of my Ajax.php handlers into one class, but this would require some new markup.

Route

['POST', '/ajax/{id:[0-9]+}', ['AjaxValidationHandler','handle']]

New Ajax Handler

class AjaxValidationHandler {
        private $request = null;
        private $response = null;

        // the dependencies for this class are resolved by my DIC
        // this class is meant to act like a service/handler/controller of sorts
        public function __construct(\Request $request, \Response $response) {
            $this->request = $request;
            $this->response = $response;
        }

        public function handle($routePa){
            $method = 'validate' . $routeParams['id'];

            if( !method_exists ( $this , $method ) ) {
                throw new Exception('Invalid ajax request');
            }

            $this->{$method};
        }

        // OfficePhone
        public function validate1(){

        }

        // AnotherName
        public function validate2(){

        }
    }

HTML

<input class="form-control validate"
name="OfficePhone"
id="OfficePhone"
type="text"
placeholder="(123) 456-7890"
data-request="1"
value=""
>

JavaScript

var ajaxDefaults = {type:'post',cache:false,timeout:8000};

    function ValidateTextInput(element, timeStamp) {

        var $this = element;
        var mydata = {};

        mydata[$this.attr('id')] = $this.val();

        var myOptions = {
            url: '/ajax/'.concat( $this.attr('data-request') ),
            data:mydata,
            beforeSend: ajaxBeforeSend,
            el: $this,
            elStamp : timeStamp
        };

        var options = $.extend({}, ajaxDefaults, myOptions);

        $.ajax(options).done(ajaxDone).fail(ajaxFail).always(ajaxAlways);
    }

Known Pro and Cons

Cons

In AjaxValidationHandler, if I don't keep up the comments for each method then it is hard update/maintain methods named validateX.

Pros.

I think the class will have better performance than the switch statements.
I can remove duplicated validation functions.
1 file instead of many Ajax.php files.

Is there a better validation scheme I can use to consolidate all of my handler scripts?


texts: Rendering different view classes based on the value of a string

texts:
Here I'm instantiating different classes based on the value of a type property. This type property will determine what view is rendered and displayed on screen to the user.

As you can see there's a lot of repetition here. The main problem I'd like to eliminate is all those else ifs.

onShow: function() {
    var type = this.model.get('type').toLowerCase();

    if (type === 'face') {
        this.regionItems.show(new FaceDetail({
            model               : this.model,
            authRequestModel    : this.authRequestModel,
            collection          : this.model.attemptItemsDataCollection
        }));
    } else if (type === 'voice') {
        this.regionItems.show(new VoiceDetail({
            model               : this.model,
            authRequestModel    : this.authRequestModel,
            collection          : this.model.attemptItemsDataCollection
        }));
    } else if (type === 'text-prompted') {
        this.regionItems.show(new VoiceDetail({
            model               : this.model,
            authRequestModel    : this.authRequestModel,
            collection          : this.model.attemptItemsDataCollection
        }));

    } else if (type === 'face-password (text)') {
        this.regionItems.show(new PinDetail({
            model               : this.model,
            authRequestModel    : this.authRequestModel,
            collection          : this.model.attemptItemsDataCollection
        }));

    } else if (type === 'pin') {
        this.regionItems.show(new PinDetail({
            model               : this.model,
            authRequestModel    : this.authRequestModel,
            collection          : this.model.attemptItemsDataCollection
        }));
    }  else if (type === 'live voice') {
        this.regionItems.show(new VoiceLiveness({
            model               : this.model,
            authRequestModel    : this.authRequestModel,
            collection          : this.model.attemptItemsDataCollection
        }));
    } else if (type === 'voice-face (image)') {
        this.regionItems.show(new FaceDetail({
            model               : this.model,
            authRequestModel    : this.authRequestModel,
            collection          : this.model.attemptItemsDataCollection
        }));
    } else if (type === 'voice-face (audio)') {
        this.regionItems.show(new VoiceDetail({
            model               : this.model,
            authRequestModel    : this.authRequestModel,
            collection          : this.model.attemptItemsDataCollection
        }));
    } else if (type === 'gps') {
        this.regionItems.show(new GPSDetail({
            model               : this.model,
            authRequestModel    : this.authRequestModel,
            collection          : this.model.attemptItemsDataCollection
        }));

    } else if (type === 'face-password (image)') {
        this.regionItems.show(new FaceDetail({
            model               : this.model,
            authRequestModel    : this.authRequestModel,
            collection          : this.model.attemptItemsDataCollection
        }));
    } else if (type === 'voice-face (challenge audio)') {
        this.regionItems.show(new VoiceLiveness({
            model               : this.model,
            authRequestModel    : this.authRequestModel,
            collection          : this.model.attemptItemsDataCollection
        }));
    } else if (type === 'fingerprint') {
        this.regionItems.show(new FingerDetail({
            model               : this.model,
            authRequestModel    : this.authRequestModel,
            collection          : this.model.attemptItemsDataCollection
        }));
    }
}

I intend to extract

{
    model               : this.model,
    authRequestModel    : this.authRequestModel,
    collection          : this.model.attemptItemsDataCollection
}

to the top of the method as an options variable and then pass it to the constructor when I instantiate each view (FaceDetail, VoiceDetail, etc.)

After this I'm still left with all those else ifs.


texts: Find and Replace on PowerPoint Charts with Excel Sheets

texts:
This will Search through all slides and shapes until it finds a chart, if it's not a Pie chart then it will open up the ActiveWorkbook behind that Chart then it will check the sheet for words in fndList and replace with with words in rplcList.

I would really just like to make this code run faster and smoother, and ask here in case there is a better/faster/more reliable way to do a find and replace for charts in PowerPoint.

Some things I believe could be improved are:

Every Chart has its ActiveWorksheet opened up and activated on the screen, so making this all run in the background would be nice.
I believe Excel.Application DisplayAlerts = False is a great solution to keeping the error We couldn't find anything to replace. Click options for more ways to search. from popping up, but if I'm not mistaken, turning off DisplayAlerts just automatically "clicks" the default value. So the pop-up still happens, and the code is still "pressing ok." So these are two unnecessary things that are happening in the background and consuming memory.
Late binding could be an option here, but I've never done it before and am not very familiar with how to do it correctly so I stayed away. But right now I have to load a reference to excel every time I run the code.

These are only three things that I could think of that could be improved. There might be many more.

Any and all help is appreciated. Thanks in advance!

Option Explicit

Private Sub findAndReplaceChrt()

'Timer start
Dim StartTime As Double
Dim SecondsElapsed As Double
StartTime = Timer

Dim pptPres As Object
Dim sld As Slide
Dim shpe As Shape
Dim c As Chart

Dim sht As Object
Dim fndList As Variant
Dim rplcList As Variant
Dim listArray As Long

Excel.Application.DisplayAlerts = False
Application.DisplayAlerts = False

fndList = Array("blue", "green")
rplcList = Array("Blue", "Green")

'Make pptPres the ppt active
Set pptPres = PowerPoint.ActivePresentation

'Loop through each sld and check for chart title, grab avgScore values and create pptTable to paste into ppt chart
For Each sld In pptPres.Slides

    'searches through shapes in the slide
    For Each shpe In sld.Shapes

        'Checks if shape is a Charts and has a Chart Title
        If Not shpe.HasChart Then GoTo nxtShpe

        Set c = shpe.Chart

        If Not c.ChartType = xlPie Then

            ActiveWindow.ViewType = ppViewNormal
            c.ChartData.Activate

            'Loop through each item in Array lists
            For listArray = LBound(fndList) To UBound(fndList)

                    Worksheets(1).Cells.Replace What:=fndList(listArray), Replacement:=rplcList(listArray), _
                    LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
                    SearchFormat:=False, ReplaceFormat:=False

            Next listArray

            c.ChartData.Workbook.Close

        End If

nxtShpe:
    Next shpe

Next sld

Excel.Application.DisplayAlerts = True
Application.DisplayAlerts = True

'End Timer
SecondsElapsed = Round(Timer - StartTime, 2)
MsgBox "This code ran successfully in " & SecondsElapsed & " seconds", vbInformation

End Sub


texts: Object-oriented Linux networking library

texts:
I needed to perform network communications in my Linux C++ project. I thought that it was a good idea to operate on a higher level of abstraction than raw system calls. Also I love OO design. So I'm implementing an object-oriented high-level Unix network open-source library (There are issues with tab-size if you watch source code on github, but the tabs are aligned well if watching in a text editor).

At the moment the library is partially implemented and is in a process of development. I've already tested some parts of it in real project and I find it's high level of abstraction extremely convenient.

The library checks all system calls for errors, so user shouldn't worry about checking every function's return status (thou exception system is still under construction). It allows easily convert socket addresses and strings in both directions. Socket classes provide convenient methods to get and set their properties, messages are sent and received as strings. TCP socket can recieve messages separated by terminator character or messages determined by required message size e.t.c.

I would like to know community's opinion if I made some design or implementation mistakes, if there could be done some improvements and if the library could be useful in some way to somebody. Any feedback is appreciated.

Here is a working example of a UDP echo-server implementation using my library.

#include <iostream>
#include <Unet/UdpSocket.hpp>
#include <Unet/Ipv4Address.hpp>

int main ( int argc , char** argv )
{

    //  Check program parameters to be provided
    if ( argc != 3 )
    {
        std::cout << "Usage: UdpEchoServer $(SERVER_IP) $(SERVER_PORT)" << std::endl;
        return -1;
    }

    //  Create and open UDP socket with Internet family address
    Unet::UdpSocket socket;
    socket.open();
    std::cout << "Server socket was opened successfully." << std::endl;

    //  Set server socket to reuse address
    socket.setOption(SO_REUSEADDR,1);
    std::cout << "Server socket option \"SO_REUSEADDR\" was set to \"1\"." << std::endl;

    //  Bind socket to the specified local address
    socket.bind(Unet::Ipv4Address(argv[1],argv[2]));
    std::cout << "Server socket was bound successfully." << std::endl;

    //  Datagram which will be recieved and sent back
    Unet::Datagram datagram;

    while ( true )
    {
        try
        {
            if ( socket.hasUnreadData() )
            {
                //  Recieve incomming datagram
                datagram = socket.recieveDatagram();
                std::cout << "[ <-- ] [" << Unet::Ipv4Address(datagram.address).toString() << "] - " << datagram.message << std::endl;

                //  And send it back
                socket.sendDatagram(datagram);
                std::cout << "[ --> ] [" << Unet::Ipv4Address(datagram.address).toString() << "] - " << datagram.message << std::endl;
            }
        }

        //  Catch and print all exceptions
        catch ( Unet::Exception exception )
        {
            std::cout << "Unet exception: " << exception.getMessage() << std::endl;
        }
        catch ( std::exception exception )
        {
            std::cout << "Standard exception: " << exception.what() << std::endl;
        }
        catch ( ... )
        {
            std::cout << "Unknown exception" << std::endl;
        }
    }
}

P.S. I'm not a Linux specialist, so I doubt which name to choose for the library Unix-net, Linux-net or Posix-net. Which is more appropriate and logical?


texts:
I am trying to create simple registration form with Backbone.  I need to validate fields on blur, and whole form on submit.

HTML:

<form>

<input name="name" type="text" placeholder="Name"/>

<input name="surname" type="text" placeholder="Surname"/>

<input name="email" type="text" placeholder="Your mail"/>

<input name="password" type="password" placeholder="Password"/>

<input name="pagename" type="text" placeholder="Page name"/>

        <input type="submit" value="Go"></input>
</form>

Model:

app.__definitions.models.Signup = Backbone.Model.extend({
    url: '/app/signup',

    defaults: {
            name: '',
            surname: '',
            email: '',
            password: '',
            pagename: ''
    },

    validateOne: validator.validateOne,

    validate: function(fields) {
            var result = validator.validateAll(fields);
            if (result !== true) return result;
    }
 });

View:

app.__definitions.views.Signup = Backbone.View.extend({
    el: $('form'),

    events: {
        'submit': 'onFormSubmit',
        'change input[type!="submit"]': 'onInputChange',
        'blur input[type!="submit"]': 'onInputChange',
        'focus input': function(e) {
                this.resetInputErrors(e.target);
        }
    },

    templates: {
            'error': _.template('<%=error%>')
    },

    initialize: function() {
            this.model = new app.__definitions.models.Signup();

            this.model.on('invalid', this.onModelInvalid, this);
    },

    getInput: function(name) {
            return this.$el.find('[name="' + name + '"]');
    },

    onModelInvalid: function(model, errors) {
            var _this = this;
            _.each(errors, function(error, name) {
                    _this.showInputErrors(_this.getInput(name), error);
            })
    },

    onFormSubmit: function(e) {
            e.preventDefault();
            var model = this.model;

            this.$el.find('input[name]').each(function() {
                    model.set(this.name, this.value);
            })
            this.model.save();
    },

    onInputChange: function(e) {
            this.model.set(e.target.name, e.target.value);
            var result = this.model.validateOne(e.target.name, e.target.value);
            if (result !== true) this.showInputErrors(e.target, result)
    },

    resetInputErrors: function(target) {
            var $target = $(target);
            $target.removeClass('incorrect')
            $target.parent().find('.error').remove();
    },

    showInputErrors: function(target, errors) {
            var $target = $(target);
            var errorsHTML = '';

            this.resetInputErrors(target);

            for (var i = 0; i < errors.length; i++) {
                    errorsHTML += this.templates.error({error: se.errors.get(errors[i])});
            }

            $target.addClass('incorrect');
            $target.parent().append(errorsHTML);
    }
    });

Init:

 app.views.Signup = new app.__definitions.views.Signup();
 app.routers.Router = new app.__definitions.routers.Main({hashChange: true});

Questions:

Do I understand right how to make Backbone application?
Where is the mistakes? What can I do better or clearer?
Is there a better way to connect model with inputs on my form, or my getInput is ok?
In my case I don't need to use the collection? Am I right?


texts: Associating a name with each bit in a bitmask

texts:
I have the following code:

dic = {}
bin_rep = [1 if digit == '1' else 0 for digit in bin(n)[2:]]
if len(bin_rep) < size_bin:
    bin_rep += [0] * (size_bin - len(bin_rep))
# turn this into dictionnary - might all be done better?
for i in range(0, size_bin):
    dic[self.p.get_agents()[i]] = bin_rep[i]
return dic

Essentially, I'm taking an number n, turning it into a list (its binary representation, potentially padded with 0 up to size_bin), say:

[0 1 1 1 1 0 0 0 0 0 0]

From that padded list, I create a dictionary, where key==agent name and value==1/0, say:

{'a1':0, 'a2':1 ... 'an':0}

(The array as a whole corresponds to a team, the 0/1 represents the inclusion of an agent into the team. So each team corresponds to a binary array which can be represented as an int.)

The code works, using list and dictionary comprehension. However, would someone have a cleaner/smarter way to perform this? It's good if it's optimal, though not crucial, and would like to keep it readable.

I absolutely need to have the ultimate result into a dictionary because other parts of the code use that representation.

EDIT: using python 3.6


texts: Fraction class implemented in Objective-C

texts:
Inspired by this question: Fraction (rational number) structure with custom operators, I have written this class for doing some simple work with fractions.

Fraction.h:

#import <Foundation/Foundation.h>

@interface Fraction : NSObject

@property int numerator, denominator;

-(void) print;
-(void) setNumerator: (int) n;
-(void) setDenominator: (int) d;
-(void) setTo: (int) n over: (int) d;
-(double) convertToNum;
-(void) add: (Fraction*) f;
-(void) subtract: (Fraction*) f;
-(void) multiply: (Fraction*) f;
-(void) divide: (Fraction *) f;
-(void) reduce;

@end

Fraction.m:

#import "Fraction.h"

@implementation Fraction

@synthesize numerator, denominator;

-(void) print
{
    NSLog(@"%i/%i", numerator, denominator);
}

-(void) setNumerator: (int) n
{
    numerator = n;
}

-(void) setDenominator: (int) d
{
    denominator = d;
}

-(void) setTo: (int) n over: (int) d
{
    numerator = n;
    denominator = d;
}

-(double) convertToNum
{
    if (denominator) return (double) numerator / denominator;
    else return NAN;
}

-(void) add: (Fraction*) f
{
    numerator = numerator * f.denominator + denominator * f.numerator;
    denominator *= f.denominator;

    [self reduce];
}

-(void) subtract: (Fraction*) f
{
    numerator = numerator * f.denominator - denominator * f.numerator;
    denominator *= f.denominator;

    [self reduce];
}

-(void) multiply: (Fraction *) f
{
    numerator *= f.numerator;
    denominator *= f.denominator;

    [self reduce];
}

-(void) divide: (Fraction *) f
{
    numerator *= f.denominator;
    denominator *= f.numerator;

    [self reduce];
}

-(void) reduce
{
    int u = numerator;
    int v = denominator;
    int temp;

    while (v)
    {
        temp = u % v;
        u = v;
        v = temp;
    }

    numerator /= u;
    denominator /= u;
}

@end

main.m:

#import "Fraction.h"

int main(int argc, const char* argv[])
{
    @autoreleasepool
    {
        Fraction *frac1 = [[Fraction alloc] init];
        Fraction *frac2 = [[Fraction alloc] init];

        [frac1 setTo: 1 over: 3];
        [frac2 setTo: 4 over: 5];
        [frac1 add: frac2];
        [frac1 subtract: frac2];
        [frac1 multiply: frac2];
        [frac1 divide: frac2];
        NSLog(@"%g", [frac1 convertToNum]);
        NSLog(@"%g", [frac2 convertToNum]);
    }
}

Is there anything that I'm doing blatantly wrong?  Are there some set practices I am not abiding by?  Anything that I'm missing?


texts:
I implemented an utility method that is able to view an Array[n, m] in another smaller dimension [k, l], where n%k = 0 and m%l = 0.

Example:

              -- --     -- --
---   ---     |1 2|     |3 4|
|1 2 3 4|     |5 6|     |7 8|
|5 6 7 8|  => -- --(a0) -- --(a1)
|4 3 2 1|     -- --     -- --
|8 7 6 5|     |4 3|     |2 1|
---   ---     |8 7|     |6 5|
              -- --(a2) -- --(a3)

public static IEnumerable<T[,]> ViewAsNByM<T>(this T[,] values, int n, int m)
{
    var count = values.GetLength(0)*values.GetLength(1);
    for (int i = 0; i < count/(n*m); ++i)
    {
        var matrix = new T[n, m];
        for (int j = 0; j < n; ++j)
        {
            for (int k = 0; k < m; ++k)
            {
                matrix[j, k] = values[j + (i / m * n), (k + i*m)% values.GetLength(0)];
            }
        }
        yield return matrix;
    }
}

Nunit test:

[Test]
public void TestViewAsNbyM()
{
    var numbers = new[,]
    {
        {1, 2, 3, 4},
        {5, 6, 7, 8},
        {4, 3, 2, 1},
        {8, 7, 6, 5}
    };

    var aux = numbers.ViewAsNByM(2, 2).ToList();
    Assert.AreEqual(4, aux.Count);

    var a0 = new[,] {{1, 2}, {5, 6}};
    var a1 = new[,] {{3, 4}, {7, 8}};
    var a2 = new[,] { { 4, 3 }, { 8, 7 } };
    var a3 = new[,] { { 2, 1 }, { 6, 5 } };

    Assert.That(aux, Is.EquivalentTo(new[] {a0,a1,a2,a3}));
}

Any thoughts about the implementation?


texts: Database design for an online learning application

texts:
It is an online learning application with different types of learnable items, that different users learn.

The users learn by spaced repetition (once right, wait a couple days, ask again), success is mirrored in stages and mistakes made.

I intend to use this for scientific data collection in the near future, so there is one table especially, user_terms_answers where data amasses at a granularity not currently used by the application.

I especially had trouble with figuring out how to arrange my learnable types, and I'm not sure if I chose the optimal solution.

Since this is potentially not understood just from looking at the chart, the two basic types are:

known – unknown: What year did Thomas Edison die? – [1931] - one question & one answer
cloze tests or gap texts: Slow loris are of the genus [Nycticebus] and of the subfamily [Lorinae] - one question & many answers!

My schema

The part in gray ships with the TankAuth component of CodeIgniter and I'm hoping that this is properly done already.

Database schema

In response to a now-gone comment by l0bo, I visualized this in SchemaSpy as well.

Common queries

These the views that I have so far, they reflect quite well what the application will usually want.
They also reflect how I run into trouble with the way I chose to implement "languages".

CREATE VIEW `retrieve_user_term_or_gap` AS
SELECT
  u.id, u.learnable_id, u.user_id, u.stage, u.mistakes, u.time_due, u.added,
  terms.language, terms.field, terms.known, terms.unknown, terms.hint,
  gaps.cloze_id, gaps.gap,
  c.language AS cloze_language, c.field AS cloze_field, c.cloze,
  c.hint AS cloze_hint -- this is bad, not 3NF
FROM
  user_terms AS u
LEFT JOIN learnables AS l ON u.learnable_id = l.id
LEFT JOIN terms ON l.id = terms.learnable_id
LEFT JOIN gaps ON l.id =  gaps.learnable_id
LEFT JOIN clozetests AS c ON c.id = gaps.cloze_id

CREATE VIEW `how_many_due` AS
SELECT COUNT(id) FROM user_terms
WHERE stage < 5 AND DATE(time_due) <= CURDATE()

CREATE VIEW `due_terms` AS
SELECT
  u.id, u.learnable_id, u.user_id, u.stage, u.mistakes, u.time_due, u.added,
  terms.language, terms.field, terms.known, terms.unknown, terms.hint,
  gaps.cloze_id, gaps.gap,
  c.language AS cloze_language, c.field AS cloze_field, c.cloze,
  c.hint AS cloze_hint -- this is bad, not 3NF
FROM
  user_terms AS u
LEFT JOIN learnables AS l ON u.learnable_id = l.id
LEFT JOIN terms ON l.id = terms.learnable_id
LEFT JOIN gaps ON l.id =  gaps.learnable_id
LEFT JOIN clozetests AS c ON c.id = gaps.cloze_id
WHERE DATE(u.time_due) <= CURDATE() AND u.stage < 5
ORDER BY terms.language, terms.field, u.id


texts: Extract a range of rows from one file into another

texts:
Wondering if there is anything I can improve upon my code?

This method accepts a filename (usually will be the path to the file in txt format), the starting row count of that file and the total amount of rows of the file. The method is suppose to iterate through the starting row count passed in and then write into a new file with the remaining rows.

public void blah(String fileName, String startRowCount, String totalRowCount) {
        BufferedReader br = null;
        File newFile = null;
        BufferedWriter output = null;
        StringBuilder sb = null;
        int startRowCountInt = Integer.parseInt(startRowCount);
        int totalRowCountInt = Integer.parseInt(totalRowCount);

        try {
            br = new BufferedReader(new FileReader(fileName));
            sb = new StringBuilder();
            newFile = new File("name_Rerun.txt");
            output = new BufferedWriter(new FileWriter(newFile));
            String line = "";
            int counter = 0;

            while ((line = br.readLine()) != null) {
                if (startRowCountInt <= counter && counter <= totalRowCountInt) {
                    output.write(line);
                    output.newLine();
                }
                counter++;
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            LOGGER.info("File was not found.");
            e.printStackTrace();
        } finally {
            // Should update to Java 7 in order to use try with resources and then this whole finally block can be removed.
            try {
                if ( br != null ) {
                    br.close();
                }
                if ( output != null ) {
                    output.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                LOGGER.info("Couldn't close BufferReader.");
                e.printStackTrace();
            }
        }
    }


texts: Python implementation of Netcat, new design

texts:
I've made a simple netcat in Python and would appreciate any advice/opinions of how I've implemented it.

test.py:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys

import netcat

def main(*args):
    netcat.connect('localhost', 4444)
    netcat.listen('', 4444)

if __name__ == '__main__':
    sys.exit(main(*sys.argv))

netcat.py:

# -*- coding: utf-8 -*-

import sys
import select
import socket
from contextlib import closing

from servers import Server
from cat import cat_line

def netcat(sock, infile=sys.stdin, outfile=sys.stdout):
    with closing(sock) as s:
        sf = s.makefile()
        while True:
            r, w, e = select.select([s, infile], [], [])
            if s in r:
                if not cat_line(sf, outfile):
                    break
            if infile in r:
                if not cat_line(infile, sf):
                    break

def listen(lhost, lport, *args, **kwargs):
    with Server(lhost, lport) as server:
        client = server.get_client()
        netcat(client, *args, **kwargs)

def connect(rhost, rport, *args, **kwargs):
    server = socket.create_connection((rhost, rport))
    with closing(server) as s:
        netcat(s, *args, **kwargs)

servers.py:

# -*- coding: utf-8 -*-

import socket

class Server(object):

    def __init__(self, lhost, lport):
        self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self._sock.bind((lhost, lport))
        self._sock.listen(1)

    def __iter__(self):
        return self

    def next(self):
        return self.get_client()

    def __enter__(self):
        return self

    def __exit__(self, *exc):
        self.close()

    def get_client(self):
        return self._sock.accept()[0]

    def close(self):
        self._sock.close()

cat.py:

# -*- coding: utf-8 -*-

import sys

def cat_line(infile=sys.stdin, outfile=sys.stdout):
    line = infile.readline()
    if not line:
        return False
    outfile.write(line)
    outfile.flush()
    return True

def cat(infile=sys.stdin, outfile=sys.stdout):
    while True:
        if not cat_line(infile, outfile):
            break

Edit: Maybe I should take the responsibility of closing the socket from the netcat function...

def netcat(sock, infile=sys.stdin, outfile=sys.stdout):
    sf = sock.makefile()
    while True:
        r, w, e = select.select([sock, infile], [], [])
        if sock in r and not cat_line(sf, outfile):
                break
        if infile in r and not cat_line(infile, sf):
                break

and instead, put that functionality into the listen function?

def listen(lhost, lport, *args, **kwargs):
    with Server(lhost, lport) as server:
        client = server.get_client()
    with closing(client) as c:
        netcat(c, *args, **kwargs)

Also...

def cat(infile=sys.stdin, outfile=sys.stdout):
    while True:
        if not cat_line(infile, outfile):
            break

could be

def cat(infile=sys.stdin, outfile=sys.stdout):
    while cat_line(infile, outfile):
        pass

github


texts:
Initial stage of implementation of the polynomial class. Essentially I need to implement the basic mathematical operations. Right now I have implemented just addition. Was wondering if this is a good way to proceed. I also want to be sure if the move constructor would be called during the addition operation.

poly.h

/* Class for polynomials*/
/* Constant term is the first coefficient*/
/*To Do:
1. Establish invariants

*/
#ifndef POLY_H
#define POLY_H
#include <vector>
#include <iostream>
#include <cstdlib>
#include <stdexcept>
template< typename T>
class Poly
{
 public:
 Poly() = default; // default constructor
 Poly(size_t s):sz{s}, coeff{}{}; // constructor assumes positive size
 Poly(std::initializer_list<T> lst):sz{lst.size()}, coeff{lst}{}; // constructor with initializer list
 Poly(Poly && ) = default; // Move
 Poly &  operator = (Poly && ) = default;
 Poly (Poly const & ) = default; // Copy
 Poly &  operator = (Poly const & ) = default;

 T & operator[](int i) {
      if(i < 0 || i >= sz)
     throw std::out_of_range{"Poly::operator[]"};
   return coeff[i];
 }

 size_t getSize() const{return sz;};

 Poly &  operator += (const Poly &b){
   size_t bsz = b.getSize();
   if(sz > bsz){
     for(int i = 0; i < bsz; ++i)
       coeff[i] += b[i];
   }
   else{
     int i = 0;
     for(; i < sz; ++i)
       coeff[i] += b[i];
     sz = bsz;
     for(; i < bsz; ++i)
       coeff.push_back(b[i]);
   }
   return *this;
 }
 const T & operator[](int i) const{
      if(i < 0 || i >= sz)
     throw std::out_of_range{"Poly::operator[]"};
   return coeff[i];
 }

 T * begin(){return & coeff[0];}
  T * end(){return & coeff[0] + sz;}

 ~Poly() = default;

 private:
 std::size_t sz;
 std::vector  <T>  coeff; // coeff is a vector of type T. It could be the class Poly itself
 };
template <typename T>
inline Poly < T >operator + (const Poly < T > & a,  const Poly < T > & b){
  Poly < T > res{a};
  res += b;
  return res;
}

#endif /* POLY_H*/

main.cpp (for test runs)

#include <iostream>
#include <vector>
#include "poly.h"
int main(int argc,  char **argv)
{
  std::vector  < double > a;
  a =  {1, 2, 3};

  Poly < double > poly1{2, 3, 4, 5};
  Poly < double > poly2{2, 3, 4};
  poly1 += poly2;
  for(auto & x: poly1)
    std::cout << x;

  poly1 = poly2 + poly2;
  for(auto & x: poly1)
    std::cout << x;

  return 0;
}


texts:
I wrote a split by delimiter function in Haskell and wanted some feedback on this piece of code.
Since I come from an imperative programming background, I often write too complex functions in haskell.
split :: Char -> String -> [String]
split c str = fst $ splitInternal c ([], str)

splitInternal :: Char -> ([String], String) -> ([String], String)
splitInternal _ (result, "")  = (result, "")
splitInternal c (result, str) = splitInternal c (
    result ++ [takeWhile (/= c) str],
    case dropWhile (/= c) str of
        "" -> ""
        rest -> tail rest
    )

My questions are

Is it bad to have splitInternal function? I couldn't figure out a way without it.
Is there maybe a simpler way to write the function?
Any other feedback is welcome as well


texts: Translating words from one language to another

texts:
My program translates words from one language to another using a language Pivot and systran.io API.

I used promises, callbacks and external API for the first time but I'm not sure that's the best way to use them. The function Translate will translate word and send a response via a callback. Then in the POST request, I used promises to chain tasks.

var express = require('express');
var request = require('request');

var router = express.Router();

router.post("/", function(req, res) {
    console.log
    var resultat
    var promise = new Promise((resolve, reject) => {
        translate(req.query.source, "en", req.query.content, function(resa) {
            resolve(resa);

        })
    }).then(function(resolve) {
        console.log(resolve);
        translate("en", req.query.target, resolve, function(resa2) {
            console.log(resa2);

        })
    });
});

function translate(source, target, content, callback) {
    let result;
    result = request("https://api-platform.systran.net/translation/text/translate?input=" + content + "&source=" + source + "&target=" + target + "&key=xxxxxxxx-783f-4f90-aea4-7fb357016647", function(err, data, body) {
        body = JSON.parse(body);
        console.log(body);

        callback(body.outputs[0].output)
    })
}
module.exports = router;

Is there a better way to write my program, which is already working?


texts: Angular forms - reactive vs. [(ngModel)]

texts:
I am developing this angular app and it has big forms with 100 + fields. I was thinking about using [(ngModel)] without reactive forms, so that it's easier to do validations and I only have to provide the same JSON to the web service endpoint. Is this a right approach?

Reactive forms

export class ProfileEditorComponent {
  profileForm = new FormGroup({
    firstName: new FormControl(''),
    lastName: new FormControl(''),
  });
}

<input type="text" formControlName="firstName">

Alternative

    export class ProfileEditorComponent {
     profileForm = {
       firstName:""
     }
    }

<input type="text" [(ngModel)]="profileForm.firstName">

My idea was to handle all the validations and everything manually.


texts:
Is there any way to improve the performance of local report or even an alternative if not? I have been looking for a solution for quite some time but the general consensus seems to be that it's just slow.

public byte[] genReportBytes(int id, string fromm,string too,string filetype)
{
    reportDetails repD = new reportDetails();
    repD = getOneReport(id);

    LocalReport report = new LocalReport();

    if (fromm != null)
        repD.ParametersCommandLine = "@startdate=" + fromm;

    if (too != null)
        repD.ParametersCommandLine += " @enddate=" + too;

    string RDLCPath = ConfigurationManager.AppSettings["RDLCPath"];
    string ReportOutputPath = ConfigurationManager.AppSettings["ReportOutputPath"];

    string RDLCName = repD.RDLCName;
    RDLCPath += @"\" + RDLCName;
    report.ReportPath = RDLCPath;

    string sqlGet = repD.SQLOfReport;

    report.DataSources.Add(new ReportDataSource(repD.DatasetName, getReportData(sqlGet, repD.ParametersCommandLine)));

    // export to byte array

    Warning[] warnings;
    string[] streamids;
    string mimeType;
    string encoding;
    string filenameExtension;
    string deviceInf = "";
    byte[] bytes;
    string extension;

    if (filetype == "pdf")
    {
        deviceInf = "<DeviceInfo><PageHeight>8.5in</PageHeight><PageWidth>11in</PageWidth><MarginLeft>0in</MarginLeft><MarginRight>0in</MarginRight></DeviceInfo>";
        //fileName = ReportOutputPath + @"\" + repD.NameOfOutputPDF + ".PDF";
        bytes = report.Render("pdf", deviceInf, out mimeType, out encoding, out filenameExtension,
        out streamids, out warnings);
    }
    else
    {
        //fileName = ReportOutputPath + @"\" + repD.NameOfOutputPDF + ".XLS";
        bytes = report.Render(
              "Excel", null, out mimeType, out encoding,
               out extension,
              out streamids, out warnings);
    }

    return bytes;
}


texts:
This is a follow up question to: Login system, PDO and me

Is this considered secure for a login script?

if (filter_input(INPUT_POST, "login", FILTER_UNSAFE_RAW)) {
    $usercookie = 'Admin-'.uniqid(mt_rand(), true);

    $lastlogin = date('d / m / y - H:ia');
    $session = uniqid(mt_rand(), true);
    $active = 1;

    $username = filter_input(INPUT_POST, "username", FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
    $password = filter_input(INPUT_POST, "password", FILTER_UNSAFE_RAW);

    $query = 'SELECT password FROM wcx_admin WHERE username = :username';

    $stmt = $backend->queryIt($query);
    $stmt = $backend->bind(':username', $username);
    $stmt = $backend->execute();
    $dbpass = $backend->getColumn();

    if(password_verify($password, $dbpass)) {
        $query = 'UPDATE wcx_admin SET active = :active, lastlogin = :lastlogin, session = :session WHERE username = :username';
        $stmt = $backend->queryIt($query);
        $stmt = $backend->bind(':active', $active);
        $stmt = $backend->bind(':lastlogin', $lastlogin);
        $stmt = $backend->bind(':session', $session);
        $stmt = $backend->bind(':username', $username);
        $login = $backend->execute();
    }

    if($login) {
        $_SESSION['loggedin'] = $session;
        $_SESSION['auth'] = $session;
        setcookie( 'wcxadmin', $usercookie, time()+3600);
        header('Location: index.php');
    }
    else {
        $_SESSION['errors'] = 'Incorrect Username or Password';
        header('Location: index.php');
    }
}

The bind function:

public function bind($param, $value, $type = null){
if (is_null($type)) {
    switch (true) {
        case is_int($value):
            $type = PDO::PARAM_INT;
            break;
        case is_bool($value):
            $type = PDO::PARAM_BOOL;
            break;
        case is_null($value):
            $type = PDO::PARAM_NULL;
            break;
        default:
            $type = PDO::PARAM_STR;
    }
}
$this->stmt->bindValue($param, $value, $type);
}

Error output:

if(isset($_SESSION['errors'])) {
    echo '
'.$_SESSION['errors'].'
';
    $_SESSION['errors'] = '';
}


texts:
I'm just starting out in Rust and I find the concept of ownership confusing so I wrote an implementation of the echo command. I would like to know if I could have set the initial value on the echo variable any better or just any general improvements.

use std::env;

fn main() {
    let args: Vec<String> = env::args().collect();

    let mut echo: String;
    if let Some(string) = args.get(1) {
        echo = string.to_string();
    } else {
        return;
    }

    for arg in &args[2..] {
        echo.push(' ');
        echo.push_str(arg.as_str());
    }
    echo.push('\n');

    println!("{}", echo);
}


texts:
Do you see any inefficient parts with the following code? On internet I see 30 ms for 100.000 integers but I can sort 100.000 integers in 300ms. The data is random. I am using late 2013 macbook pro so I don't expect a 10x slowdown from CPU, but who knows.

void mergesort2(int* list, int begin, int end,int *tmplist=0){
    bool allocated = false;
    if (end-begin < 1) {
        return;
    }
    if (tmplist == 0) {
        allocated = true;
        tmplist = new int[end-begin+1];
    }

    int middle = (begin+end)/2;

    mergesort2(list, begin, middle, tmplist);
    mergesort2(list, middle+1, end, tmplist);

    for (int first=begin, second=middle+1, tmp=0; tmp<end-begin+1; tmp++) {
        if (first > middle) {

            memcpy(tmplist+tmp, list+second, sizeof(int)*(end-begin-tmp+1));
        }
        else if (second > end) {
            memcpy(tmplist+tmp, list+first, sizeof(int)*(end-begin-tmp+1));

        }
        else if (list[first] <= list[second]) {
            tmplist[tmp] = list[first++];
        }else{
            tmplist[tmp] = list[second++];
        }
    }

    memcpy(list+begin, tmplist, (end-begin+1)*sizeof(int));

    if (allocated) {
        delete tmplist;
    }
}


texts: Is this a good structure for SQLAlchemy code?

texts:
Right now i'm making a Discord Bot written in python, i'm using SQLAlchemy to deal with the database.
My structure is:

One database.py containing a "DatabaseConnection" class initializing the SQLAlchemy engine, and making a new session with the DB every time i use it
Many .py file(each file for different purposes) containing a class inheriting "DatabaseConnection"

Example:
database.py:
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, Session

class DatabaseConnection:
    def __init__(self):
        self.engine = create_engine(DB_URI, echo=False)
        self.session = None

    def __enter__(self) -> Session:
        self.session = sessionmaker(bind=self.engine)()
        return self.session

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.session.close()

example.py:
from database import DatabaseConnection

class Foo(DatabaseConnection):
    def get_bar(self):
        with self as session:
            #do thing

My question is, is this a right way to use inheritance? Or it is just better calling directly to DatabaseConnection? It can be cause problems? There are better/cleaner/more pythonic ways to do it?


texts: Algorithm that generate all possible strings from N Tuples. Found Brute Force version, Recursive Version uses a Tree?

texts:
I am trying to figure out a solution for a problem. Consider the following tuples (it could be any number of tuples, I am using four in this example):

{A, B, C, D}
{E, F, G, H}
{I, J, K, L}
{M, N, O, P}

Out of this tuples I have to construct a four-character string, but I can only choose one element from each tuple. Note that if I had \$N\$ tuples, it would be an \$N\$ character string.

The strings "AEIM", "BGLP", "DEIO" are valid examples. The string "EAIM" is not, because the A and E are in the wrong position.

I am able to brute force and get the solution, but there has to be a recursive way to do this... Because brute force does not solve for \$N\$ tuples

String[][] arr = { {"A", "B", "C", "D"}, {"E", "F", "G", "H"}, {"I", "J", "K", "L"}, {"M", "N", "O", "P"} };

String temp;
for(int i = 0; i < 4; i++){

    for (int j = 0; j < 4; j++){

        for (int k = 0; k < 4; k++){

            for (int l = 0; l < 4; l++){

                temp = arr[0][i] + arr[1][j] + arr[2][k] + arr[3][l];
                System.out.println(temp);

            }
        }
    }
}

I am aware that I could use a Tree to recursively solve this, however I do not know how to proceed... Any help is deeply appreciated!


texts:
I have started learning HTML. Here is one of the very basic HTML pages I have written. I would appreciate advice about how to write code especially regarding indentation.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title> Checking Different Headings | Isnt it fun?</title>
</head>

<body>
<h1>  This is big</h1>
<h2>  This is also good </h2>
<h3>  This is also good </h3>
<h4>  This is also good  </h4>
<h5>  This is also good </h5>
<h6>  This is small </h6>
</body>
</html>


texts: Splitting and printing comma-separated values

texts:
I stumbled upon a question on SO asking how to split a comma-separated string into individual values.

Since it's been a while since I've had any good reason to write C I'd like to ask for some feedback.

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

int main (int argc, const char * argv[]) {
    const char str[] ="coma separated,input,,,some fields,,empty";
    const char tok[] = ",";
    char * tmp = (char *)str;
    size_t count;
    for (count=0; tmp[count]; tmp[count] == tok[0] ? count++ : * tmp++) {
        //Empty loop body.
    }
    tmp = (char *)str;
    for (size_t i = 0, l = 0; i < count; i++) {
        l = strcspn (tmp, tok);
        if (l == 0) {
            printf("\"\"\n");
        } else {
            printf("\"%.*s\"\n", l, tmp);
        }
        tmp += sizeof(char) * (l + 1);
    }
    printf("\"%s\"\n", tmp);
    return 0;
}

Output as expected:

"coma separated"
"input"
""
""
"some fields"
""
"empty"


texts: How to optimize this majority vote method

texts:
I have the following code to do a majority vote for data in a dataframe:
def vote(df, systems):
    test = df.drop_duplicates(subset=['begin', 'end', 'case', 'system'])
    n = int(len(systems)/2)
    data = []

    for row in test.itertuples():
        # get all matches
        fx = test.loc[(test.begin == row.begin) & (test.end == row.end) & (test.case == row.case)]
        fx = fx.loc[fx.system.isin(systems)]

        # keep if in a majority of systems
        if len(set(fx.system.tolist())) > n:
            data.append(fx)

    out = pd.concat(data, axis=0, ignore_index=True)
    out = out.drop_duplicates(subset=['begin', 'end', 'case'])

    return out[['begin', 'end', 'case']]

The data look like:
systems = ['A', 'B', 'C', 'D', 'E']

df = begin,end,system,case
0,9,A,0365
10,14,A,0365
10,14,B,0365
10,14,C,0365
28,37,A,0366
38,42,A,0366
38,42,B,0366
53,69,C,0366
56,60,B,0366
56,60,C,0366
56,69,D,0366
64,69,E,0366
83,86,B,0367

The expected output should be:
out = begin,end,case
    10,14,0365
    56,69,0366

IOW, if desired elements begin, end, case appear in a majority of systems, we accumulate them and return them as a dataframe.
The algorithm works perfectly fine, but since there are hundreds of thousands of rows in it, this is taking quite a while to process.
One optimization I can think of, but am unsure of how to implement is in the itertuples iteration: If, for the first instance of a filter set begin, end, case there are matches in
fx = test.loc[(test.begin == row.begin) & (test.end == row.end) & (test.case == df.case) & (fx.system.isin(systems))]

then, it would be beneficial to not iterate over the other rows in the itertuples iterable that match on this filter. For example, for the first instance of 10,14,A,0365 there is no need to check the next two rows, since they've already been evaluated. However, since the iterable is already fixed, there is no way to skip these of which I can think.


texts: Catching multiple types of exceptions when writing JSON

texts:
I have a class which throws a lot of exceptions:

    try {
        mapper.writeValue(outStream, myVal);
    } catch (JsonGenerationException e) {
        e.printStackTrace();
    } catch (JsonMappingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

I think this looks messy. Is it ok to just catch a generic Exception and not catch each individual exception if within the catch clause of each exception I'm just printing the stack trace?


texts:
I am trying to improve my code to find the tennis court line intercepts so that I can find the boundaries of the different quadrants of the court.

This is the tennis court image I am trying to analyze

This is the final result

I achieved this by first finding the white pixels in the image, then applying canny edge detection with some preprocessing such as Gaussian blur. Then the canny edge output is dilated to help prepare it for hough lines detection.

Then taking the hough lines output I used the python implementation of the  Bentley–Ottmann algorithm by github user ideasman42 to find the hough line intercepts.

This seems to work pretty well, but I'm struggling to tune my system to find the last 4 intercept points. If anyone could give me advice to improve or tune this implementation or even offer up some ideas for a better way to solve the problem of finding the court boundaries I would appreciate it.

# import the necessary packages
import numpy as np
import argparse
import cv2
import scipy.ndimage as ndi
import  poly_point_isect as bot

# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", help = "path to the image")
args = vars(ap.parse_args())

# load the image
image = cv2.imread(args["image"])

# define the list of boundaries
boundaries = [
    ([180, 180, 100], [255, 255, 255])
]

# loop over the boundaries
for (lower, upper) in boundaries:
    # create NumPy arrays from the boundaries
    lower = np.array(lower, dtype = "uint8")
    upper = np.array(upper, dtype = "uint8")

    # find the colors within the specified boundaries and apply
    # the mask
    mask = cv2.inRange(image, lower, upper)
    output = cv2.bitwise_and(image, image, mask = mask)

    # show the images
    cv2.imshow("images", np.hstack([image, output]))
    cv2.waitKey(0)

gray = cv2.cvtColor(output,cv2.COLOR_BGR2GRAY)

kernel_size = 5
blur_gray = cv2.GaussianBlur(gray,(kernel_size, kernel_size),0)

low_threshold = 10
high_threshold = 200
edges = cv2.Canny(gray, low_threshold, high_threshold)
dilated = cv2.dilate(edges, np.ones((2,2), dtype=np.uint8))

cv2.imshow('dilated.png', dilated)
cv2.waitKey(0)

rho = 1  # distance resolution in pixels of the Hough grid
theta = np.pi / 180  # angular resolution in radians of the Hough grid
threshold = 10 # minimum number of votes (intersections in Hough grid cell)
min_line_length = 40  # minimum number of pixels making up a line
max_line_gap = 5  # maximum gap in pixels between connectable line segments
line_image = np.copy(output) * 0  # creating a blank to draw lines on

# Run Hough on edge detected image
# Output "lines" is an array containing endpoints of detected line segments

lines = cv2.HoughLinesP(dilated, rho, theta, threshold, np.array([]), min_line_length, max_line_gap)

points = []
for line in lines:
    for x1, y1, x2, y2 in line:
        points.append(((x1 + 0.0, y1 + 0.0), (x2 + 0.0, y2 + 0.0)))
        cv2.line(line_image, (x1, y1), (x2, y2), (255, 0, 0), 5)

cv2.imshow('houghlines.png', line_image)
cv2.waitKey(0)

lines_edges = cv2.addWeighted(output, 0.8, line_image, 1, 0)
print(lines_edges.shape)

intersections = bot.isect_segments(points)
print(intersections)

for idx, inter in enumerate(intersections):
    a, b = inter
    match = 0
    for other_inter in intersections[idx:]:
        c, d = other_inter
        if abs(c-a) < 8 and abs(d-b) < 8:
            match = 1
            if other_inter in intersections:
                intersections.remove(other_inter)
                intersections[idx] = ((c+a)/2, (d+b)/2)

    if match == 0:
        intersections.remove(inter)

for inter in intersections:
    a, b = inter
    for i in range(6):
        for j in range(6):
            lines_edges[int(b) + i, int(a) + j] = [0, 0, 255]

# Show the result
cv2.imshow('line_intersections.png', lines_edges)
cv2.imwrite('line_intersections.png', lines_edges)
cv2.waitKey(0)


texts: Taking YouTube links out of a list of GitHub repo READMEs

texts:
I have a .csv file that contains student GitHub repository assignment submissions. I made a script to go to each repository and extract the YouTube video that they must have provided in their README file.

The structure of the CSV file is as follows:

Timestamp,Name,Student Number,Git Repo link

#!/usr/bin/python3

import csv
import github3
import time
import re
import argparse
from secrets import username, password

# API rate limit for authenticated requests is way higher than anonymous, so login.
gh = github3.login(username, password=password)
# gh = github3.GitHub() # Anonymous

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("filepath", type=str, metavar="filepath", help="Filepath to the input csv file.")

    args = parser.parse_args()
    args = vars(args)  # Turn into dict-like view.

    return args

def get_row_count(filename):
    with open(filename, 'r') as file:
        return sum(1 for row in csv.reader(file))

def get_repositories(link):
    if gh.rate_limit()['resources']['search']['remaining'] == 0:
        print("API rate exceeded, sleeping for {0} seconds.".format(gh.rate_limit()['resources']['search']['reset'] - int(time.time()+1)))
        time.sleep(gh.rate_limit()['resources']['search']['reset'] - int(time.time()+1))

    return gh.search_repositories(link.replace("https://github.com/", "", 1), "", 1)

def main():
    filepath = parse_args()['filepath']
    if not filepath.endswith('.csv'):
        print("Input file must be a .csv file.")
        exit()

    p = re.compile(r"http(?:s?):\/\/(?:www\.)?youtu(?:be\.com\/watch\?v=|\.be\/)([\w\-\_]*)(&(amp;)?[\w\?=]*)?") # From http://stackoverflow.com/a/3726073/6549676
    row_counter = 0
    row_count = get_row_count(filepath)

    with open(filepath, 'r') as infile, open(filepath[:3] + "_ytlinks.csv", "w") as outfile:
        reader = csv.reader(infile)
        next(reader, None)  # Skip header

        writer = csv.writer(outfile)
        writer.writerow(["Youtube Link", "Name", "GitHub Link"])  # Write header

        for row in reader:
            for repo in get_repositories(row[3]):
                readme = repo.repository.readme().decoded
                if not readme:
                    readme = "No Youtube link found."

                if type(readme) is bytes:
                    readme = readme.decode('utf-8')

                ids = p.findall(readme)
                if len(ids) != 0:
                    ids = ids[0]

                ids = [x for x in ids if x]

                for _id in ids:
                    writer.writerow(['https://www.youtube.com/watch?v={0}'.format(_id), row[1], row[3]])

                if len(ids) == 0:
                    writer.writerow(['No Youtube Link Found', row[1], row[3]])

            print('Processed row {0} out of {1}'.format(row_counter, row_count))
            row_counter += 1

    print("Finished.")

if __name__ == "__main__":
    main()


texts: Inheriting needed when only difference is performed in the constructor?

texts:
I have a class that produces a key based on the two objects passed. The key for the items passed is simply the string of the ID (a GUID) for each object. There is also a subclass that makes sure any to items are only represented once (sets).

The classes looked like the first code block below. But then I ran into a performance problem where creating the key every time was accessed was just to slow. So I changed it such that I create the key in the constructor and store it in a member variable. But now it seems that the inheritance is overkill.

Maybe the inheritance was always overkill but I didn't see it because I overrode an actual behavior so it seemed more OOPy? Or did it become inheritance abuse after the re-factoring? Or is it still fine but I am seeing it wrong?

Note that the ID must be unique and is often, but not always, a GUID.

Public Interface IIdentifiable
    ReadOnly Property ID() As String
End Interface

Public Class Keyed
    Public Sub New(item1 As IIdentifiable, item2 As IIdentifiable)
        PrimaryItem = item1
        SecondaryItem = item2
    End Sub

    Public Property PrimaryItem As IIdentifiable

    Public Property SecondaryItem As IIdentifiable

    Public Overridable Function Key() As String
        Return PrimaryItem.ID & SecondaryItem.ID
    End Function

End Class

Public Class KeyedForSet
    Inherits Keyed

    Public Sub New(item1 As IIdentifiable, item2 As IIdentifiable)
        MyBase.New(item1, item2)
    End Sub

    Public Overrides Function Key() As String
        If PrimaryItem.ID.CompareTo(SecondaryItem.ID) > 0 Then
            Return PrimaryItem.ID & SecondaryItem.ID
        Else
            Return SecondaryItem.ID & PrimaryItem.ID
        End If
    End Function

End Class

Second implementation for performance reason.

Public Class Keyed
    Public Sub New(item1 As IIdentifiable, item2 As IIdentifiable)
        mKey = item1.ID & item2.ID
        PrimaryItem = item1
        SecondaryItem = item2
    End Sub

    Public Property PrimaryItem As IIdentifiable
    Public Property SecondaryItem As IIdentifiable

    Protected mKey as string
    Public Overridable Function Key() As String
        Return mKey
    End Function
End Class

Public Class KeyedForSet
    Inherits Keyed

    Public Sub New(item1 As IIdentifiable, item2 As IIdentifiable)
        MyBase.New(item1, item2)
        If PrimaryItem.ID.CompareTo(SecondaryItem.ID) > 0 Then
            mKey = PrimaryItem.ID & SecondaryItem.ID
        Else
            mKey = SecondaryItem.ID & PrimaryItem.ID
        End If
    End Sub

End Class


texts: Best pattern for catching errors in javascript loop

texts:
This loop executes a function this.DoSomething based on multiple conditions:
for (let i=0; i<this.noProfiles; i++) {
    // Check for error in function below
    try {
        var page = await this.Function(url)
    } catch (err) {
        // new iteration in case of error
        // do not execute code below
    }
    // Execute code based on bool function
    if (!(await this.BoolFunction1(page))) {
        var imgArray = await this.LoadImages(page)
        // Execute code based on bool function
        if (await BoolFunction2(page,imgArray)) {
            // do something
            await this.DoSomething(page,imgArray)
        } else {
            // new iteration
            i = i-1
        }
    } else {
        // new iteration
        i = i-1
    }
    // do something in case of new iteration
    await page.close()
}

If given conditions are not true, new iteration takes place.
I need to program new iteration also in case there is an error in this.Function() + following actions are skipped in such case.
What is an optimal pattern to do this in Javascript? Maybe multiple generators one after another?


texts: Rewritten implementation of quadratic equation formula

texts:
I just started learning the C programming language at the university, and today we got a new assignment there is about Refinement of a C software there is designed to find the roots of the general quadratic equation. We got an old C software that we have to rewrite with functions instead of using the Whole code inside main. We have to split the functions into 3 where is about

Calculation of the discriminant.
Calculation of the first root.
Calculation of other root.

The old code:

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

/* Prints roots of the quadratic equation a * x*x + b * x + c = 0 */
void solveQuadraticEquation(double a, double b, double c){
  double discriminant, root1, root2;

  discriminant = b * b - 4 * a * c;

  if (discriminant < 0)
    printf("No roots\n");
  else if (discriminant == 0){
    root1 = -b/(2*a);
    printf("One root: %f\n", root1);
  }
  else {
    root1 = (-b + sqrt(discriminant))/(2*a);
    root2 = (-b - sqrt(discriminant))/(2*a);
    printf("Two roots: %f and %f\n", root1, root2);
  }

}

int main(void) {
  double a = 1.0, b = -8.0, c = 15.0,
         d = 2.0, e =  8.0, f =  2.0,
         g, h, i;

  /* First call - coefficents are values of variables */
  solveQuadraticEquation(a, b, c);

  /* Second call - coefficents are values of expressions */
  solveQuadraticEquation(d - 1, -e, 7 * f + 1);

  /* Third call - coefficents are entered by user outside
solveQuadraticEquation */
  printf("Enter coeficients a, b, and c: ");
  scanf("%lf %lf %lf", &g, &h, &i);
  solveQuadraticEquation(g, h, i);

  return 0;
}

My Solution:

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

double discriminant(double a, double b, double c);
double root1(double a, double b, double c);
double root2(double a, double b, double c);

/* Prints roots of the quadratic equation a * x*x + b * x + c = 0 */
void solveQuadraticEquation(double a, double b, double c){

  if (discriminant(a, b, c) < 0)
    printf("No roots\n");
  else if (discriminant(a, b, c) == 0){
    printf("One root: %f\n", root1(a, b, c));
  }
  else {
    printf("Two roots: %f and %f\n", root1(a, b, c), root2(a, b, c));
  }

}

int main(void) {
  double a = 1.0, b = -8.0, c = 15.0,
         d = 2.0, e =  8.0, f =  2.0,
         g, h, i;

  /* First call - coefficents are values of variables */
  solveQuadraticEquation(a, b, c);

  /* Second call - coefficents are values of expressions */
  solveQuadraticEquation(d - 1, -e, 7 * f + 1);

  /* Third call - coefficents are entered by user outside
solveQuadraticEquation */
  printf("Enter coeficients a, b, and c: ");
  scanf("%lf %lf %lf", &g, &h, &i);
  solveQuadraticEquation(g, h, i);

  return 0;
}

double discriminant(double a, double b, double c){
    return b * b - 4 * a * c;
}

double root1(double a, double b, double c){
  return (-b + sqrt(discriminant(a, b, c)))/(2*a);
}

double root2(double a, double b, double c){
  return (-b - sqrt(discriminant(a, b, c)))/(2*a);
}

I have already made a well-working solution, but I was wondering if I could make it even better, so if I have done something wrong or weird, please let me know.


texts: Checking password strength while honoring functional requirements

texts:
A program needs a password strength estimator but has several implementation restrictions:

Nothing outside of Python's standard library may be used.
A database of common passwords may not be consulted.
The code must be simple, self-contained, and easy to verify.

As for the interface of the password strength estimator, several requirements are provided:

Empty passwords must have a strength of zero.
Passwords may only use ASCII whitespace, alphanumeric, and punctuation characters.
Passwords with other characters must have a strength less than zero.
Otherwise, strength must be estimated as the bit-space needed to store the password.

In keeping with the caveats listed above, the following function appears to do as required:

import math
import string

def estimate_quality(password):
    if not password:
        return 0
    types = ([False, frozenset(string.whitespace)],
             [False, frozenset(string.ascii_lowercase)],
             [False, frozenset(string.ascii_uppercase)],
             [False, frozenset(string.digits)],
             [False, frozenset(string.punctuation)])
    for character in password:
        for index, (flag, group) in enumerate(types):
            if character in group:
                types[index][0] = True
                break
        else:
            return -1
    space = sum(len(group) for flag, group in types if flag)
    return math.ceil(math.log2(space) * len(password))

Is it possible to refactor the code to improve upon the third implementation restriction?


texts: Project Euler #49: Find 12-digit number concatenating a three terms sequence

texts:
First of all, project Euler has been a great help for me to learn Clojure. I tried for months trying to get web projects going but ended up frustrated with and struggling with tooling and libraries more than anything else. The code below gives the solution to Problem 49 in Project Euler:

  The arithmetic sequence, 1487, 4817, 8147, in which each of the terms
  increases by 3330, is unusual in two ways: (i) each of the three terms
  are prime, and, (ii) each of the 4-digit numbers are permutations of
  one another.

  There are no arithmetic sequences made up of three 1-, 2-, or 3-digit
  primes, exhibiting this property, but there is one other 4-digit
  increasing sequence.

  What 12-digit number do you form by concatenating the three terms in
  this sequence?

;; gen-primes Taken from https://stackoverflow.com/a/7625207/466694
(defn gen-primes "Generates an infinite, lazy sequence of prime numbers"
  []
  (let [reinsert (fn [table x prime]
                   (update-in table [(+ prime x)] conj prime))]
    (defn primes-step [table d]
      (if-let [factors (get table d)]
        (recur (reduce #(reinsert %1 d %2) (dissoc table d) factors)
               (inc d))
        (lazy-seq (cons d (primes-step (assoc table (* d d) (list d))
                                       (inc d))))))
    (primes-step {} 2)))

(defn get-digits [num]
  (->> [num []]
     (iterate (fn [[num digits]]
                (when (> num 0)
                  [(quot num 10) (conj digits (rem num 10))])))
     (take-while some?)
     (last)
     (second)))

(defn are-permutations-of-each-other? [num1 num2]
  (= (sort (get-digits num1)) (sort (get-digits num2))))

(let [four-digit-primes (->> (gen-primes)
                             (drop-while #(< % 1000))
                             (take-while #(< % 10000))
                             (apply sorted-set))]
  (->> (for [i four-digit-primes
             j four-digit-primes]
         [i j])
       (remove #(apply = %))
       (filter #(apply are-permutations-of-each-other? %))
       (filter (fn [[n1 n2]]
                 (let [mx (max n1 n2)
                       mn (min n1 n2)
                       diff (- mx mn)
                       next (+ mx diff)]
                   (and (< next 10000)
                        (four-digit-primes next)
                        (are-permutations-of-each-other? n1 next)))))
       (map sort)
       (distinct)
       (map #(cons (+ (second %) (- (second %) (first %))) %))
       (map sort)
       (map #(map str %))
       (map (partial apply str))
       (second)))

For example, the last let expression is the result of tinkering for half an hour or so until I get the information I want out of it. Two questions:

I've found threading macros (especially ->>) a pure joy to work with. But, is there such a thing as a threading expression that is too long?
I know that this is throw-away coding, but what things can I do to improve this code to fit best practices? Are there things I'm doing wrong?


texts: Todo-list practice code accepts title and list

texts:
I am new to OOP principles and best practices. People often say I write "unpythonic code," so give me your perspective on how to do things better.

class TodoList(object):

    def __init__(self, title=None):
        self.title = title
        self.items = list()

    # depend on _list, accepts _list index numbers
    def __str__(self, tdl=None):

        if tdl is None:
            tdl=range(len(self.items))

        for i in tdl:
            item = "{0}. {1}".format(i, self.items[i])
            print(item)
        return str()

    def __len__(self):
        return len(self.items)

    # list bindings
    def add(self, item):
        self.items.append(item)

    def update(self, key, update):
        self.items[key] = update

    def remove(self, key):
        del self.items[key]

    # search through i, find query, append key
    def search(self, query):
        result = []
        for k, i in enumerate(self.items):
            if query in i:
                result.append(k)
        return self.__str__(result)


texts:
Find junk values in all tables and columns:

Loop through all tables in a schema (Oracle 18c)
Loop through each number and text column
If columns have values that are junk, then add a statistic/record to a log table:

0 (number)
  (text; single space)
   (text; double space)
0 (text)
- (text)
NULL (text; not a true null)
<NULL> (text; not a true null)

Get the data custodian to review the issue and correct it if applicable.

--TRUNCATE TABLE incorrect_value_results;
--CREATE TABLE incorrect_value_results (id NUMBER, table_name VARCHAR2(30), column_name VARCHAR2(30), val_count NUMBER);

DECLARE
   l_count NUMBER;
   l_index NUMBER;
BEGIN
   l_index := 0;
   -- Loop through each table in the schema
   FOR i IN (SELECT table_name
               FROM user_tables) LOOP
      -- Loop through each relevant column for this table
      FOR j IN (SELECT column_name, data_type
                  FROM user_tab_cols
                 WHERE table_name = i.table_name
                   AND data_type IN ('VARCHAR2', 'CHAR', 'NCHAR', 'NVARCHAR2', 'NUMBER')) LOOP
         IF j.data_type IN ('VARCHAR2', 'CHAR', 'NCHAR', 'NVARCHAR2') THEN
            EXECUTE IMMEDIATE 'SELECT COUNT(1) FROM '||i.table_name||' WHERE UPPER('||j.column_name||') IN('' '', ''  '', ''0'', ''-'', ''NULL'', ''<NULL>'' )' INTO l_count;
         ELSIF j.data_type = 'NUMBER' THEN
            EXECUTE IMMEDIATE 'SELECT COUNT(1) FROM '||i.table_name||' WHERE '||j.column_name||' <= 0' INTO l_count ;
         END IF;

         -- If there are results then log them
         IF l_count > 0 THEN
            l_index := l_index + 1;
            INSERT INTO incorrect_value_results (id, table_name, column_name, val_count)
            VALUES (l_index,
                    i.table_name,
                    j.column_name,
                    l_count);
         END IF;
      END LOOP;
   END LOOP;
END;

COMMIT;

I'm relatively new to PL/SQL. How can the script be improved?


texts:
I have a problem where I need to sort an extremely large number of numbers but the numbers are in a narrow range (0..r-1) where r is typically around 10, and after googling around a bit it seemed like a good time to use radix sort. I have the following implementation below (I had to extract it out of a much larger program and simplify for illustration). It seems reasonably fast, but is there any other trick I can use to further speed it?

public static void sort(int[] data, int radix) {
    int aux[] = new int[data.length];
    int count[] = new int[radix];
    for (int i = 0; i < data.length; i++) {
        count[data[i]]++;
    }
    int cumulate = 0;
    for (int i = 0; i < radix; i++) {
        for (int j = 0; j < count[i]; j++)
            aux[cumulate + j] = i;
        cumulate = cumulate + count[i];
    }
    for (int i = 0; i < aux.length; i++) {
        data[i] = aux[i];
    }
}


texts: Generating and using a list of prime numbers

texts:
Here is some code I've created to generate and use a list of prime numbers.  This is some of the first Common Lisp code I've written, and I'd be grateful for any comments regarding style and its use or misuse of common idioms.  I'm not really interested in improving the algorithm, but in making my implementation readable and efficient.

    ;;; Estimate the number of primes below a number n
(defun primes-pi (n)
  (ceiling (/ n (- (log n) 1))))

;;; (A high) estimate of the number below which there are n primes, this is the
;;; reverse of primes-pi
(defun primes-n (n)
  (* n (ceiling (+ (log n) 1))))

;;; Code to generate prime numbers
(defun plist (n)
  (let (;; An array of booleams flags for the sieve
        (arr (make-array (+ n 1) :element-type 'boolean :initial-element t))
        ;; The first prime the loop below will handle
        (p 3)
        ;; results is used to build the list of primes
        (result nil))
    ;; 0 isn't prime
    (setf (aref arr 0) nil)
    ;; 1 isn't prime
    (setf (aref arr 1) nil)
    ;; 2 is primes
    (push 2 result)

    ;; Now the special cases are out of the way start sieving for new primes
    ;; when p is nil the loop has reached the end of the arr array
    (do () ((eq nil p))
      ;; add p to the list of primes
      (push p result)
      ;; Remove all multiples of p from the array
      (loop for i from (+ p p) to n by p
         do (setf (aref arr i) nil))
      ;; search forward in the array to the next non nil entry, this will be
      ;; the next prime.
      (setf p (loop for i from (+ 2 p) to n by 2
                 when (eq t (svref arr i))
                 return i)))
    ;; reverse the list to get the primes in ascending order
    ;; not really needed if only using the list in build-is-prime?
    (nreverse result)))

;;; This function creates and returns a closure that allows testing
;;; for primeality of at least the first n prime number
(defun build-is-prime (n)
  (let ((prime-table (make-hash-table :size n)))
    ;; Populate the hash table
    (loop for i in (plist (primes-n n)) do
         (setf (gethash i prime-table) t))
    ;; Lambda to test for presence of p in the hash table
    (lambda (p)
      (gethash p prime-table)
      )))


texts:
I need to use some flags in my code. To make it a bit clearer, I am looking to set the flags in some structure, and I need to match the following needs:

The flag representation in the structureis hidden.
The following methods are provided (or the same idea at least): setFlag(structWithFlags *, ACTION_FLAGS ),
isFlagSet(structWithFlags *, ACTION_FLAGS) and removeFlag(structWithFlags *, ACTION_FLAGS)
The structure should not contain a "magic number" that defines the size of the flag bytes, since the number of flags may vary, when compiling for different projects.

In general, this is serving as part of a general module, used by many different modules, in many different combinations.

Currently, my method to achieve that is as follows:

projectSpecificNeeds.h:

typedef enum ACTION_FLAGS {
    ACTION_FLAG_NO_1,
    ACTION_FLAG_NO_2,
    //.. etc.
    FLAG_LAST
}ACTION_FLAGS ;

genericModuleThatServesEveryBody.c:

#include <limits.h>
#include "projectSpecificNeeds.h"
typedef struct structWithFlags {
    // Some irrelevant fields
    // each flag is represented by one bit in the flagByte array
    char flagBytes[FLAG_LAST / CHAR_BIT + 1];
}structWithFlags ;

structWithFlags * getStructWithFlags() {
    return calloc(sizeof(structWithFlags));
}

// Bitwise OR between the relevant flag byte and the flag
void setFlag(structWithFlags * st, ACTION_FLAGS flag) {
    st->flagBytes[flag / CHAR_BIT] |= 1 << (flag % CHAR_BIT);
}

// return the AND between the relevant flag byte and the flag
char isFlagSet(structWithFlags * st, ACTION_FLAGS flag) {
    return st->flagBytes[flag / CHAR_BIT] & ( 1 << (flag % CHAR_BIT));
}

// Bitwise AND between the relevant flag byte all bits except of the flag
void removeFlag(structWithFlags * st, ACTION_FLAGS flag) {
    st->flagBytes[flag / CHAR_BIT] &= ~(1 << (flag % CHAR_BIT));
}

It works well, and I met no problem with it until now. But I wonder whether there's some more elegant / readable yet memory saving method to implement this functionality.


texts:
I want to rewrite blockchain source code from Golang to C++11. Please, review my code and help me to improve it.

Source in Golang:

package main

import "time"

type Block struct {
  Timestamp     int64
  Data          []byte
  PrevBlockHash []byte
  Hash          []byte
  Nonce         int
}

func NewBlock(data string, prevBlockHash []byte) *Block {
  block := &Block{ time.Now().Unix(), []byte(data), prevBlockHash, []byte{}, 0}

  proof := NewProofOfWork(block)
  nonce, hash := proof.Run()

  block.Hash = hash[:]
  block.Nonce = nonce

  return block
}

func NewGenesisBlock() *Block {
  return NewBlock("Genesis Block", []byte{})
}

My source in C++:

blockchain.h:

#ifndef BLOCKCHAIN_H
#define BLOCKCHAIN_H

#ifdef USE_BLOCK

#include <cstdint>
#include <vector>
#include <array>
#include <string>

using sha_t  = std::array<unsigned char, 32>;
using data_t = std::vector<unsigned char>;

struct Block
{
    uint64_t timestamp;
    data_t   data;
    sha_t    prevBlockHash;
    sha_t    hash;
    int      nonce;
};

Block make_block(std::string const& data,
                 sha_t const& prevBlockHash);
Block make_genesis_block();

#endif

#endif

block.cpp:

#define USE_BLOCK

#include "blockchain.h"

#include <chrono>

Block make_block(std::string const& data,
                 sha_t const& prevBlockHash)
{
    using namespace std::chrono;

    milliseconds ms = duration_cast<milliseconds>(system_clock::now().time_since_epoch());
    uint64_t timestamp = ms.count();
    data_t d(data.begin(), data.end());
    Block block{timestamp, d, prevBlockHash, sha_t(), 0};

    return block;
}

Block make_genesis_block()
{
    return make_block("Genesis Block", sha_t());
}

My questions:

How to improve code structure and architecture?
How to improve performance? Use constexpr or something else?
How to store the data that all are byte arrays, but some of arrays have fixed length (such as SHA256 hashes), and some have dynamic size (such as data)?
How to pass empty byte array? sha_t() is ok?
How to deal with time and make code short and fast?
What SHA256 library should I use?


texts: How should I pass settings to a module in Perl that also exports symbols?

texts:
In Test::Version I want to add configuration settings that allow one to toggle certain features. I'm thinking about passing an anonymous hash to a custom import like so.

use Test::Version 1.2 qw( version_ok ), { is_strict => '1', has_version => '0' };

other options I've thought of include package variables (though more ugly in my opinion).

use Test::Version 1.2 qw( version_ok );
$Test::Version::IS_STRICT   = 1;
$Test::Version::HAS_VERSION = 0;

or maybe using some other kind of operator to denote config settings on import, though I'm not sure exactly how to implement this.

use Test::Version 1.2 qw( version_ok ), +is_strict => '1', +has_version => '0';

Keep in mind that this has a simple functional interface, so passing objects, or using config files is overkill. Any preferences? or other suggestions?


texts:
I am looking for a review on the following code which is for this question. I am looking for a general review of the code. I am specifically also looking for advice on how to make this code run more efficiently.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.InputStreamReader;
import java.util.*;
public class Main
{
    public static void main(String args[]) throws IOException
    {
        int S[] = new int[100000];
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter out = new PrintWriter(System.out);
        String s[] = in.readLine().split(" ");
        int n = Integer.parseInt(s[0]);
        int m = Integer.parseInt(s[1]);
        String St = in.readLine();
        char num[] = St.toCharArray();
        for (int j = 0; j < m; j++)
        {
            String r1 = in.readLine();
            int r = Integer.parseInt(r1);
            int sum1 = 0, sum2 = 0;
            for (int p = 0, len = num[r - 1]; p < r - 1; p++)
            {
                int diff = len - num[p];
                if (diff < 0)
                    sum1 = sum1 + diff;
                else
                    sum2 = sum2 + diff;
            }
            out.println((sum2 - sum1));
        }
        out.flush();
        out.close();
    }
}