texts: Check the hardrive performance of the particular process using a Perl script

texts:
I have written the following Perl script to monitor the hardrive performance of the particular process (say, for example, Chrome).

use strict;
use warnings;
use Spreadsheet::WriteExcel;

#@usage example perl script.pl 5 5 if($#ARGV!=1);

my $login = (getpwuid $>);
die "must run as root" if $login ne 'root';

my $workbook = Spreadsheet::WriteExcel->new("Performance_report.xls");
my  $disk=$workbook->add_worksheet('disk');
$disk->write(0,0,"Time_interval",0);
$disk->write(0,1,"read/s",0);
$disk->write(0,2,"write/s",0);

#stores the time interval
my $time_interval=$ARGV[0];
#stores the no of iteration
my $test_count=$ARGV[1];
my $iter=0;
while($iter<$test_count)
{
   my @processes;
   @processes=`iotop -b -n 1 |grep chrome`;
   my $read_per_second=0;

   my $write_per_second=0;
   foreach(@processes)
   {
      my $read=0;
      my $write=0;
      while ($_ =~ /([\d\.]+)\s+[B|K]\/s+\s+([\d\.]+)/sg)
      {
          $read_per_second+=$1;
          $write_per_second+=$2;
      }
   }
   $disk->write($iter+1,0,$time_interval*($iter+1));
   $disk->write($iter+1,1,$read_per_second);
   $disk->write($iter+1,2,$write_per_second);
   sleep($time_interval);
   $iter++;
}
$workbook->close() or die "Cannot close the worksheet";

I have used the iotop tool in this script to monitor the disk performance.

sudo iotop -b -n 1 | grep chrome gives the following output:

3687 be/4 venkat      0.00 B/s    0.00 B/s  0.00 %  0.00 % chrome --type=zygote
4284 be/4 venkat      0.00 B/s    0.00 B/s  0.00 %  0.00 % chrome
3693 be/4 venkat      0.00 B/s    0.00 B/s  0.00 %  0.00 % chrome --type=zygote
3695 be/4 venkat      0.00 B/s    0.00 B/s  0.00 %  0.00 % chrome
3728 be/4 venkat      0.00 B/s    0.00 B/s  0.00 %  0.00 % chrome
5468 be/4 venkat      0.00 B/s    0.00 B/s  0.00 %  0.00 % chrome

I store the output to the array, process every value of the array, extract the second and third column value, recursively add the values of every thread of Chrome and store the final sum in the Excel sheet for every iteration.  Is there any better way to do this using a Perl script?


texts: Bash script to replace string in database

texts:
How secure is my script?

#!/usr/bin/env bash

echo "Input database name"
read databaseName
echo "The database name is set to $databaseName"

echo "Input database host"
read databaseHost
echo "The database host is set to $databaseHost"

echo "Input database user"
read user
echo "The database user is set to $user"

stty -echo
echo "Input database user password"
read password
stty echo

echo "Input url to search for"
read searchUrl
echo "The search url is set to $searchUrl"

echo "Input url to replace with the searched url"
read replaceUrl
echo "The replace url is set to $replaceUrl"

mysql --user="$user" --password="$password" --host="$databaseHost" --database="$databaseName" -e "UPDATE messages SET message = REPLACE(message, '$searchUrl', '$replaceUrl')"

Is it bad practise to get the user his password like this? Or is there anything I can improve?


texts: Parsing values from string into struct using match in Julia

texts:
My goal
I am parsing from a string which contains token:value pairs into a type.
Example:
mutable struct Foo
    bar
    baz
    qux
end

function parse(str::AbstractString)::Foo
    f = Foo()

    bar_pattern = r"bar:(\w*)"
    baz_pattern = r"baz:(\d*)"
    qux_pattern = r"qux:(\w*)"

    f.bar = match(bar_pattern, s)[1]
    f.baz = match(baz_pattern, s)[1]
    f.qux = match(qux_pattern, s)[1]

    return d
end

Problem
This works but only if the patterns are actually present. When match can't find the pattern, it returns nothing, which of course can't be indexed [1] or accessed with captures. The result is an error.
I want the fields of the returned struct to either get the matched result (the "capture") directly, or remain empty or set to nothing, should the match be unable to find the pattern.
I could do something like this:
function safeparse(str::AbstractString)::Foo
    f = Foo()

    bar_pattern = r"bar:(\w*)"
    baz_pattern = r"baz:(\d*)"
    qux_pattern = r"qux:(\w*)"

    if !isnothing(match(bar_pattern, s))
        f.bar = match(bar_pattern, s)[1]
    end

    if !isnothing(match(baz_pattern, s))
        f.baz = match(baz_pattern, s)[1]
    end

    if !isnothing(match(qux_pattern, s))
        f.qux = match(qux_pattern, s)[1]
    end

    return f
end

But that approach seems ugly and becomes verbose very quick if more/new patterns are introduced.
Question
Is there a nicer but readable way to achieve this?
Preferably without combining/changing the regex patterns or too much regex magic, however I am
open to that route too if it is the only nice (less verbose) way. I am of course also open to general tips.
To keep things simple, just assume that the patterns my example is looking for only appear 0 or 1 times. However if the only way to make this nicer involves writing another function like safematch which does the check for nothing and returns the captured value or nothing, I would want that to also work with multiple matches somehow and stay a bit more general.


texts: Complex class polymorphism and lazy-loaded components

texts:
I'm having an issue defining a base class and child classes, which handle initialization differently. I want it to work in ES6 but allow babel to transpile to ES5, and currently babel does not have a backwards compatible translation for new.target so I'm looking for something "close enough".

class Complex {
  constructor(real, imag, abs, arg) {
    if (new.target === Complex) {
      real = arguments.length > 0 && real !== undefined ? real : 0;
      imag = arguments.length > 1 && imag !== undefined ? imag : 0;
      abs  = arguments.length > 2 && abs  !== undefined ? abs  : Math.sqrt(real * real + imag * imag);
      arg  = arguments.length > 3 && arg  !== undefined ? arg  : Math.atan2(imag, real);

      this.real = real;
      this.imag = imag;
      this.abs  = abs >= 0 ? abs : -abs;
      // limits arg between (-pi, pi] and also corrects phase for negative abs
      this.arg  = arg ? -((-arg + (abs >= 0 ? Math.PI : 0)) % (Math.PI * 2) - Math.PI) : abs < 0 ? Math.PI : 0;
    }
  }

  // ... all mathematical static and non-static methods will go here
}

Complex.Cartesian = class Cartesian extends Complex {
  constructor(real = 0, imag = 0, abs, arg) {
    super();

    this.real = real;
    this.imag = imag;

    if (arguments.length === 4) {
      Object.defineProperties(this, {
        abs: {
          configurable: true,
          enumerable: true,
          value: abs >= 0 ? abs : -abs,
          writable: true,
        },
        arg: {
          configurable: true,
          enumerable: true,
          value: arg ? -((-arg + (abs >= 0 ? Math.PI : 0)) % (Math.PI * 2) - Math.PI) : abs < 0 ? Math.PI : 0,
          writable: true,
        },
      });
    }
  }

  get abs() {
    const value = Math.sqrt(this.real * this.real + this.imag * this.imag);

    Object.defineProperty(this, 'abs', {value, configurable: true, enumerable: true, writable: true});

    return value;
  }

  get arg() {
    const arg = Math.atan2(this.imag, this.real);
    const value = arg ? -((-arg + Math.PI) % (Math.PI * 2) - Math.PI) : 0;

    Object.defineProperty(this, 'arg', {value, configurable: true, enumerable: true, writable: true});

    return value;
  }
};

Complex.Polar = class Polar extends Complex {
  constructor(abs = 0, arg = 0, real, imag) {
    super();

    this.abs = abs >= 0 ? abs : -abs;
    this.arg = arg ? -((-arg + (abs >= 0 ? Math.PI : 0)) % (Math.PI * 2) - Math.PI) : abs < 0 ? Math.PI : 0;

    if (arguments.length === 4) {
      Object.defineProperties(this, {
        real: {
          configurable: true,
          enumerable: true,
          value: real,
          writable: true,
        },
        imag: {
          configurable: true,
          enumerable: true,
          value: imag,
          writable: true,
        },
      });
    }
  }

  get real() {
    const value = this.abs * Math.cos(this.arg);

    Object.defineProperty(this, 'real', {value, configurable: true, enumerable: true, writable: true});

    return value;
  }

  get imag() {
    const value = this.abs * Math.sin(this.arg);

    Object.defineProperty(this, 'imag', {value, configurable: true, enumerable: true, writable: true});

    return value;
  }
};

The general idea is to have a base class Complex() that handles initialization of all complex components (real, imag, abs, arg) when invoked directly, but not when invoked by child classes Cartesian() or Polar(), which use lazy-loaded abs and arg, or real and imag respectively.

My idea is to use this instanceof Object && this.constructor === Complex instead of new.target, but I'm not sure if that handles all edge cases exactly the same.

Any other advice not directly related to my specific issue is also welcome.

The code above is under MIT license, so if you plan on "borrowing" it for anything, please provide credit accordingly.


texts:
I need to validate the fields of user sent by an API. All works fine but the only one problem is that I don't like the solution is not an OOP solution. In the controller I call the service created by me:

$userValidatorService = $this->get(UserValidatorService::class);

And the service:

class UserValidatorService
{

/**
 * @var EntityManagerInterface
 */
private $entityManager;

/**
 * @var LoggerInterface;
 */
private $logger;

/**
 * @var TranslatorInterface
 */
private $translator;

/**
 * @var UserManagerInterface
 */
private $userManager;

/**
 * @var array
 */
private $locales;

/**
 * @var User
 */
private $user;

/**
 * @var array
 */
private $userFormData;

/**
 * UserValidatorService constructor.
 * @param EntityManagerInterface $entityManager
 * @param LoggerInterface $logger
 * @param TranslatorInterface $translator
 * @param UserManagerInterface $userManager
 */
public function __construct(
    EntityManagerInterface $entityManager,
    LoggerInterface $logger,
    TranslatorInterface $translator,
    UserManagerInterface $userManager
)
{
    $this->entityManager    = $entityManager;
    $this->logger           = $logger;
    $this->translator       = $translator;
    $this->userManager      = $userManager;
}
/**
 * @return array
 */
public function updateUser()
{
    $messages = [];

    if( '' !== $errorMessage = $this->validateEmail()){
        $messages['email'] = $errorMessage;
    }

    if( '' !== $errorMessage = $this->validateLocale()){
        $messages['locale'] = $errorMessage;
    // and all fields are validated like that
}
 /**
 * @return string
 */
private function validateEmail()
{
    if(isset($this->userFormData['email'])){
        if(!filter_var($this->userFormData['email'], FILTER_VALIDATE_EMAIL)){
            return $this->translator->trans('error.message');
        }
        return '';

    }
    return $this->translator->trans('error.message');
}

/**
 * @return string
 */
private function validateLocale()
{
    if(isset($this->userFormData['locale'])){
        if(!in_array($this->userFormData['locale'], $this->locales)){
            return $this->translator->trans('error.message');
        }
        return '';
    }
    return $this->translator->trans('error.message');
}

The question exists as a pattern to use to avoid this duplication and to do more OOP (I repeat that this code works just fine). I want to do that by myself without using Symfony validators.


texts:
I'm trying to dive deeper into C#, and so I've been experimenting with some code. I'm creating a console application that shows the path of a projectile depending on the angle, and it works great! You can check it out here actually. It's not perfect, but I like it.

Is there a better way to use my for loops? I'm using 3 inside eachother, and I'm not sure if that should be an issue. If you could take a look at the code in the link, it'd be great.

I realized my code might not have shown up. The code snippet won't work if you try to do it as you're missing a couple functions I've devised, but you should be able to get the idea just by looking at it.

using System.IO;
using System;
using System.Threading;
class Program
{

static void Main()
{
    Console.Clear();

    DoArc();
}

static void DoArc() {

            int tempVal = 0;
            string displayLine = "";
    //HERE
    for(int a = 0; a < 90; a+= 2) {

        Console.Clear();
        //HERE
        for(int y = 0; y < 16; y++) {
            //HERE
            for(int x = 0; x < 40; x++) {
                tempVal = Mathf.RoundToInt(Physics.HeightAtPoint(x, a, 15f, 0));
                tempVal = Mathf.Clamp(tempVal, 0, 16);

                if(Mathf.CloseTo(16 - y, tempVal, 1))
                displayLine += " X";
                else
                displayLine += " .";

            }
        Console.WriteLine(displayLine);
        displayLine = "";
        }
        Console.WriteLine("Angle: " + a);
        Thread.Sleep(500);

    }
}
}


texts: Send a volley request in the background every 10 seconds to a server

texts:
I created a class called HomeService that extends the android.app.Service. I then declared and implemented a class called BackgroundService which extends Thread. In the run method of the class I call the member method run of Runnable which calls my sendRequest method which is responsible for the Volley string request.

My service is supposed update the HomeActivity Text view so I implemented a broadcast listener in the activity and in the sendRequest I send a broadcast with an intent filter and the response from the server.

I am hoping someone can just take a look at me approach illustrated in the code bellow and tell me if it is the best approach. I have a feeling it is a little overkill. Thanks

public class HomeService extends Service {
BackgroundService service;
Intent responseComplete;

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

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

    if (!service.isRunning()) {
        service.start();
        service.isRunning = true;
    }
    return super.onStartCommand(intent, flags, startId);
}

@Override
public void onCreate() {
    super.onCreate();
    service = new BackgroundService();
    Log.d("CREATED>>>>", "Created");
}

@Override
public void onDestroy() {
    super.onDestroy();
    if (service.isRunning) {
        service.interrupt();
        service.isRunning = false;
        service = null;
    }
}

class BackgroundService extends Thread {
    public boolean isRunning = false;
    public long milliSecs = 10000;
    //        Handler networkRequest= new Handler();
    Runnable runTask = new Runnable() {
        @Override
        public void run() {
            isRunning = true;
            while (isRunning) {
                try {
                    Log.d("HANDLER_RUNNABLE>>>>", "HANDLER");
                    sendRequest();
                    Thread.sleep(milliSecs);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    isRunning = false;
                }
            }
        }
    };

    public boolean isRunning() {
        return isRunning;
    }

    @Override
    public void run() {
        super.run();
        runTask.run();
    }

    private void sendRequest() {
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constants.URL_HOME,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.d("RESPONSE>>>>", response);
                        responseComplete = new Intent(Constants.RESPONSE_SUCCESS);
                        responseComplete.putExtra("response", response);
                        LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(responseComplete);
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                responseComplete = new Intent(Constants.RESPONSE_ERROR);
                LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(responseComplete);
            }
        });
        VolleyController.getInstance().addToRequestQueue(stringRequest);
    }
}}


texts:
In a recent interview I have been asked to write a program to generate the following output:

* * * * *
 * * * *
  * * *
   * *
    *
   * *
  * * *
 * * * *
* * * * *

I had written the following code in java

public class Triangle
{
    public static void main( String[] args )
    {
        show( 5 );
    }

    public static void show( int n )
    {
        for ( int i = 0; i < n - 1; i++ )
        {
            for ( int j = 0; j < i; j++ )
            {
                System.out.print( " " );
            }
            for ( int k = n - i; k > 0; k-- )
            {
                System.out.print( "* " );
            }
            System.out.println();
        }
        for ( int i = 0; i < n; i++ )
        {
            for ( int j = n - i; j > 1; j-- )
            {
                System.out.print( " " );
            }
            for ( int k = 0; k < i + 1; k++ )
            {
                System.out.print( "* " );
            }
            System.out.println();
        }
    }
}

But the interviewer was not happy. He asked me minimize the number variables I had used. I didn't found a way. Anyone could help? Also, could there be a possibility to optimize the iteration here?


texts:
I'm using a one-dimensional array with length \$W(\text{weight capacity})\$. Is this is any better than the solutions with a two-dimensional array \$W, n\$ where \$n\$ is the number of items? I'm looking for code review, optimizations and best practices.

class Thieves:

    def __init__(self, details, items):
        self.details = details
        self.items = items
        self.index = [None] * (self.details[1] + 1)

    def valuable(self):
        ind = 0

        while ind < len(self.items):

            to_be_added = set()

            for i in range(1, len(self.index)):

                if self.items[ind][0] <= self.details[1]:

                    if self.index[i] == self.items[ind][1] and i == self.items[ind][0]:
                        if self.index[i * 2] != None:
                            if self.index[i * 2] < self.index[i] * 2:
                                self.index[i * 2] = self.index[i] * 2
                        else:
                            self.index[i * 2] = self.index[i] * 2

                    if i == self.items[ind][0]:
                        if self.index[i] != None and self.index[i] < self.items[ind][1]:
                            self.index[i] = self.items[ind][1]

                        elif self.index[i] == None:
                            self.index[i] = self.items[ind][1]

                    if i - self.items[ind][0] > 0 and i - self.items[ind][0] != self.items[ind][0]: #and self.index[self.items[ind][0]] == self.items[ind]  #and self.index[self.items[ind][0]] == self.items[ind][0]:
                        if self.index[i - self.items[ind][0]] != None and self.index[i] == None:
                            value = self.index[i - self.items[ind][0]] + self.items[ind][1]
                            to_be_added.add((i, value))

                        elif self.index[i - self.items[ind][0]] != None and self.index[i] != None:
                            if self.index[i] < self.index[i - self.items[ind][0]] + self.items[ind][1]:
                                to_be_added.add((i,self.index[i - self.items[ind][0]] + self.items[ind][1]))

            #print to_be_added
            for i in to_be_added:
                self.index[i[0]] = i[1]
            to_be_added = set()

            ind += 1

        print self.index[self.details[1]]

def main():

    t = Thieves((5, 5), [[3, 5], [7, 100], [1, 1], [1, 1], [2, 3]])
    t.valuable()

    z = Thieves((12, 5), [[3, 5], [7, 100], [1, 1], [1, 1], [2, 3], [3, 10], [2, 11], [1, 4], [1, 7], [5, 20], [1, 10], [2, 15]])
    z.valuable()

    k = Thieves((4, 10), [[6, 30], [3, 14], [4, 16], [2, 9]])
    k.valuable()


texts:
I have an MD5 hash string:

_hash = '743a0e0c5c657d3295d347a1f0a66109'

I want to write function that splits passed string to path in nginx cache format:

print hash2path(_hash, [1, 2, 3])
# outputs '7/43/a0e/743a0e0c5c657d3295d347a1f0a66109'

This is my variant:

def hash2path(_hash, levels):
    hash_copy = _hash
    parts = []
    for level in levels:
        parts.append(_hash[:level])
        _hash = _hash[level:]
    parts.append(hash_copy)
    return '/'.join(parts)

How could this be improved?


texts:
I will get straight to the point - I am a freshman at uni and I am currently working on my first bigger personal project - Statula is a terminal tool for data analysis which takes in dataset (as a file) and then spits out bunch of numbers about the numbers. I am quite satisfied with where it is going but I am not gonna lie -  I have some concerns.

Here is the git repo.

I will say it beforehand in case someone goes for a lecture - I am aware that I did not check for returned errors in compute_dataset.
I have just reworked some of them and I am kind of busy this week - I will get onto it as soon as possible. Also, my tests suck - or rather a single one. I have just introduced new structure which basically broke all of my tests. I am also working on that.

So, back to the point.
 My main focus is performance. I am satisfied with the fact that on my rig  (i5-4670k) this program can finish it's job in under 240ms. However, that is not good enough for me. I believe that the main performance hog might be the mode function - and for a good reason.

Here is the code:

int mode(struct dataset *set)
{
    assert(set->number_count>0);
    double max_value=0;
    int max_count=0,i,j,mode_count=1;
    for(i=0;i<set->number_count;i++){
        int count=0;
        for(j=i+1;set->numbers[j]==set->numbers[i]&&j<set->number_count;j++);
        count=j-i;
        if(count>max_count){
            mode_count=1;
            max_count=count;
            max_value=set->numbers[i];
        } else if(count==max_count) {
            mode_count++;
            i=j-1;
        }
    }
    if(mode_count==1){
        *(set->mode)=max_value;
        set->is_mode_present=1;
    } else{
        *(set->mode) = 0;
        set->is_mode_present=0;
    }
    return mode_count==1?1:0;
}

Perhaps there is some room for improvement. For the record, the number set is qsorted before being passed to the function. That's the main premise. Can it get any faster than that?

I also wonder whether the struct itself is a good idea - I guess there is no going back. Do not get me wrong, I have put a lot of thought into this matter and I came to a conclusion that by using struct I can:

Analyse multiple sets by reading multiple datasets - each has it's own struct. Beforehand, all I had was a local variable.
Avoid some unneccessary function calls - for instance, I have needed mean to compute standard deviation. Sure, I could pass it as an argument to a function, but.. where is the fun?

Unfortunately, that means that you cannot just copy-paste the function out of the source code and expect it to work - it relies on dataset structure being present.

So that is more of a general question - do you prefer your code to be correct (in a very loose sense) or portable?

General code suggestions are also welcome!


texts: Iconography - How would you improve this?

texts:
I would like your opinion on the following subject.
I have to provide icons in different sizes and states. The sizes will be 16*16, 24*24 and 32*32.

The states bright, dark, disabled and link.

Because of browser support we decided for .png instead of .svg.
Do you feel this is the best CSS approach for this case?

Would you make some changes to improve this styles?

<i class="fx-icon fx-icon-home">

.fx-icon { /*standard icon size*/
    border: none;
    display: inline-block;
    height: 16px;
    line-height: 16px;
    margin-right: 3px;
    vertical-align: top;
    width: 16px;
}

.fx-icon.fx-icon-medium {
    height: 24px;
    line-height: 24px;
    width: 24px;
}

.fx-icon.fx-icon-large {
    height: 32px;
    line-height: 32px;
    width: 32px;
}

.fx-icon.fx-icon-larger {
    height: 48px;
    line-height: 48px;
    width: 48px;
}

/*Icon Home*/
.fx-icon-home-bright,
.fx-icon-home-dark,
.fx-icon-home-disabled,
.fx-icon-home-link {
    background: url(images/icon-home.png) no-repeat;
}

.fx-icon-home-dark {
    background-position: -16px 0;
}

.fx-icon-home-disabled {
    background-position: -32px 0;
}

.fx-icon-home-link {
    background-position: -48px 0;
}


texts: Efficient Album Cover loading for ListView

texts:
I have a list view which display in each view a Album's name, the associated Artist and the album art.

Here is the code of my ListFragment which display this list:

public class AlbumsFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor> {

AlbumsAdapter mAdapter;

        @Override
           public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
           View myFragmentView = inflater.inflate(R.layout.albums_fragment_layout, container, false);
           return myFragmentView;
         }

        @Override
          public void onActivityCreated(Bundle savedInstanceState) {
           super.onActivityCreated(savedInstanceState);

                    mAdapter = new AlbumsAdapter(getActivity(), null);
                    setListAdapter(mAdapter);
                    getLoaderManager().initLoader(0, null, this);
        }

static final String[] ALBUM_SUMMARY_PROJECTION = { MediaStore.Audio.Albums._ID, MediaStore.Audio.Albums.ALBUM, MediaStore.Audio.Albums.ARTIST, MediaStore.Audio.Albums.ALBUM_ART,};

        public Loader<Cursor> onCreateLoader(int id, Bundle args) {
            String select = null;
            return new CursorLoader(getActivity(), MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,ALBUM_SUMMARY_PROJECTION, select, null, null);
        }

        public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
            mAdapter.swapCursor(data);
        }

        public void onLoaderReset(Loader<Cursor> loader) {
            mAdapter.swapCursor(null);
        }
    }

Here is my custom CursorAdapter's code:

public class AlbumsAdapter extends CursorAdapter {

    private final LayoutInflater mInflater;

     public AlbumsAdapter(Context context, Cursor c) {
        super(context, c);
        mInflater=LayoutInflater.from(context);

    }
    @Override
    public void bindView(View view, Context context, Cursor cursor) {

        ViewHolder holder = (ViewHolder) view.getTag();
        if (holder == null) {
            holder = new ViewHolder();
            holder.albumTitle = (TextView) view.findViewById(R.id.albumTextView);
            holder.artistName = (TextView) view.findViewById(R.id.artistTextView);
            holder.coverAlbum = (ImageView)view.findViewById(R.id.album_cover);
            holder.column1 = cursor.getColumnIndexOrThrow(MediaStore.Audio.Albums.ALBUM);
            holder.column2 = cursor.getColumnIndexOrThrow(MediaStore.Audio.Albums.ARTIST);
            holder.column3 = cursor.getColumnIndexOrThrow(MediaStore.Audio.Albums.ALBUM_ART);
            view.setTag(holder);
        }
        holder.albumTitle.setText(cursor.getString(holder.column1));
        holder.artistName.setText(cursor.getString(holder.column2));
        Bitmap coverBitmap = BitmapFactory.decodeFile(cursor.getString(holder.column3));
        holder.coverAlbum.setImageBitmap(coverBitmap);
    }

    static class ViewHolder {
        TextView albumTitle;
        TextView artistName;
        ImageView coverAlbum;
        int column1;
        int column2;
        int column3;
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        final View view=mInflater.inflate(R.layout.albums_row,parent,false);
        return view;
    }

}

As you can see, I use already the trick of the ViewHolder to avoid calling findViewById too often.

But the problem is that my list is still very slow. What can I do to optimize it even more? For instance I could load in priority the Albums' title and Artists' names and display them and then, load in a second time the cover (asynchronously).

I've also tried to scale down the resolution of the Cover's Bitmap before displaying them in the ImageViews, but I saw no improvement :/

Do you have any idea how to make this list less laggy? Any advice is welcome.


texts: Get tuple of the first and last days of the last N months

texts:
I am trying to get a tuple of date (or datetime) objects over the last N months.

My thought was to use the dateutil package with something like this:

def last_n_months(n=12, ending=None):
    """Return a list of tuples of the first/last day of the month
    for the last N months
    """
    from datetime import date
    from dateutil.rrule import rrule, MONTHLY
    from dateutil.relativedelta import relativedelta

    if not ending:
        ending = date.today()

    # set the ending date to the last day of the month
    ending = ending + relativedelta(months=+1, days=-ending.day)

    # starting is the first day of the month N months ago
    starting = ending - relativedelta(months=n, day=1)

    months = list(rrule(MONTHLY, bymonthday=(1, -1), dtstart=starting,
                        until=ending))

    # we return pairs of dates like this: (1st day of month, last day of month)
    months = zip(months[::2], months[1::2])

    return months

Example usage:

    >>> from datetime import date, timedelta

    # get last two months as a degenerate example
    >>> l2n = last_n_months(2, ending=date(2012, 01, 01))
    >>> map(lambda x: [x[0].year, x[0].month, x[0].day], l2n)
    [[2011, 11, 1], [2011, 12, 1], [2012, 1, 1]]
    >>> map(lambda x: [x[1].year, x[1].month, x[1].day], l2n)
    [[2011, 11, 30], [2011, 12, 31], [2012, 1, 31]]

    >>> l24n = last_n_months(24, ending=date(2012,03,16))
    >>> len(l24n) # inclusive of current month
    25

    # every tuple starts with the first day of the month
    >>> all(x[0].day == 1 for x in l24n)
    True

    # every tuple ends with the last day of the month
    >>> all((x[1] +timedelta(days=1)).month != x[1].month for x in l24n)
    True

    # every tuple is the same month
    >>> all(x[0].month == x[1].month for x in l24n)
    True

I am posting it here to see if anyone has a better solution than this (and perhaps see if this yields some off-by-one sort of error that I haven't thought of).

Is there a simpler or faster solution than this?


texts:
Is there a better way I can code this? It's old code and I'm not sure makes sense today. JSLint gives me a lot of errors too. I don't have experience with JavaScript and I would like to optimize this snippet.

Any suggestion? Maybe I can achieve better code with JQuery?

<script type="text/javascript">
// <![CDATA[
    var jump_page = '{LA_JUMP_PAGE}:',
    var on_page = '{ON_PAGE}';
    var per_page = '{PER_PAGE}';
    var base_url = '{A_BASE_URL}';
    var style_cookie = 'phpBBstyle';
    var style_cookie_settings = '{A_COOKIE_SETTINGS}';
    var onload_functions = new Array();
    var onunload_functions = new Array();

    /**
    * Find a member
    */
    function find_username(url)
    {
        popup(url, 760, 570, '_usersearch');
        return false;
    }

    /**
    * New function for handling multiple calls to window.onload and window.unload by pentapenguin
    */
    window.onload = function()
    {
        for (var i = 0; i < onload_functions.length; i++)
        {
            eval(onload_functions[i]);
        }
    };

    window.onunload = function()
    {
        for (var i = 0; i < onunload_functions.length; i++)
        {
            eval(onunload_functions[i]);
        }
    };

// ]]>
</script>

This is how an handler is called for example:

<script type="text/javascript">
// <![CDATA[
    /**
    * Change language
    */
    function change_language(lang_iso)
    {
        document.forms['register'].change_lang.value = lang_iso;
        document.forms['register'].submit.click();
    }

    <!-- IF CAPTCHA_TEMPLATE and S_CONFIRM_REFRESH -->
    onload_functions.push('apply_onkeypress_event()');
    <!-- ENDIF -->

// ]]>
</script>


texts: Converting a list of integers into a two-dimensional array in Java

texts:
I want to convert a list of integers into a two-dimensional array for use with TestNG DataProvider.  Here is the code I've written:

static List<Integer> studentList = new ArrayList<Integer>();

@Test()
public void testMethod(){
    studentList.add(477915);
    studentList.add(477916);
    studentList.add(477917);
    System.err.println(studentList);
}

@DataProvider(name = "persons")
public static Object[][] primeNumbers() {
    Object [][] objArray = new Object[studentList.size()][];

    for(int i=0;i< studentList.size();i++){
        objArray[i] = new Object[1];
        objArray[i][0] = studentList.get(i);
    }

    return objArray;
}

@Test(dataProvider="persons")
public void testRunPersonRules(int val) {
    System.err.println(val);
}

Is there a better way to accomplish this?


texts: Implementation of Sieve of Eratosthenes in Python

texts:
The following is my implementation of Sieve of Eratosthenes. Can somebody please review it? Am I adhering to the algorithm and is it a reasonable implementation of it?

def SieveofEratosthenes(primeseries):

    i=1
    primeserieslist = []
    while(i<primeseries):
        i=i+1
        primeserieslist.append(i)

    x=2

    primeslist = []

    while x <= primeseries and x*2 <= primeseries:
        j=2
        while (j < primeseries):
            z = j*x
            if (z <= primeseries):
                if (z in primeserieslist):
                    primeserieslist.remove(z)
            j = j+1

        x=x+1

    print primeserieslist

SieveofEratosthenes(1000000)


texts:
I've created a private function called _successResponse to handle successful responses from my promise.

The challenge was passing the dispatch function to the _successResponse which is being passed to the .then method as a callback.

I accomplished this by currying using .bind. I would love to get feedback on this approach.

import axios from 'axios';
import { browserHistory } from 'react-router';
import {
        AUTH_USER,
        AUTH_ERROR,
        UNAUTH_USER,
        FETCH_MESSAGE
    } from './types';

const ROOT_URL = 'http://localhost:3090';

export function signinUser({ email, password }){
    return function(dispatch){
        // Submit email/password to server
        axios.post(`${ROOT_URL}/signin`, { email, password })
            .then(_successResponse.bind(null, dispatch))
            .catch(() => {dispatch(authError('Bad Login Info'))})
    }
}

export function signupUser({email, password}){
    return function(dispatch){
        axios.post(`${ROOT_URL}/signup`, { email, password })
            .then(_successResponse.bind(null, dispatch))
            .catch(response => {dispatch(authError(response.response.data.error))});
    }
}

export function authError(error){
    return {
        type: AUTH_ERROR,
        payload: error
    }
}

export function signoutUser(){
    localStorage.removeItem('token');

    return { type: UNAUTH_USER }
}

export function fetchMessage(){
    return function(dispatch){
        axios.get(ROOT_URL, {
            headers: { authorization: localStorage.getItem('token') }
        })
            .then(response => {
                dispatch({
                    type: FETCH_MESSAGE,
                    payload: response.data.message
                })
            });
    }
}

// Private functions
function _successResponse(dispatch, response){
        // If request is valid...
        // - Update state to indicate user is authenticated
        dispatch({ type: AUTH_USER });
        // - Save the JWT token
        localStorage.setItem('token', response.data.token);
        // - redirect to the route '/feature'
        browserHistory.push('/feature');
}


texts:
Please point out every problem you see with this code. Any fundamental flaws, naming conventions, design decisions, you name it.

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

class SieveHelper {
public:
    SieveHelper() : cur(2) {}

    bool operator()(unsigned int i) {
        return i != cur && i % cur == 0;
    }

    unsigned int cur;
};

void sieve(std::vector<unsigned int>& arr) {
    SieveHelper helper;
    auto it = arr.begin();

    while (it != arr.end()) {
        helper.cur = *it;

        auto last = std::remove_if(it, arr.end(), helper);
        arr.erase(last, arr.end());

        it++;
    }
}

int main() {
    int n;
    std::cin >> n;

    std::vector<unsigned int> arr(n);
    for (int i = 2; i <= n; i++)
        arr[i-2] = i;

    sieve(arr);

    std::for_each(arr.begin(), arr.end(), [](unsigned int i) {
        std::cout << i << " ";
    });
    return 0;
}


texts:
I made an attempt to implement a Properties File MRU Cache with a limited cache size which are of the most recently used properties can only be held in.  A read miss from this cache leads to a read from the file for that particular property and keep it in the cache until it goes out of the limit where other recently properties gets read into the cache from the file.

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedHashMap;

public class PropertiesFileMRUCache {

    private LinkedHashMap<String, String> propertiesMap = new LinkedHashMap<>(
            10);

    private int limit = 8;

    private String propertiesFile = "default.properties";

    public PropertiesFileMRUCache() {

    }

    public PropertiesFileMRUCache(String propertiesFile) {
        this.propertiesFile = propertiesFile;
    }

    public PropertiesFileMRUCache(int limit, String propertiesFile) {
        this(propertiesFile);
        this.limit = limit;
    }

    public String getCapital(String country) {
        String capital = propertiesMap.get(country);
        if (capital == null) {
            capital = readFromFile(country);
            if (propertiesMap.size() == limit) {
                propertiesMap.remove(propertiesMap.keySet().iterator().next());
            }
        } else {
            propertiesMap.remove(country);
        }
        propertiesMap.put(country, capital);
        return capital;
    }

    private String readFromFile(String country) {
        try (BufferedReader br = new BufferedReader(new FileReader(
                propertiesFile))) {
            for (String line; (line = br.readLine()) != null;) {
                if (line.startsWith(country)) {
                    return line.substring(line.indexOf('=') + 1);
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        PropertiesFileMRUCache pfc = new PropertiesFileMRUCache("res\\CountryCapital.properties");
        pfc.getCapital("India");
        pfc.getCapital("USA");
        pfc.getCapital("UK");
        pfc.getCapital("Kuwait");
        pfc.getCapital("Iraq");
        pfc.getCapital("Canada");
        pfc.getCapital("Australia");
        pfc.getCapital("India");
        pfc.getCapital("India");
        pfc.getCapital("India");
        pfc.getCapital("Germany");
        pfc.getCapital("India");
        pfc.getCapital("Germany");
        pfc.getCapital("China");
        pfc.getCapital("Pakistan");
        System.out.println(pfc.propertiesMap);
    }
}

For testing purpose I provided a user specified property as res\CountryCapital.properties with the default cache limit as 8.  The content of the CountryCapital.properties is provided below for reference:

India=New Delhi
USA=Washington
Egypt=Cairo
Srilanka=Columbo
South Korea=Seoul
Tailand=Bangkok
Qutar=Doha
Lebanon=Beirut
Canada=Toronto
Norway=Oslo
Sweden=Stockholm
Finland=Helsinki
China=Beiging
Japan=Tokyo
Bangladesh=Dhaka
Pakistan=Karachi
Afganistan=Kabul
Australia=Sydney
Newzeland=Wellington
Ireland=Dublin
Germany=Berlin
Itlay=Rome
Nepal=Kadmantu
North Korea=Pyongyang
Brazil=Brazilia
South Africa=Cape Town
France=Paris
Czech Repulic=Prague
Austria=Vienna
Israel=Jerusalem
Kuwait=Kuwait City
Greece=Athens
Iraq=Bagdad
Syria=Demascaus
Denmark=Copengahen
UK=London


texts:
This Lua code runs in redis. It iterates over some JSON docs, and applies some logic based on the user (if any) making the request. I'm sure there's a lot I can improve here.

local function iterAll(limit)
  local start = 0
  local stop = limit-1
  local ids = redis.call('zrevrange', 'questions-by-latest', start, stop)
  local i = 0
  local function it()
    i = i+1
    if i <= #ids then
      return ids[i]
    elseif i > #ids then
      start = start+limit
      stop = stop+limit
      i = 1
      ids = redis.call('zrevrange', 'questions-by-latest', start, stop)
      if #ids > 0 then
        return ids[i]
      end
    end
  end
  return it
end

local function filter(qid, optUid)
  local q = cjson.decode(redis.call('hget', 'questions', qid))
  if not q['is-active'] then return false end

  if optUid then
    local u = cjson.decode(redis.call('hget', 'users', optUid))
    if #u['ignored-tags'] > 0 then
      for idx, itag in ipairs(u['ignored-tags']) do
        for jdx, qtag in ipairs(q['tags']) do
          if itag == qtag then return false end
        end
      end
    end
  end

  return true
end

local offset = tonumber(ARGV[1])
local limit = tonumber(ARGV[2])

local optUid = false
if #ARGV == 3 then
  optUid = tonumber(ARGV[3])
end

local i = 0
local j = 0
local ids = {}
for qid in iterAll(limit) do
  if filter(qid, optUid) then
    i = i+1
    if i > (offset+limit) then break end
    if i > offset then
      j = j+1
      ids[j] = qid
    end
  end
end

return ids


texts: Implementation of Generic SQL Data Reader

texts:
I am using below virtual method to read the data from SQL Data Reader like:

public IList<District> GetList()
{
    IList<District> _list = new List<District>();

    SqlConnection con = new SqlConnection(ConStr);
    try
    {
        string StoreProcedure = ConfigurationManager.AppSettings["SP"].ToString();

        SqlCommand cmd = new SqlCommand(StoreProcedure, con);
        cmd.CommandType = CommandType.StoredProcedure;
        con.Open();
        SqlDataReader rdr = cmd.ExecuteReader();
        _list = new GenericReader<District>().CreateList(rdr);
        rdr.Close();
        con.Close();
    }
    finally
    {
        IsConnectionOpenThenClose(con);
    }
    return _list;
}

District Class:

public class District
{
    public int id { get; set; }
    public string name { get; set; }
}

And GenericReader Class as:

public class GenericReader<T>
{
    public virtual List<T> CreateList(SqlDataReader reader)
    {
        var results = new List<T>();

        while (reader.Read())
        {
            var item = Activator.CreateInstance<T>();
            foreach (var property in typeof(T).GetProperties())
            {
                if (!reader.IsDBNull(reader.GetOrdinal(property.Name)))
                {
                    Type convertTo = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
                    property.SetValue(item, Convert.ChangeType(reader[property.Name], convertTo), null);
                }
            }
            results.Add(item);
        }
        return results;
    }
}

Is this approach is better or still, we can refactor?


texts:
I want to achieve this

var arr = [1,2,3];

var duplicateArr = duplicate(arr, 2) // will be [1,2,3,1,2,3]

var duplicateArr2 = duplicate(arr, 3) // will be [1,2,3,1,2,3,1,2,3]

I have implemented it like this:

function duplicate(arr, n) {
  var len = arr.length;
  if (n == 0 || n == 1) {
    return arr;
  }
  if (n > 1) {
    for (var j = 0; j < n - 1; j++) {
      for (var i = 0; i < len; i++) {
        arr.push(arr[i])
      }
    }
  }
  console.log(arr);
}
duplicate([1, 2, 3], 3);

I know this may not be the efficient way to do it.


texts: Project Euler problem 79: deducing a passcode

texts:
For one place that I interviewed at (for a Python developer position) I worked with one of the devs on two Project Euler problems, one being problem 79. We talked through different approaches and came up with solutions together, but we coded separately. He seemed impressed that we were able to get through two problems. After the interview, he asked me to clean up the code and submit it, which you can see below. He never got back to me after I sent him the code. I'd like to know what's wrong with my code and not make the same mistakes again.
Problem 79:

A common security method used for online banking is to ask the user for three random characters from a passcode. For example, if the passcode was 531278, they may ask for the 2nd, 3rd, and 5th characters; the expected reply would be: 317.
The text file, keylog.txt, contains fifty successful login attempts.
Given that the three characters are always asked for in order, analyse the file so as to determine the shortest possible secret passcode of unknown length.

# problem79.py
# Project Euler
# Nicolas Hahn

# list of keys -> passcode string
# at each iteration through list,
def passcodeDerivation(keys):
    answer = ''
    while len(keys) > 0:
        firsts = []
        rests = []
        for key in keys:
            # split first digits, rest of the key into two lists
            f, r = key[0], key[1:]
            if f not in firsts:
                firsts += f
            rests += r
        for f in firsts:
            # if f has never been seen except as the first digit of a key
            # it must be the next one in the passcode
            if f not in rests:
                newkeys = []
                # take out digit we just found from all keys
                for key in keys:
                    newkeys.append(key.replace(f,''))
                # remove empty keys
                keys = [k for k in newkeys if k != '']
                answer += f
                break
    return answer

# filename -> list of keys
def loadKeys(keyFile):
    keys = []
    with open(keyFile,'r') as f:
        for line in f:
            keys.append(line.replace('\n',''))
    return keys

def main():
    keys = loadKeys('problem79keylog.txt')
    # correct answer = 73162890
    print(passcodeDerivation(keys))

if __name__ == "__main__":
    main()


texts:
I am currently doing a project for school, and I am completely stumped. We are only on Chapter 8 of C# Development 1 and I have a question about the code.
The project is:

Use a one-dimensional array to solve the following problem:
Write an app that the user inputs numbers, each of which is between 10 and 100, inclusive. As each number is read, display it only if it’s not a duplicate of a number already read. Provide for the “worstcase,” in which all numbers are different. Use the smallest possible array to solve this problem. Display the complete set of unique values input after the user inputs each new value.

So far, this is what I have for the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MidtermHandsOn
{
class Program
{
static void Main(string[] args)
{
    //Create array from user input.
    Console.WriteLine("How many numbers will you enter?");
    int Array_Size = Convert.ToInt32(Console.ReadLine());
    int[] Array_Numbers = new int[Array_Size];
    //End array creation.

    //Input numbers into the array.
    int OuterCounter = 0;
    while (OuterCounter < Array_Size)
    {
        Console.Write("Enter number: ");
        int UserNumber = Convert.ToInt32(Console.ReadLine());

        if (UserNumber >= 10 && UserNumber <= 100) //Check if the numbers are between 10 and 100.
        {
            Array_Numbers[OuterCounter] = UserNumber;

            for (int InnerCounter = 0; InnerCounter < Array_Numbers.Length; InnerCounter++)
            {
                if (Array_Numbers[InnerCounter] > 0)
                {
                   Console.WriteLine(Array_Numbers[InnerCounter]);
                }
            }

            OuterCounter++;
        }
        else
        {
            Console.WriteLine("Number must be between 10 and 100");
        }
    }

    Console.ReadKey();
}
}
}

I can get the numbers to input and display in order, which is all well and good, but I cannot for the life of me get the duplicates eliminated.
Now, I'm not wanting the answer to the issue or anything, just wanting to get pointed in the right direction.
Is there ANY way to eliminate duplicates WITHOUT using Linq or Hashset or anything of the sort?


texts: Exporting a table with header and subheader

texts:
I have an array matrix, for example A(3,3), I want to make a table with header names like, ['force','mass','acceleration'], the second row contains the units (subheader), ['N','Kg','m/s^2'], and the rest of the table contains the elements of A.

I want to export this table as a (.dat) file, how can I do that in an efficient way (I want to implement it for a large number of matrices)?

This is my code, which I believe it is not professional.

A = [1,2,3;4,5,6];

C(1,:) = {'force','mass','acceleration'};
C(2,:) = {'N','Kg','m/s^2'};

C(3,:) = num2cell(A(1,:));
C(4,:) = num2cell(A(2,:));
T = cell2table(C)

writetable(T,'tabledata.dat')

also this is a new update

A = [1,2,3;4,5,6;7,8,9];
C(1,:) = {'N','Kg','m/s^2'};
C(3:5,:) = num2cell(A(:,:));

T = cell2table(C)

T.Properties.VariableNames = {'force' 'mass' 'acceleration'};

writetable(T,'tabledata.dat','Delimiter','\t')


texts: Python sprinting game using strings, loops and statements

texts:
Here is my code for a sprinting game in Python. You have to tap the 'a' and 'd' keys as fast as you can to run 100 meters. Any improvements?

import msvcrt
import time
high_score = 50
name = "no-one"
while True:
    distance = int(0)
    print("\n--------------------------------------------------------------")
    print('\n\nWelcome to the 100m sprint, tap a and d rapidly to move!')
    print('* = 10m')
    print("\n**Current record: " + str(high_score) + "s, by: " + name)
    print('\nPress enter to start')
    input()
    print('Ready...')
    time.sleep(1)
    print('GO!')
start_time = time.time()
while distance < 100:
    k1 = msvcrt.getch().decode('ASCII')
    if k1 == 'a':
        k2 = msvcrt.getch().decode('ASCII')
        if k2 == 'd':
            distance += 1
            if distance == 50:
                print("* You're halfway there!")
                elif distance % 10 == 0:
                    print('*')
fin_time = time.time() - start_time
fin_time = round(fin_time,2)
print('Well done you did it in...'+str(fin_time))
if fin_time < high_score:
    print("Well done you've got a new high score ")
    name = input("Please enter your name : ")


texts:
Code is below. I'd like to know if this is a solid/efficient implementation of the in-place quicksort algorithm and if my Python style is good (I know there are no comments for now). Code is also on Github here if you'd like: https://github.com/michaelrbock/data-structs-and-algos/blob/master/Sorts/quicksort.py Thanks!

def quicksort(lst):
    if len(lst) <= 1:
        return lst
    lst, store_index = partition(lst)
    return quicksort(lst[:store_index-1]) + [lst[store_index-1]] + quicksort(lst[store_index:])

def partition(lst):
    if len(lst) % 2 == 0:
        middle = (len(lst) / 2) - 1
    else:
        middle = len(lst) / 2

    pivot_choice = get_median( [lst[0], lst[middle], lst[len(lst)-1]] )

    if pivot_choice == lst[0]:
        PIVOT_INDEX = 0
    elif pivot_choice == lst[middle]:
        PIVOT_INDEX = middle
    elif pivot_choice == lst[len(lst)-1]:
        PIVOT_INDEX = len(lst) - 1

    pivot = lst[PIVOT_INDEX]
    lst[0], lst[PIVOT_INDEX] = lst[PIVOT_INDEX], lst[0]
    i = 1
    for j in range(1, len(lst)):
        if lst[j] < pivot:
            lst[j], lst[i] = lst[i], lst[j]
            i += 1
    lst[0], lst[i-1] = lst[i-1], lst[0]
    return lst, i

def get_median(nums):
    values = sorted(nums)
    if len(values) % 2 == 1:
        return values[(len(values)+1)/2-1]
    else:
        lower = values[len(values)/2-1]
        upper = values[len(values)/2]
    return (lower+upper)/2


texts:
I want to get my first CSS layout reviewed.
First of all, the related HTML code is as follows -

<!DOCTYPE html>

<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title> Preferences </title>

        <script src="options.js"></script>
        <link rel="stylesheet" href="options.css" />
    </head>

    <body>
        <h1> Search in New Tab - Preferences </h1>
        <form id="preference-form">
                <label for="search-engine"> Search Engine </label>
                <select id="search-engine">
                    <option id="google" value="google" selected="selected"> Google </option>
                    <option id="bing" value="bing"> Bing </option>
                    <option id="yahoo" value="yahoo"> Yahoo! </option>
                    <option id="duckduckgo" value="duckduckgo"> DuckDuckGo </option>
                    <option id="wikipedia" value="wikipedia"> Wikipedia </option>
                </select>

                <br>

                <label for="focus-search-tab"> Make the search tab active </label>
                <input type="checkbox" value="focus-search-tab" id="focus-search-tab" />
        </form>
    </body>
</html>

I wrote the following CSS file in order to provide satisfactory presentation to the HTML -

h1
{
    width : 40%;
    background : #eeeeee;
    box-shadow : 0 0 5px 5px #888;
    margin-top : 10%;
    margin-left : 30%;
    margin-right : 30%;
    padding-top : 10px;
    padding-bottom : 10px;
    text-align : center;
    font-family : "Arial", "Century Gothic", "Lucida Sans Unicode";
}

form
{
    width : 30%;
    background : #eeeeee;
    box-shadow: 0 0 5px 5px #888;
    margin-top : 1%;
    margin-left : 35%;
    margin-right : 35%;
    padding-top : 10px;
    padding-bottom : 10px;
}

label
{
    width : 60%;
    display : inline-block;
    text-align : right;
    margin-top : 10px;
    margin-bottom : 10px;
    margin-right : 10px;
    font-family : "Arial";
}

The resulting HTML document looks like this:

Basically, I wanted to avoid the use of float property. I felt that I could accomplish the same by using combinations of inline-block property, padding and margins. So, I used that. Was that the right way?
Other than that, I would like to know if I did things right. Also, any improvements that make my CSS code better are welcome.


texts: Node Express App - Create structure around incoming payload

texts:
I am working on a simple NodeJS express app that accepts an incoming payload from a few different systems. There is a single route that ships the data off to another method and waits for the promise.

I am trying to make the incoming endpoint more secure to at least define an expected schema of the post data.

Payload Example - I require a topic that must be a string, and a data object which can really be anything as shown. The key/values are all dynamic in the data property so I can't define specifically what I want.

What is the best way to add some security to an incoming endpoint like this?

{
    "topic": "tool-ingest",
    "data": {
        "firstName": "Jim",
        "lastName": "Bob",
        "age": 28,
        "department": "None",
        "campus": "A2",
        "state": "Florida"
    }
}

-

/**
 *
 * server.js
 *
 * Handles the routing of the application.
 * We wait for data to be sent over to the defined
 * endpoints and then get routed accordingly.
 *
 */

// Defined variables
require("dotenv").config();

const asyncHandler = require("express-async-handler"),
  producer = require("./producer"),
  express = require("express"),
  app = express(),
  bodyParser = require("body-parser"),
  port = process.env.PORT || 5000,
  utilities = require("./utilities");

// Express Config
app.use(bodyParser.json());

// Receive our incoming payload
app.post(
  "/payload",
  asyncHandler(async (req, res, next) => {
    let result = await producer.sendToProducer(req.body);
    res.json(result);
  })
);

// Begin Listening
app.listen(port, () => {
  utilities.logError(`Server Listening...`);
});

/**
 *
 * producer.js
 *
 * After receiving a payload from ingest,
 * send our data to the kafka producer
 * which will contain the topic and message.
 *
 */

// Defined variables
const kafka = require("kafka-node"),
  HighLevelProducer = kafka.HighLevelProducer,
  utilities = require("./utilities");

module.exports = {

  sendToProducer: async function(payload) {

    return new Promise((resolve, reject) => {

      var client = new kafka.KafkaClient(),
        producer = new HighLevelProducer(client);

      let mappedData = utilities.mapFields(payload);
      mappedData.message_uuid = uuidv1();

      // Define our topic object
      const topicObj = [
        {
          topic: payload.topic,
          messages: JSON.stringify(mappedData)
        }
      ];

      // On producer ready
      producer.on("ready", function() {

        // Send our payload to our topic
        producer.send(topicObj, function(err, data) {

          if (err) {
            utilities.logError("Producer Sent received error", {
              error: error,
              data: data
            });
            reject(err);
          }

          producer.close();
          resolve(data);

        });
      });

      // On producer error
      producer.on("error", function(err) {
        utilities.logError("Producer received error", err);
        producer.close();
        reject(err);
      });

    });
  }
};


texts:
I have this code that is working as intended I would just like to speed it up.

#include <windows.h>

void pressW();

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

    DWORD x = 566;
    DWORD y = 967;
    DWORD red = 2039797;
    DWORD gold = 43963;
    DWORD blue = 15715270;

    while (true) {
        if (GetAsyncKeyState(0x31)) {
            pressW();
            while (true) {
                HDC dc = GetDC(NULL);
                COLORREF color = GetPixel(dc, x, y);
                ReleaseDC(NULL, dc);
                if (color == blue) {
                    pressW();
                    break;
                }
            }
        }
        else if (GetAsyncKeyState(0x32)) {
            pressW();
            while (true) {
                HDC dc = GetDC(NULL);
                COLORREF color = GetPixel(dc, x, y);
                ReleaseDC(NULL, dc);
                if (color == red) {
                    pressW();
                    break;
                }
            }
        }
        else if (GetAsyncKeyState(0x33)) {
            pressW();
            while (true) {
                HDC dc = GetDC(NULL);
                COLORREF color = GetPixel(dc, x, y);
                ReleaseDC(NULL, dc);
                if (color == gold) {
                    pressW();
                    break;
                }
            }
        }
    }
}

void pressW() {
    INPUT i;
    i.type = INPUT_KEYBOARD;
    i.ki.wScan = MapVirtualKey(0x57, MAPVK_VK_TO_VSC);
    i.ki.time = 0;
    i.ki.dwExtraInfo = 0;
    i.ki.wVk = 0x57;
    i.ki.dwFlags = 0;
    SendInput(1, &i, sizeof(INPUT));
    i.ki.dwFlags = KEYEVENTF_KEYUP;
    SendInput(1, &i, sizeof(INPUT));
}

Basically what it does is when I press 1/2/3 it presses W and waits for the the pixel at x, y coordinates to change color corresponding to what key I pressed and presses W again.

I want it to have 10-15ms delay from the point when I press 1/2/3 to when it scans the pixel and presses the 2nd W, but I don't really know how to optimize this. Right now it's taking a snapshot of the entire screen but I just want to check that single pixel, also it's declaring everything for the sendinput every time I call that function because simply putting

SendInput(1, &i, sizeof(INPUT));
i.ki.dwFlags = KEYEVENTF_KEYUP;
SendInput(1, &i, sizeof(INPUT));

in the pressW() didn't work.


texts: Functional Conway's Game of Life in JavaScript

texts:
In this code, I tried to integrate my little knowledge of (and great fascination towards) functional programming. I'd like to make this code more functional, and faster, if that's possible.

'use strict';
var insert = require('./insert');

const STEP = 50;
const WIDTH = 200, HEIGHT = 100;
var ptr  = [[0, 1, 0, 0, 0, 0, 0],
            [0, 0, 0, 1, 0, 0, 0],
            [1, 1, 0, 0, 1, 1, 1]];

function init(scr) {
    var cwObj = {
        canvas: document.getElementById(scr),//set up the graphics department
        gMap: new Array(HEIGHT).fill(new Array(WIDTH).fill(0))
    };
    draw(cwObj, ptr, 30, 60);
    step(cwObj.gMap);
    return cwObj;
}

function draw(cwObj, pattern, x = 0, y = 0) {
    if(pattern){//draw pattern to map
        pattern.map(function (cur, i){
            cwObj.gMap[x + i] = insert(cwObj.gMap[x + i], cur, y);
            //insert() is a helper, just inserts at an index
        });
    }
    var out = '';
    cwObj.gMap.map(function (cur) {     //create a string of active and
        cur.map(function (cell) {       //inactive cells
            if(cell) {out += "&#9632;";} else {out += "&#9632;";}
        });
        out += "
";
    });
    cwObj.canvas.innerHTML = out;  //put it in the HTML
}

function step (gm){
    return gm.map(function (cur, y) {
        return cur.map(function (cell, x){
            var n = getNb(gm, x, y);
            n = cell === 1 ? n - 1 : n;//getNb includes the cell itself
            return n === 3 ? 1 : ((n === 2 && cell === 1) ? 1 : 0);//rules
        });
    });
}

function getNb (gm, x, y){
    var w = WIDTH, h = HEIGHT,
        xmin = (x <= 0) ? 0 : x-1, ymin = (y <= 0) ? 0 : y-1,//handle borders
        xmax = (x+2 > w) ? w : x+2, ymax = (y+2 > h) ? h : y+2;

    var env = gm.slice(ymin, ymax).map(function (row){//get environment array
        return row.slice(xmin, xmax);
    });

    env = [].concat.apply([], env);//flatten array

    return env.reduce(function (prev, cell) {//sum the neighbors
        return prev += cell;
    });
}

var Game = init("screen");

setInterval(function (){//repeat the steps every 50ms
    Game.gMap = step(Game.gMap);
    draw(Game);
}, STEP);


texts:
I had to write my own iterator implementation for my structure which has ArrayList<Vector> field. An iterator is supposed to iterate over mentioned List. Any suggestions on improving it, or anything else?

public class ExamplesIterator implements Iterator<Vector> {

    private List<Vector> examples;  //ArrayList<Vector> will be set here
    private int          index;

    public ExamplesIterator(List<Vector> examples) {
        this.examples = examples;
        index = 0;
    }

    @Override
    public Vector next() {
        if(hasNext()) {
            return examples.get(index++);
        } else {
            throw new NoSuchElementException("There are no elements size = " + examples.size());
        }
    }

    @Override
    public boolean hasNext() {
        return !(examples.size() == index);
    }

    @Override
    public void remove() {
        if(index <= 0) {
            throw new IllegalStateException("You can't delete element before first next() method call");
        }
        examples.remove(--index);
    }
}


texts: Project Euler # 53 Combinatoric selections in Python

texts:
There are exactly ten ways of selecting three from five, 12345:

123, 124, 125, 134, 135, 145, 234, 235, 245, and 345

In combinatorics, we use the notation, 5C3=10.

In general, nCr = n! / r! (n−r)!, where r≤n, n! = n × (n−1) × ... × 3 × 2 × 1, and 0! = 1.

It is not until n = 23, that a value exceeds one-million: 23C10 = 1144066.

How many, not necessarily distinct, values of nCr for 1≤n≤100, are greater than one-million?

from time import time
from math import factorial

def combinations(n, r):
    """Assumes n, r a set of numbers and r number of numbers to choose from n.
    returns number of combinations."""
    return factorial(n) // (factorial(r) * factorial(n - r))

def generate_combinations(n_range, minimum):
    """generates non-distinct combinations in range n_range inclusive that exceed the minimum."""
    for n in range(1, n_range + 1):
        for r in range(1, n):
            combination = combinations(n, r)
            if combination > minimum:
                yield 1

if __name__ == '__main__':
    START_TIME = time()
    print(sum(generate_combinations(100, 10**6)))
    print(f'Time: {time() - START_TIME} seconds.')


texts: Advice on modelling with generics in Java

texts:
Use Case

The third party library that I am working with implements its data model in this fashion.

Interface
  - Implementation (24 different implementations)
     - Interface
         - Implementation (variable number of implementations)
              - etc...

Unfortunately, none of the interfaces have definitions for any of the common methods in the implementations... which has been interesting. As well, many of the implementations come in two flavours - required and optional. For whatever reason, this was not implemented as a flag, but as two separate classes.

This has lead to some interesting code, which I feel has some code smell it, but I'm not sure how to improve it.

Code

This code essentially fetches a deeply nested list of items buried inside this third party library. Oddly, all implementations will eventually produce this list of items all with the same bean. Since all implementations are essentially the same, I moved it an abstract class:

public abstract class AbstractAdapter<ChoiceClass, OptionalClass, RequiredClass, EntryBeanClass, BeanClass> {

    Class<ChoiceClass> choiceClass;
    Class<OptionalClass> optionalClass;
    Class<RequiredClass> requiredClass;
    Class<EntryBeanClass> entryBeanClass;
    Class<BeanClass> beanClass;

    {
        initializeClasses();
    }

    abstract void initializeClasses();
    abstract List<ChoiceClass> optionalToEntry(OptionalClass optional);
    abstract List<ChoiceClass> requiredToEntry(RequiredClass required);
    abstract BeanClass entryToBean(EntryBeanClass entry);

    List<BeanClass> getCcdBeans(MagicRequestBean requestBean) {
        List<Component3Choice> components = requestBean.getComponent();

        List<ChoiceClass> entries = Lists.newArrayList();
        for (Component3Choice component : components) {
            if (optionalClass.isInstance(component)) {
                entries = optionalToEntry(optionalClass.cast(component));
                break;
            }
            if (requiredClass.isInstance(component)) {
                entries = requiredToEntry(requiredClass.cast(component));
                break;
            }
        }

        return entries.stream()
                .filter(entryBeanClass::isInstance)
                .map(entryBeanClass::cast)
                .map(this::entryToBean)
                .collect(Collectors.toList());
    }
}

Questions

Is there a cleaner solution to model this adapter?

Any other advice to improve this code would be appreciated.


texts:
So I got kind of a weird format returned from the api I'm calling it's the following:
[
    [
        1609065000000,
        "22739.71000000",
        "22795.73000000",
        "22700.39000000",
        "22779.08000000",
        "38.81782800",
        1609065899999,
        "883167.94526884",
        2261,
        "18.58965200",
        "423036.58181400",
        "0"
    ]
]

    public static class StringExtensions
    {
        public static IEnumerable<Candlestick> ToCandleStickList(this string jsonObject)
        {
            var candleStickList = new List<Candlestick>();
            var list = JsonConvert.DeserializeObject<List<object[]>>(jsonObject);
            foreach (var obj in list)
            {
                candleStickList.Add(new Candlestick
                {
                    OpenTime = (long)obj[0],
                    Open = double.Parse((string)obj[1]),
                    High = double.Parse((string)obj[2]),
                    Low = double.Parse((string)obj[3]),
                    Close = double.Parse((string)obj[4]),
                    Volume = double.Parse((string)obj[5]),
                    CloseTime = (long)obj[6],
                    QuoteAssetVolume = double.Parse((string)obj[7]),
                    NumberOfTrades = (long)obj[8],
                    TakerBuyBaseAssetVolume = double.Parse((string)obj[9]),
                    TakerBuyQuoteAssetVolume = double.Parse((string)obj[10])
                });
            }

            return candleStickList;
        }
    }

    public class Candlestick
    {
        public long OpenTime { get; set; }
        public double Open { get; set; }
        public double High { get; set; }
        public double Low { get; set; }
        public double Close { get; set; }
        public double Volume { get; set; }
        public long CloseTime { get; set; }
        public double QuoteAssetVolume { get; set; }
        public long NumberOfTrades { get; set; }
        public double TakerBuyBaseAssetVolume { get; set; }
        public double TakerBuyQuoteAssetVolume { get; set; }
    }

I use the static method as follows
public async Task<IEnumerable<Candlestick>> GetCandleSticks(string symbol, string interval)
        {
            var endpoint = $"api/v3/klines?symbol={symbol}&interval={interval}";
            var response = await _httpClient.GetAsync(endpoint);

            if (response.IsSuccessStatusCode)
            {
                var result = (await response.Content.ReadAsStringAsync()).ToCandleStickList();

                return result;
            }

            throw new Exception($"");
        }

Does anyone got any suggestions for better code? Thanks in advance!


texts: Pick the best combination of n choose k models

texts:
Algorithm

  Let \$M_0\$ denote the null model which contains no predictors. This model simply predicts the sample mean of each observation.

  For \$k=1,2,\ldots,n\$:

  Fit all \$n \choose k\$ models that contain exactly \$k\$ predictors.
  Pick the best among these \$n \choose \$ models, and call it \$M_k\$. Here the best is defined as having the smallest RSS or equivalent measure.

  Select the single best model among \$M_0,M_1,\ldots,M_n\$ using cross validated prediction error, \$C_p\$, BIC, \$R^2_{\mathit{adj}}\$ or any other method.

I looked up a tutorial and created a function based upon its script. It's essentially used so I can select dependent variables that's a subset of a data frame. It runs but it is very very slow.

How would I flatten a nested for-loop such as this?

# Loop over all possible combinations of k features
for k in range(1, len(X.columns) + 1):
       # Looping over all possible combinations: from 11 choose k
       for combo in itertools.combinations(X.columns,k):
           # Store temporary results
           temp_results = fit_linear_reg(X[list(combo)],Y)

           # Append RSS to RSS Lists
           RSS_list.append(temp_results[0])

I tried implementing an enumerate version but it did not work. I'm not sure, how I can flatten the nested for loop, such that I can append the results of a function to a list.

# This function takes in a subset of a dataframe representing independent
# variables (X) and a column for dependent variable (Y). This function fits
# separate models for each possible combination of the k predictors (which is
# based on the column length of X) and then select the best subset. The
# resulting output is a dataframe.

def BestSubsetSelection(X,Y):
    # number of predictors
    k = len(X.columns)
    # Store the RSS from a linear regression model
    RSS_list = []
    # Store the R-square from a linear regression model
    R_squared_list = []
    # Store the features for a given iteration.
    feature_list = []
    # Store the number of features used for a given iteration. This corresponds with the feature_list.
    numb_features = []

    # Loop over all possible combinations of k features
    for k in range(1, len(X.columns) + 1):
            # Looping over all possible combinations: from 11 choose k
            for combo in itertools.combinations(X.columns,k):
                # Store temporary results
                temp_results = fit_linear_reg(X[list(combo)],Y)

                # Append RSS to RSS Lists
                RSS_list.append(temp_results[0])

                # Append R-Squared TO R-Squared list
                R_squared_list.append(temp_results[1])

                # Append Feature/s to Feature list
                feature_list.append(combo)

                # Append the number of features to the number of features list
                numb_features.append(len(combo))

    df = pd.DataFrame({
        'No_of_Features': numb_features,
        'RSS' : RSS_list,
        'R-Squared' : R_squared_list,
        'Features' : feature_list
    })

    # Finding the Best Subsets for each number of features

    # The smallest RSS
    df_min = df[df.groupby('No_of_Features')['RSS'].transform(min) == df['RSS']]
    # The Largest R-Squared Value
    df_max = df[df.groupby('No_of_Features')['R-Squared'].transform(min) == df['R-Squared']]
    display(df_min)
    display(df_max)

    # Adding columns to the dataframe with RSS and R-Squared values of the best subset
    df['min_RSS'] = df.groupby('No_of_Features')['RSS'].transform(min)
    df['max_R_Squared'] = df.groupby('No_of_Features')['R-Squared'].transform(max)

This code is taken from my IPython notebook.


texts:
As you know, converting an int to an enum is straightforward. Doing it generically with type/range checking isn't. I looked for a reusable example since this seems like a common situation but did not find a suitable one. If it exists, please let me know. Below is a C# extension method that encapsulates this behavior. Any feedback is welcome.

public static T ToEnum<T>(this int value)
{
    Type type = typeof(T);

    if (!type.IsEnum)
    {
        throw new ArgumentException($"{type} is not an enum.");
    }

    if (!type.IsEnumDefined(value))
    {
        throw new ArgumentException($"{value} is not a valid ordinal of type {type}.");
    }

    return (T)Enum.ToObject(type, value);
}


texts: c# Converting from one object to another without using foreach

texts:
I am return an student object from my database and I want to convert it into a StudentRecoredRequest model. The way i have implement is shown below. I was wondering if there was a nicer way to convert from the student object to studentsystemrecordrequest. Thanks
        var result = await _context.Student.ToListAsync();
        var studentInfo = new List<StudentSystemRecordRequest>();
        foreach(var student in result)
        {
            var stud = new StudentSystemRecordRequest
            {
                FirstName = student.FirstName,
                LastName = student.SurName,
                DateOfBirth = student.DateOfBirth,
                Address = student.Address1
            };
            studentInfo.Add(stud);
        }


texts:
The SPOJ problem:

  Given a 40 character string representing outcomes of 40 coin tosses,
  find the frequency destribution of all the possible outcome triplets.
  So, for string like : HHHH....40 Hs ,the result is HHH : 38 and the
  rest 0. The exact input output format is given in the link.

My approach, as is clear from the code, is to iterate through the string and match all consecutive sub-strings of length 3, while increasing the frequency count.

My solution got accepted, but I am not really happy with what I have done here. As you can see, there is a lot of redundant code I could not remove.

For instance, if string "TTT" could be directly mapped to the macro TTT, somehow, and so on, a large number of lines of code could have been reduced. I know technically strings and macros are two different things, but is there some trick that I am missing?

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<limits.h>
#define TTT 0
#define TTH 1
#define THT 2
#define THH 3
#define HTT 4
#define HTH 5
#define HHT 6
#define HHH 7
void getCount(char str[] , int count[]){
    int i;
    for(i=0;i<8;++i)
        count[i]=0;

    int l = strlen(str);
    for(i=2;i<l;++i){
        if(strncmp(str+i-2 , "TTT" , 3)==0)
            ++count[TTT];
        if(strncmp(str+i-2 , "TTH" , 3)==0)
            ++count[TTH];
        if(strncmp(str+i-2 , "THT" , 3)==0)
            ++count[THT];
        if(strncmp(str+i-2 , "THH" , 3)==0)
            ++count[THH];
        if(strncmp(str+i-2 , "HTT" , 3)==0)
            ++count[HTT];
        if(strncmp(str+i-2 , "HTH" , 3)==0)
            ++count[HTH];
        if(strncmp(str+i-2 , "HHT" , 3)==0)
            ++count[HHT];
        if(strncmp(str+i-2 , "HHH" , 3)==0)
            ++count[HHH];
    }
}
int main()
{
    char str[41];
    int t,n,count[8],i;
    scanf("%d",&t);
    while(t--){
        scanf("%d",&n);
        printf("%d ",n);

        scanf("%s",str);
        getCount(str,count);

        for(i=0;i<8;++i){
            printf("%d ",count[i]);
        }
        printf("\n");
    }
    return 0;
}


texts: Extracting specific rows and columns from a CSV file

texts:
I have written a function to selectively extract data from a file.
I want to be able to extract only from a certain line and only given rows.

Would convert this function into a generator improve the overhead when I need to process large files?

import itertools
import csv

def data_extraction(filename,start_line,lenght,span_start,span_end):
    with open(filename, "r") as myfile:
        file_= csv.reader(myfile, delimiter=' ')  #extracts data from .txt as lines
        return (x for x in [filter(lambda a: a != '', row[span_start:span_end]) \
        for row in itertools.islice(file_, start_line, lenght)])


texts:
Is there a way to speed up the Linq.Any check or perform the check in another way to enhance performance.

I have a mastercodes table that records unique codes for a campaign.  The code below will create new codes for a campaign but checks the mastercode table to make sure that it doesn;t already exist. Once the codes have been created and added to the mastercodes table it creates an excel file for download.

The main issue is that a campaign can have 400k codes and we have several campaigns running at once. So the mastercode table can get into the millions of records. When I request 300 new codes and run the below process without the .Any() check it takes 1-2 seconds in production. However when i add the check the process times out with the "no response to user" timeout error.

I'm using the Z.EntityFrameworrk.Extensions and the post to the table happens pretty much instantly.  But is there a way to code the perform the mastercode check that doesn't have a huge performance issue.

The Model

public class MasterCode
{
    public int MasterCodeId { get; set; }
    public int CampaignId { get; set; }
    public string CampaignCode { get; set; }
    public string Code { get; set; }
    public bool Used { get; set; }
    public DateTime SubmittedOn { get; set; }
}

The code

public static void GenerateMasterCodes(GenerateMasterCode model)
{
    using (ApplicationDbContext _context = new ApplicationDbContext())
    {
        Campaign campaign = _context.Campaigns.Find(model.CampaignId);

        List<MasterCode> masterCodes = new List<MasterCode>();
        for (var i = 1; i <= model.Count; i++)
        {
            var masterCode = new MasterCode
            {
                CampaignId = campaign.CampaignId,
                CampaignCode = campaign.CampaignCode,
                Used = false,
                SubmittedOn = DateTime.Now
            };

            // Ensure that no code already exists for that campaign.
            var code = GenerateMasterCode(model.StartString, model.CodeLength);
            while (_context.MasterCodes.Any(m => m.Code == code && m.CampaignCode == campaign.CampaignCode))
            {
                code = GenerateMasterCode(model.StartString, model.CodeLength);
            }
            masterCode.Code = code;

            masterCodes.Add(masterCode);
        }

        try
        {
            _context.MasterCodes.AddRange(masterCodes);
            _context.BulkSaveChanges();
        }
        catch (Exception ex)
        {
            ...
        }
    }
}

The Code generator

public static string GenerateMasterCode(string startString, int mastercodeLength)
{
    string numericChars = "X123456789";

    char[] chars = new char[mastercodeLength];
    Random rd = new Random();

    for (int i = 0; i < mastercodeLength; i++)
    {
        if (!string.IsNullOrEmpty(startString) && i < startString.Length)
        {
            chars[i] = Char.Parse(startString.Substring(i, 1));
        }
        else
        {
            chars[i] = numericChars[rd.Next(0, numericChars.Length)];
        }
    }

    return new string(chars);
}


texts:
public boolean connectedOnGameServer = false;
public final Object conGameServerMonitor = new Object();

public void connectedToGameServer() {
    synchronized (conGameServerMonitor) {
        if (connectedOnGameServer != false)
            throw new RuntimeException("Player connected twice");
        connectedOnGameServer = true;
        conGameServerMonitor.notifyAll();
    }
}

public void waitForGameServerConnection() {
    synchronized (conGameServerMonitor) {
        try {
            long startTime = System.currentTimeMillis();
            long waited = 0;
            while (!connectedOnGameServer && waited < GAMESERVER_CONNECT_TIMEOUT) {
                conGameServerMonitor.wait(GAMESERVER_CONNECT_TIMEOUT - waited);
                waited = System.currentTimeMillis() - startTime;
            }
            if (waited > GAMESERVER_CONNECT_TIMEOUT && connectedOnGameServer) {
                throw new RuntimeException("Client didn't connect to game server in time (" + GAMESERVER_CONNECT_TIMEOUT + " ms)");
            }
        } catch (InterruptedException e) {
            throw new RuntimeException("Interrupted while waiting for client to connect to game server", e);
        }
    }
}

What I need is:

Thread A calls waitForGameServerConnection
Thread B calls connectedToGameServer
Thread A continues


texts: Better code for error handling in NodeJs and Express

texts:
I have this code for a post request, when the user wants to change his password. Because of all the cases and the following page renders the code came out really ugly. Is there a better way to structure this? (It works fine and does what I want.)

// Check if old password is correct
    SQL.getUserFromDB(request.session.username).then(function (results) {
        // Hash and compare with stored hash
        bcrypt.compare(request.body.oldPw, results[0].password, function (error, result) {
            // Log possible error
            if (error) console.log(error);
            if (result === true) {
                // Check if new passwords are both the same
                if (request.body.newPw === request.body.newPw2) {
                    // Call mysql function
                    SQL.changeUserPassword(request.session.username, request.body.newPw).then(function () {
                        response.render('pages/changePassword', {
                            user: request.session.username,
                            text: 'Passwort erfolgreich geändert.'
                        });
                    }).catch(function (error) {
                        console.log(error);
                        if (error == 'pw') {
                            response.render('pages/changePassword', {
                                user: request.session.username,
                                text: 'Neues Passwort zu unsicher.'
                            });
                        } else {
                            // Render error page
                            response.render('pages/changePassword', {
                                user: request.session.username,
                                text: 'Fehler beim Ändern des Passworts.'
                            });
                        }
                    });
                } else {
                    // Render error page
                    response.render('pages/changePassword', {
                        user: request.session.username,
                        text: 'Neue Passwörter stimmen nicht überein!'
                    });
                }
            } else {
                // Render error page
                response.render('pages/changePassword', {
                    user: request.session.username,
                    text: 'Altes Passwort stimmt nicht überein!'
                });
            }
        });
        // Catch sql errorsFehler beim Ändern des Passworts
    }).catch(function (error) {
        if (error) console.log(error);
        response.render('pages/errors/loginFailed');
    });

I tried just setting the text in the different cases and rendering one page with the text at the bottom, this didn't work however.


texts: Selecting multiple filters based on the true/false conditions

texts:
I wrote a method to select the filters (two or more) based on the true/false conditions. Here is the method I used for selecting the multiple filters:

    public T SetPropertyTypes<T>(bool residential, bool commercial) where T : IPage, new()
{

    // Residential Property Type Check logic
    if (residential && (ElementIsNotActive(() => FindElement(By.CssSelector(propertyTypeResidentialCss))).Invoke(Driver)))
        ClickButton(() => FindElement(By.CssSelector(propertyTypeResidentialCss)), "Residential");
    else if (ElementIsActive(() => FindElement(By.CssSelector(propertyTypeResidentialCss))).Invoke(Driver))
        ClickButton(() => FindElement(By.CssSelector(propertyTypeResidentialCss)), "Residential");

    // Commercial Property Type Check logic
    if (commercial && (ElementIsNotActive(() => FindElement(By.CssSelector(propertyTypeCommercialCss))).Invoke(Driver)))
        ClickButton(() => FindElement(By.CssSelector(propertyTypeCommercialCss)), "Commercial");
    else if (ElementIsActive(() => FindElement(By.CssSelector(propertyTypeCommercialCss))).Invoke(Driver))
        ClickButton(() => FindElement(By.CssSelector(propertyTypeCommercialCss)), "Commercial");
}

Later I found that the code is redundant and it could be better if I make it simpler and non-ambiguous. I'm new to C# and am not aware of many features. Is there any way to refactor this using any features of C#? I tried checking the variables using if-else-if but that's not working as intended.


texts:
I've recently discovered the power of sed; regular expressions seem like they'll take a lifetime to master. This tiny script uses both to add a zero before the single digit in file names.

Can this be done more easily without sed? Is the regex sound?

#!/bin/bash

# > addzero.sh <
# Adds a zero before the single digit in file names separated by an underscore.
# Designed to help keep files in sequence in directory listings. Otherwise, you get listings like
# "_0.txt, _1.txt, _10.txt, _11.txt, _12.txt, ..., _2.txt, _20.txt, _21.txt, _22.txt, ..."

for filename in $(ls -1 ./*); do
  if [[ $filename =~ _[0-9]\. ]]; then
    new_filename=$(echo $filename | sed -n 's/_\([0-9]\)\./_0\1\./p')
    mv $filename $new_filename
  fi
done


texts: Using statement in context of streams and WebClients

texts:
Mostly a question on which approach would be better and when utilizing the using keyword, would it still be neccesary to close streams programatically. If an object implements IDisposable should using always be used?

Link to my full answer using this sample: Stackoverflow Answer

Option 1:

WebClient webClient;
webClient = new WebClient();
string json = webClient.DownloadString(@"urlToTheJsonResponse");

MemoryStream stream = new MemoryStream((Encoding.UTF8.GetBytes(json)));
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(GISData));
stream.Position = 0;
GISData data = (GISData)ser.ReadObject(stream);
stream.Close();

Option 2:

WebClient webClient;
MemoryStream stream;
string json;
GISData data;

using (webClient = new WebClient())
{
    json = webClient.DownloadString(@"urlToTheJsonResponse");
}

using (stream = new MemoryStream((Encoding.UTF8.GetBytes(json))))
{
    DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(GISData));
    data = (GISData)ser.ReadObject(stream);
    stream.Close();
}

using (webClient = new WebClient())
{
    webClient.DownloadFile(data.href, "C:/" + data.href.Substring(data.href.LastIndexOf("/") + 1));
}


texts: Wiki Link Mapper — A webcrawler which crawls links recursively and prints them into a graph

texts:
I would like some suggestions on how to make it better and also if any features that i should add to this Script. I am using beautifulsoup,requests for scraping and networkx for plotting the graph.

https://github.com/HardikM1999/WikiLinkMapper

import requests
from bs4 import BeautifulSoup
import sys
import networkx as nx
import matplotlib.pyplot as plt

#Taking Arguments
#Starting string
start = sys.argv[1]

#No of repetitions
rep = int(sys.argv[2])
tot_list = []

#Creating graph
G = nx.Graph()
G.add_node(start)

#recur function to scrape links
def recur(url,depth,tot_list,parent,rep):
    if(depth<=rep):
        page = requests.get('https://www.wikipedia.org/wiki/' + url)
        #parsing the page
        soup = BeautifulSoup(page.text,'html.parser')
        cnt = 0
        #list for particular depth
        depth_list = []
        for para_tag in soup.select('p'):
            for anchor_tag in para_tag.select('a'):
                if cnt>rep:
                    break
                #getting the link
                check_string = anchor_tag['href']
                if check_string.startswith('#cite') == False and check_string.startswith('/wiki/Help') == False and check_string.startswith('/wiki///en:') == False and check_string.startswith('/wiki/Wikipedia') == False :
                    cnt = cnt + 1
                    depth_list.append(check_string[6:])
            if cnt>rep:
                break
        for link in depth_list:
            tot_list.append((link,parent))
            recur(link,depth+1,tot_list,link,rep)
    return tot_list

tot_list = recur(start,0,tot_list,start,rep)
node_sizes = []
node_sizes.append(100*len(start))

#Adding tot_list to the graph
for a,b in tot_list:
    G.add_node(a)
    G.add_edge(a,b)
    node_sizes.append(100*len(a))

#Drawing the Graph
nx.draw(G,node_color = 'orange',node_size = node_sizes,with_labels = True)
plt.draw()
plt.show()


texts: PDO Is this registration secure and well coded?

texts:
i finally have been moved to PDO (from MySQLi) and i m now trying to make simple login and registration page (for training purposes).

This code does work! But i want to know if it is secure?

Also witch way is better for prepared statements to pass values with ? or :username?
Is the way i use PDO is simple or should i change something?

// Define variables and initialize with empty values
$username = $password = $confirm_password = "";
$username_err = $password_err = $confirm_password_err = "";

// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){

    // Validate username
    if(empty(trim($_POST["username"]))){
        $username_err = "Please enter a username.";
    } else{
        // Prepare a select statement
        $sql = "SELECT id FROM users WHERE username = :username";

        if($stmt = $pdo->prepare($sql)){
            // Bind variables to the prepared statement as parameters
            $stmt->bindParam(":username", $param_username, PDO::PARAM_STR);

            // Set parameters
            $param_username = trim($_POST["username"]);

            // Attempt to execute the prepared statement
            if($stmt->execute()){
                if($stmt->rowCount() == 1){
                    $username_err = "This username is already taken.";
                } else{
                    $username = trim($_POST["username"]);
                    $email = trim($_POST["email"]);
                }
            } else{
                echo "Oops! Something went wrong. Please try again later.";
            }
        }

        // Close statement
        unset($stmt);
    }

    // Validate password
    if(empty(trim($_POST["password"]))){
        $password_err = "Please enter a password.";
    } elseif(strlen(trim($_POST["password"])) < 6){
        $password_err = "Password must have atleast 6 characters.";
    } else{
        $password = trim($_POST["password"]);
    }

    // Validate confirm password
    if(empty(trim($_POST["confirm_password"]))){
        $confirm_password_err = "Please confirm password.";
    } else{
        $confirm_password = trim($_POST["confirm_password"]);
        if(empty($password_err) && ($password != $confirm_password)){
            $confirm_password_err = "Password did not match.";
        }
    }

    // Check input errors before inserting in database
    if(empty($username_err) && empty($password_err) && empty($confirm_password_err)){

        // Prepare an insert statement
        $sql = "INSERT INTO users (username, email,  password) VALUES (:username, :email, :password)";

        if($stmt = $pdo->prepare($sql)){
            // Bind variables to the prepared statement as parameters
            $stmt->bindParam(":username", $param_username, PDO::PARAM_STR);
            $stmt->bindParam(":email", $param_email, PDO::PARAM_STR);
            $stmt->bindParam(":password", $param_password, PDO::PARAM_STR);

            // Set parameters
            $param_username = $username;
            $param_email = $email;
            $param_password = password_hash($password, PASSWORD_DEFAULT); // Creates a password hash

            // Attempt to execute the prepared statement
            if($stmt->execute()){
                // Redirect to login page
                header("location: login");
                die();
            } else{
                echo "Something went wrong. Please try again later.";
            }
        }

        // Close statement
        unset($stmt);
    }

    // Close connection
    unset($pdo);
}

Thanks in advance!


texts:
I am trying to write a python function which retries a given function until given time or function returns True with given delay.

I have written the following function, but was thinking if there is a better way to do it?

Example function I want to retry for

def is_user_exist(username):

    try:
        pwd.getpwnam(username)
        log.info("User %s exist" % username)
        return True
    except KeyError:
        log.exception("User %s does not exist." % username)
        return False

My retry function

def retry(func, *func_args, **kwargs):
    retry_count = kwargs.get("retry_count", 5)
    delay = kwargs.get("delay", 5)
    while retry_count > 1:
        if func(*func_args):
            return
        log.debug("waiting for %s seconds before retyring again")
        sleep(delay)
        retry_count = retry_count - 1

    return func(*func_args)


texts:
Google's Guava library has a great RateLimiter, but I also needed a way to limit on an irregular basis, such as if an API I'm using has been throttled.  I basically built a wrapper around Guava's RateLimiter, only using the simple acquire() method from it.

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import com.google.common.util.concurrent.RateLimiter;

public class CustomLimiter {
    private RateLimiter guavaLimiter;
    private Throttle apiThrottle = new Throttle();

    public CustomLimiter() {
        this.guavaLimiter = RateLimiter.create(.8);
    }

    public double acquire() {
        try {
            apiThrottle.waitChoke();
        } catch (Exception e) {
            throw new IllegalStateException("Someone else handle this");
        }
        return guavaLimiter.acquire();
    }

    public void rateLimitNotify() {
        apiThrottle.startChoke();
    }

    class Throttle {
        private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
        private ScheduledFuture future;

        public void startChoke() {
            future = executor.schedule(new EndThrottle(this), 5, TimeUnit.SECONDS);
        }

        public void waitChoke() throws InterruptedException, ExecutionException {
            if(future == null || future.isDone() || future.isCancelled())
                return;
            future.get();
        }
    }

    class EndThrottle implements Runnable {

        private Throttle throttle;
        @Override
        public void run() {
            System.out.println("I feel like I should be doing something with the throttle here");
        }

        public EndThrottle(Throttle throttle) {
            this.throttle = throttle;
        }
    }
}

Multiple threads will be using this limiter and the API, and they may each encounter throttles.  This allows each thread to encounter any throttle notification and tell the limiter, and it only keeps record of the most recently encountered one, since it will also be the last to expire.

Initially, I thought I would need to synchronize everywhere, but in the end, I didn't use any.  Is this code still usable from multiple threads?

As a side question- ScheduledExecutorService seemed like the best way to delay without forcing a block unless something needs to wait, but it asks for a Runnable, which I don't seem to really utilize.  Is this poor design?