Game on numeric arrays Two participants, A and B, are playing the following game:

The initial set of games is a sequence of zeroes and ones.
A and B
change turns, and participant A always moves first.
During each
turn, a player removes one element from the sequence that satisfies
the following:
It is not the first or last element.
It must be
surrounded by zeroes on both sides.
The first participant who can't take
their turn loses the game.
Both participants always move optimally.

Input Format

The first line contains an integer n, denoting the number of games. The subsequent lines describe each game in the following format:

The first line before the sequence contains a single integer denoting the length of the sequence.
The second line contains the sequence, i.e. a space-separated integers denoting the respective values of the initial sequence. Each element is either zero or one.

Sample input

8
61
1 0 1 1 0 1 0 1 1 0 1 1 0 0 1 0 1 0 0 1 0 1 0 1 0 0 0 1 1 0 1 0 1 1 0 1 0 1 0 0 1 1 0 0 1 1 0 0 1 0 1 0 1 0 1 0 1 1 1 0 1
28
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
28
1 0 1 1 0 1 0 0 1 0 1 0 1 0 0 1 0 1 0 1 0 1 0 0 1 0 1 1
15
0 1 0 1 0 1 0 1 0 1 0 1 0 1 0
5
1 0 1 0 1
6
1 0 1 0 1 1
6
0 0 0 0 0 0
7
1 0 1 0 1 0 0

Sample Output

A
B
B
A
A
A
B
B

Graphical explanation for 5th and 7th sample inputs:

Number to be removed during each turn is marked in red.

My code:

 public class Solution {

 public enum Players {
              A { @Override public Players turn() {return B; }},
              B { @Override public Players turn() {return A; }},
              ;

    abstract public Players turn();
}

 public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int g = in.nextInt();
    Players winner = Players.B;

    for(int a0 = 0; a0 < g; a0++){
        int n = in.nextInt();
        Integer[] sequence = new Integer[n];
        for(int sequence_i=0; sequence_i < n; sequence_i++){
            sequence[sequence_i] = in.nextInt();
        }
        ArrayList<Integer> initial = new ArrayList<Integer>(Arrays.asList(sequence));
        Players current = Players.B;
        for (int i=0; i < initial.size()-1; i++) {
            if (i > 0 && initial.get(i-1) == 0 && initial.get(i+1) == 0) {
                current = current.turn();
                winner = current;
                initial.remove(i);
                i = 0;
            }
        }
    System.out.println(winner);
    }
    in.close();
   }
}

Is my code logically correct? The test data is hit but I doubt anyway...

for (int i=0; i < initial.size()-1; i++) {
            if (i > 0 && initial.get(i-1) == 0 && initial.get(i+1) == 0) {
                current = current.turn();
                winner = current;
                initial.remove(i);
                i = 0;
            }
        }

You don't need to do initial.size() - 1 on each iteration.  Consider

        for (int i = 2; i < initial.size(); i++) {
            if (initial.get(i) == 0 && initial.get(i - 2) == 0) {
                current = current.turn();
                initial.remove(i - 1);
                i = 1;
            }
        }

This starts with the third element.  If it's not a 0, then there is no reason to check other values.  No math needed.  If it is a 0, then it verifies that the element two places prior is a 0.  Only then does it proceed to processing.

Note that setting i to 1 means that it will be 2 again for the next iteration.  There were actually offsetting mistakes in the original code that made it work.  You don't need i to ever be 0, so setting i to 0 and then incrementing to 1 worked.


Idea of 'parser' to make the writing of asynchronous functions chains easier Why this thing :

I work on a project where I need to call many asynchronous functions to get data, chain them, execute them if conditions are met,.. and I ended up having unreadable code.
At some point, I looked at promises library like Q.js but even with such tools my code was complicated, so I decided to write something which would make my cases of use simple to read.

 Code + what it does :

The whole concept is to help someone generate the code for the asynchronous calls as a string and then call eval() to run it (the latter probably being a major case of evil programming).  At the moment, it has only two functions because I am not sure how good this idea is.

First function : chain
This functions chains two asynchronous calls, optionally with a condition on the result of the first asynchronous call.

pp_chain_function = function (fname,condition_string) {
var queue=this;
var prec_result = 'result_'+queue.queue_length;
queue.queue_string += !condition_string ? '.then(function(){return '+fname+'();})'
        :'.then(function('+prec_result+'){if('+prec_result+condition_string+'){return '+fname+'();}return $.when();})';
queue.length++;

return queue;
};

Second function : fail  Adds fail handler for the whole queue.

pp_fail_function = function(fname) {
    var queue = this;
    queue.queue_string += '.fail(function(error){return '+fname+'(error);})';
    return queue;
};

Global queue prototype :

queue_object = {
        pp_chain : pp_chain_function,
        pp_fail : pp_fail_function
        };

Initializing the queue :

pp_begin = function(){
    var pp_queue = Object.create(queue_object);
    pp_queue.queue_string='$.when()';
    pp_queue.queue_length=0;
    console.warn(pp_queue);
    return pp_queue;
};

 Usage case :

var chain = pp_begin(); //init the chain
    chain.pp_chain('async_0').pp_chain('async_1');  //add two standard async functions
    if(condition two){chain.pp_chain('async_2','.length>0');} //if external conditions and async_1 gave a result with length>0, execute async_2
    chain.pp_fail('fail_handler');  //add fail handler
    console.warn(chain);  //replace with eval if you want to actually run it

I would love some feedback on that idea mainly, and on the code if applicable (even if there is very few).

EDIT : jsfiddle for up-to-date version

 Concrete example :

Before :

 if (online_mode && i_s_r) { //if sync clear collections and reload them
            access.findAll()
                .then(function (result) {
                    if (result.length > 0) {
                        access.remove(result, {
                                push: false
                            })
                            .then(function () {
                                access.load()
                                    .then(function () {
                                        callback_function(i, true);
                                    });
                            });
                    } else {
                        access.load()
                            .then(function () {
                                callback_function(i, true);
                            });
                    };
                })
                .fail(function (errorObject) {
                    alert(errorObject);
                });
        } else {
            callback_function(i, true);

After :

var q0 = begin();
        if(online_mode && i_s_r){q0.chain('access.findAll()').chain('access.remove(result_1,{push: false})','.length>0').chain('access.load()').failure('alert');}
        q0.chain_sync('callback_function(i,true)');
        eval(q0.queue_string);

Interesting question,

I find this code hard to read, I wonder what you consider unreadable code.

Some remarks on

pp_chain_function = function (fname,condition_string) {
var queue=this;
var prec_result = 'result_'+queue.queue_length;
queue.queue_string += !condition_string ? '.then(function(){return '+fname+'();})'
        :'.then(function('+prec_result+'){if('+prec_result+condition_string+'){return '+fname+'();}return $.when();})';
queue.length++;

return queue;
};

Use jsbeautifier.org, always
Prefixing with pp makes no good sense
Postfixing with _string makes little sense
prec_result <- What does prec stand for
var queue=this;, you only need to re-assign this if you work with closures
Consider a templating function for your string building
That long ternary statements looks horrendous, consider splitting it over multiple lines

Some remarks on

queue_object = {
    pp_chain : pp_chain_function,
    pp_fail : pp_fail_function
};

You use queue_object as a prototype, consider changing the name to reflect, also, JavaScript ought to be written in lowerCamelCase: queue_object -> queueObject -> queuePrototype

Some remarks on

var chain = pp_begin(); //init the chain
    chain.pp_chain('async_0').pp_chain('async_1');  //add two standard async functions
    if(condition two){chain.pp_chain('async_2','.length>0');} //if external conditions and async_1 gave a result with length>0, execute async_2
    chain.pp_fail('fail_handler');  //add fail handler
    console.warn(chain);  //replace with eval if you want to actually run it

Indenting is messed up
You are putting conditions in strings..
I am fairly certain that either by making async_1 fail if length < 1 or putting your check inside async_2 you could replace this with

$.when( async_0, async_1 )
  .then( async_2, fail_handler );

The biggest elephant in the room is of course eval, you loose proper stack-traces, debugging, tooling ( jshint, jsbeautifier ), and open yourself up to all kinds of pain. I would suggest that you post one of your unreadable scripts, perhaps we can show you how to use Q so that they become readable without resorting to .. this.


Strings: Making Anagrams Problem Statement

Input Format

The first line contains a single string, a. The second line contains a single string, b.

Constraints

1<= |a|,|b| <= 10^4

It is guaranteed that and consist of lowercase English alphabetic letters (i.e., through ). Output Format

Print a single integer denoting the number of characters you must delete to make the two strings anagrams of each other.

Sample Input

cde

abc

Sample Output

4

Explanation

We delete the following characters from our two strings to turn them into anagrams of each other:

Remove d and e from cde to get c. Remove a and b from abc to get c. We must delete characters to make both strings anagrams, so we print on a new line.

Solution

public class Solution {
public static int numberNeeded(String first, String second) {

    StringBuilder firstBuilder = new StringBuilder(first);
    StringBuilder secondBuilder = new StringBuilder(second);
    int numberNeeded = firstBuilder.length() + secondBuilder.length();

    for (int i=0; i<first.length(); i++) {

        char currentChar = first.charAt(i);

        for (int j=0; j<secondBuilder.length(); j++) {
            char charToCompare = secondBuilder.charAt(j);

            if (charToCompare == currentChar) {
                firstBuilder.deleteCharAt(0);
                secondBuilder.deleteCharAt(j);
                numberNeeded -= 2;
                break;
            }
        }
    }

    return numberNeeded;

}

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    String firstArray = in.next();
    String secondArray = in.next();
    System.out.println(numberNeeded(firstArray, secondArray));
}
}

Can I please get feedback on my code and also on my solution approach? Also, can someone guide me about the time and space complexity of this solution? How do we calculate it and how can I make it better?

Thanks in advance

The time complexity is \$O(NM)\$ where \$N,M\$ are lengths of the strings. Surely is is too much. The solution can be reached in \$O(N+M)\$. In pseudocode:

    build a character histogram from the first string
    build a character histogram from the second string
    for each c in alphabet,
        result += max(hist1[c], hist2[c]) - min(hist1[c], hist2[c])


Multiple drop down validation I have written some jQuery which validates a group of drop downs.  It checks the text value selected in all the drop downs (first three characters), and if there is a duplicate, it warns the user.

This code seems quite messy, I was wondering if anyone would like to attempt to refactor this.  Tips for improvement are welcome.

Here is the link to the Fiddle.

My main function:

          function validateTeam(section) {
          //array for storing selected nationalities:
          var $selectionArr = [];

          $('#' + section + '> .form-group select').each(function () {

              //strip the selected text:
              var $optText = $(this).find('option:selected').text().substr(0, 3);

              if ($optText.length == 3) {
                  $selectionArr.push($optText);
              }
          });

          //unique array of nationalities:
          var result = [];

          $.each($selectionArr, function (index, value) {
              if ($.inArray(value, result) == -1) {
                  result.push(value);

                  if (result.length == 5) {
                      $('#warning').removeClass('label-danger').addClass('label-success').text('Thank you - your selection is valid!');
                  } else {
                      $('#warning').text('');
                  }

              } else {
                  //console.log(value);
                  $('#warning').addClass('label-danger').text('Warning! You have selected more than one players from the same nation (' + value + ')');
              }
          });
      };

You didn't incude it in your post, but I'm comment on it anyway: The way you assign the validator function to your select elements isn't very optimal:

      $('#MainContent_ddOpenBrd1').change(function () {
          validateTeam('openSelect');
      });
      $('#MainContent_ddOpenBrd2').change(function () {
          validateTeam('openSelect');
      });
      $('#MainContent_ddOpenBrd3').change(function () {
          validateTeam('openSelect');
      });
      $('#MainContent_ddOpenBrd4').change(function () {
          validateTeam('openSelect');
      });
      $('#MainContent_ddOpenBrd5').change(function () {
          validateTeam('openSelect');
      });

You've got five calls all doing the same thing. You should at least combine them into one:

      $('#MainContent_ddOpenBrd1, #MainContent_ddOpenBrd2, #MainContent_ddOpenBrd3, #MainContent_ddOpenBrd4, #MainContent_ddOpenBrd5').change(function () {
          validateTeam('openSelect');
      });

Even better would be to select them with a more optimal selector such as a common class, or in this case a desendent selector:

      $('#openSelect select').change(function () {
          validateTeam('openSelect');
      });

This assigns the handler to each elements separately. You can go yet another step and use a delegated event handler, so that in the end you'll have a single handler assigned to a single element:

      $('#openSelect').on('change', 'select', function () {
          validateTeam('openSelect');
      });

And now you can get rid of the hard-coded ID as the parameter for your function:

      $('#openSelect').on('change', 'select', function (event) {
          validateTeam(event.delegateTarget.id);
      });

So, if you have multiple independent groups you can assign them all with one call - even if you don't reference them by their IDs, but for example a class:

      $('.select-group').on('change', 'select', function (event) {
          validateTeam(event.delegateTarget.id);
      });

Speaking of the function parameter: Instead of passing the ID you should directly pass a reference to that element - and with the change from above it's simple:

      $('#openSelect').on('change', 'select', function (event) {
          validateTeam(event.delegateTarget);
      });

So the start of your function changes to:

      $(section).find('> .form-group select').each(function () {

A short point about your variable names: You should only use $ as a prefix if the variable contains a reference to a jQuery object. Neither $selectionArr nor $optText do that. Also $selectionArr is a bad name. Something like selectedCountries would be better.

One impracticable thing you are doing, is reading/parsing the country abbreviation from the display label of the option. Generally trying to get information from a text that is intended for the user to read is a bad thing, since it can change at any time, e.g.

the abbreviation is moved to the end of the string
the full name of the country should be displayed
the abbreviation/name is replaced with an icon
etc.

Any of those events requires you to change your validation function.

Instead you should store such important information independently from the display string, for example in a data-* attribute:

<option value="11700599" data-country="AFG">AFG Farazi Khaiber (2134)</option>

and get it from there:

      var country = $(this).find('option:selected').data('country');

      if (country) { // No need to check the length, just if the value is set at all
        $selectionArr.push(country);
      }

You can also optimize the reading of the countries, for one by directly selecting the options in the "outer" selector (and also limiting it to ones that actually have a data-country attribute), and for another by usings jQuery's .map() function to convert the list of options directly into a list of strings:

         var $selectionArr = $(section).find('> .form-group option[data-country]:selected').map(function () {
           return $(this).data('country');
         });

That's all for now. If I have time I'll come back later.

EDIT: Some more:

Now to the validation loop:

You can optimize the checking of duplicates by using an object like a set instead of an array. That saves you having to search the array, but however requires you to count the number of entries yourself.

You should also also move the updating of the warning label to after the loop, since currently you are unnecessarily updating it in each run through the loop.

Finally you shouldn't hard code the ID for the warning label, because it won't work if you have multiple groups. Instead give it a class and search for it inside the group. Also it would be better to show/hide it instead of just clearing the text.

var countrySet = {};
var countryCount = 0;
var hasDuplicates = false;

$.each($selectionArr, function (index, country) {
    if (countrySet[country]) {
        hasDuplicates = true;
    } else {
        countrySet[country] = true;
        countryCount++;
    }
});

var warningLabel = $(section).find('.warning');

if (!hasDuplicates && countryCount === 5) {
   warningLabel.removeClass('label-danger').addClass('label-success').text('Valid!').show();
} else if (hasDuplicates) {
   warningLabel.removeClass('label-success').addClass('label-danger').text('Duplicates!').show();
} else {
    warningLabel.hide();
}

I'll leave displaying the duplicate country as an exercise :-)


Clean up after shell script that is run via k8s pod on a gpu node for health check Team,
I have a working script but when we upgraded some drivers on the GPU system it’s starting to cause zombie process and system is lowing down as script runs periodically as a crib job.

so I am trying to see is there a way I can have a graceful clean up after the Scripts run what is the best procedure to clean up after yourself when Scripts is done running? What wrong am I doing or what better could it be?

gpu-health-check.sh: |
     #!/bin/bash
     # Do nothing if nvidia-smi is found. This is not a GPU node.
     if ! [ -x "$(command -v nvidia-smi)" ]; then
       echo "nvidia-smi not found. Ignoring"
       exit 0
     fi
     # Check if there is any retired page. The query is copied from https://docs.nvidia.com/deploy/dynamic-page-retirement/index.html.
     bad_gpus=$(nvidia-smi --query-retired-pages=gpu_uuid,retired_pages.address,retired_pages.cause --format=csv,noheader | cut -d, -f1| sort | uniq)
     if [ -z "${bad_gpus}" ]; then
       echo "No Single/Double Bit ECC Error found"
       exit 0
     fi
     for bad_gpu in "{$bad_gpus}"; do
       # Exit 1 if there is a pending page blacklist as we need to reboot the node to actually add the page to the blacklist.
       nvidia-smi -i $bad_gpu -q -d  PAGE_RETIREMENT | grep Pending| grep Yes > /dev/null 2>&1
       if [ $? -eq 0 ]; then
         echo "Found pending blacklist on ${bad_gpu}"
         exit 1
       fi
       echo "No pending blacklist on ${bad_gpu}"
     done
     exit 0

On gpu system I see

741:19286 ?        Z      0:00 [gpu-health-chec] <defunct>
757:30022 ?        Z      0:00 [gpu-health-chec] <defunct>
761:31930 ?        Z      0:00 [gpu-health-chec] <defunct>
762:31931 ?        Z      0:00 [gpu-health-chec] <defunct>
794:37947 ?        S      0:00 /bin/bash ./config/gpu-health-check.sh
795:37948 ?        S      0:00 /bin/bash ./config/gpu-health-check.sh
796:37955 ?        S      0:00 /bin/bash ./config/gpu-health-check.sh
803:37962 ?        S      0:00 /bin/bash ./config/gpu-health-check.sh
816:50066 ?        Z      0:00 [gpu-health-chec] <defunct>
817:50067 ?        Z      0:00 [gpu-health-chec] <defunct>

All above are just piling up. How to avoid coz system is becoming irresponsible after hours.

#!/bin/bash

Why not plain /bin/sh?  I don't see any non-POSIX shell constructs in there.

sort | uniq

We could replace with sort -u (that's a standard option).

     echo "Found pending blacklist on ${bad_gpu}"
     exit 1

That message should go to standard error stream: >&2.  The same may be true of the other informational messages.

 for bad_gpu in "{$bad_gpus}"; do

Really?  "{$bad_gpus}" is a single token; I think you meant $bad_gpus there.  Especially as we then expand $bad_gpu unquoted in the next line.

grep Pending| grep Yes > /dev/null 2>&1

If Pending and Yes always occur in the same order, we could simplify to a single command (and we don't need the redirection):

grep -q 'Pending.*Yes'

   if [ $? -eq 0 ]; then

That's an antipattern - it's a sign that you need to move the preceding statement into the if:

if nvidia-smi -i "$bad_gpu" ...
then


Recursive functions for sorting I made a few recursive functions for learning purposes which do a variety of tasks. Here is my current and functioning code:

def separate(p,l):
    ''' recursive function when is passed a predicate and a list returns a 2-tuple
    whose 0 index is a list of all the values in the argument list for which the
    predicate returns True,and whose 1 index is a list of all the values in the
    argument list for which the predicate returns False.'''
    if len(l) == 0:
        return ([],[])
    else:
        (true_list, false_list) = separate(p,l[1:])
        if p(l[0]):
            return ([l[0]] + true_list, false_list)
        else:
            return (true_list, [l[0]] + false_list)

def is_sorted(s):
    ''' recursive function when passed a list returns a bool telling whether or not
    the values in the list are in non-descending order: lowest to highest allowing
    repetitions. '''
    if len(s) <= 1:
        return True
    elif s[0] < s[1]:
        return is_sorted(s[1:])
    else:
        return False

def sort(l):
    ''' recursive function when passed a list; it returns a new list (not mutating
    the passed one) with every value in the original list, but ordered in non-
    descending order. '''
    if len(l) == 0:
        return []
    else:
        (before, after) = separate(lambda i: i < l[0], l[1:])
        return sort(before) + [l[0]] + sort(after)

def compare(a,b):
    ''' a recursive function when is passed two str arguments; it returns one of
    three str values: '<’, '=’, or '>’ which indicates the relationship between the
    first and second parameter.'''
    if a == '' and b == '':
        return '='
    if a == '' and b != '':
        return '<'
    if a != '' and b == '':
        return '>'
    if a[0] > b[0]:
        return '>'
    if a[0] < b[0]:
        return '<'
    else:
        return compare(a[1:],b[1:])

Is there a way to write these recursive functions in a cleaner/concise way? Any help would be great.

I recommend you be more consistent in not combining if followed by a statement sequence ending in return with an else (I left out the comments):

def separate(p,l):
    if len(l) == 0:
        return ([],[])
    (true_list, false_list) = separate(p,l[1:])
    if p(l[0]):
        return ([l[0]] + true_list, false_list)
    return (true_list, [l[0]] + false_list)

as you do e.g. in compare().

In compare() I would nest the conditions (arbitrarily based on a):

def compare(a,b):
    if a == '':
        if b == '':
            return '='
        return '<'
    if a != '':
        if b == '':
            return '>'
    if a[0] > b[0]:
        return '>'
    if a[0] < b[0]:
        return '<'
    return compare(a[1:],b[1:])

That way it is more clear to me that compare() never ends without a return value.

Your comments should at least use triple double quotes (PEP8) and you should try to conform to PEP 257 (docstring conventions).


Executing Scipy Tensor Product Can anyone advise on how to use the SymPy TensorProduct function without having to explicitly indicate the full sequence of objects to take the product of. Below (for the simple case N=3) you can see one of my attempts. But the tensor products are still not coinciding, hence I am still having to write out the full sequence to get the correct answer.

import scipy
from numpy import*
import math
from sympy import I, Matrix, symbols
from sympy.physics.quantum import TensorProduct

N = 3

x = array([1/(math.sqrt(2)),1/(math.sqrt(2))])

V =[]
for i in range(1,N+1):
    V.append(x)

V = array(V)

TP1 = TensorProduct(V[0],V[1],V[2])
TP2 = TensorProduct(V[:])

print TP1
print TP2

Thanks for any assistance.

To pass a list of array arguments as individual parameters to a Python function, use the * operator:

TP1 = TensorProduct(*V)

This is equivalent to TensorProduct(V[0], V[1], V[2],...,V[n])


Read a space delimiters settings file in C I'm a C# programmer and I would like to start getting better at coding in C. I wrote a function which reads a space delimiters settings file (supports comments / and #).
The code works fine. But from the point of view of C coding style, I'd like to know if this code is well written.

example settings file:

//Destination information
DestAddr 192.168.1.101
DestSSHPort 22

code:

int ReadConfigFile(char * in_filename)
{
    int t_buffSize = 612;
    char t_key[t_buffSize];
    char t_value[t_buffSize];

    //if input filename is null
    if(!in_filename ||
       *in_filename == '\0' ||
       in_filename == NULL)
    {
        return -1;
    }

    //open file
    FILE *t_fd   = NULL;
    t_fd         = fopen (in_filename,"r");

    if (t_fd == NULL)
    {
        fprintf(stderr, "Error opening input file: %s\n",
                in_filename);
        return -1;
    }

    //read individual settings lines
    char t_firstChar;
    while( (t_firstChar = getc(t_fd)) != EOF )
    {
        //skip comment line
        if(t_firstChar == '/' || t_firstChar == '#')
        {
            char t_comment[t_buffSize];
            long t_currFP = getline(t_fd, t_comment, t_buffSize);
            fseek(t_fd, t_currFP + 1, SEEK_SET);
        }
        else
        {
            long t_currFP = ftell (t_fd);
            fseek(t_fd, t_currFP - 1, SEEK_SET);

            if(fscanf (t_fd, "%s %s", t_key, t_value) != EOF)
            {
                printf("%s -- %s \n", t_key, t_value);
                //just print the values for now
            }
        }
    }

    return 0;
}

You are testing for NULL twice

//if input filename is null
if(!in_filename ||               // This is a test for NULL.   !valid pointer is 0 !NULL is 1
   *in_filename == '\0' ||       // Test for empty string

   in_filename == NULL)          // Test for NULL again.

No Need to do the work twice.
When you declare the variable assign it at the same time:

//open file
FILE *t_fd   = NULL;
t_fd         = fopen (in_filename,"r");

// Easyier to write and read:

//open file
FILE *t_fd   = fopen (in_filename,"r");

Also not keen on the short non-descriptive file name.

You are only allowing comments if the magic character is the first character in the line. That's a bit restrictive (most places allow for the first non white space character on a line to mark a comment).

That's because scanf() easily allows you to ignore white space:

while( (t_firstChar = getc(t_fd)) != EOF )
{
    //skip comment line
    if(t_firstChar == '/' || t_firstChar == '#')

// Easier with:

while(fscanf(t_fd, " %c", & nextChar) == 1)
{
   // Skips empty lines.
   // Returns the first non white space character

You are skipping lines with getline() which reads off the end of line marker ('\n'). The trouble is you are reading the line into a buffer of fixed size but not checking if you spill over that size. fscanf provides an alternative that allows you to read and discard the content.

        long t_currFP = getline(t_fd, t_comment, t_buffSize);

        // Can be replaced with:
        fscanf(t_fd, "%*[^\n]"); // Read up to the '\n character
                                 // But not including it. The star '*' indicates to
                                 // discard the input
        fscanf(t_fd, "\n");      // Read the '\n' character

        // Note you have to do these two lines separately.
        // You can not use the string "%*[^\n]\n"
        //    This is because if there is only a '\n' character (not any comment) then
        //    the first part fails and it would have failed leaving the '\n' on the stream.

But you then doing a seek() to an absolute position. I am not sure how this is working in your code because the seek moves the read point to the absolute position identified by the length of the line just read. So unless the only comment is the first line then this will fail.

// this line should just be removed).
// fseek(t_fd, t_currFP + 1, SEEK_SET);

Your move back one space in the input stream is support directly with a relative seek

       long t_currFP = ftell (t_fd);
       fseek(t_fd, t_currFP - 1, SEEK_SET);

       // replace with:
       fseek(t_fd,-1, SEEK_CUR);

Then you do the real work:

        if(fscanf (t_fd, "%s %s", t_key, t_value) != EOF)

This line will never return EOF as you have just made sure there is at least one character in the stream be rewinding one place. But it can still fail. You should test the result for the number of conversions it performed.
Also if either your key or value exceed the size of the buffer things will horribly wrong. So you need to make sure your don't read past the end of the buffer:
Finally you are not reading off the '\n' character this will leave this on the line for (see above to find about reading the rest of the line).

How to build the conversion string will depend.
You are using the identifier t_buffSize as a buffer size. If this is a macro (which it usually is) then building the string is easy with some macros magic and string compile time concatenation:

#define   DO_QUOTE(X)   #X
#define   QUOTE(X)  DO_QUOTE(X)

#define   CONVERSION_STRING_SIZE(SIZE)   "%" QUOTE(SIZE) "s"

#define   ConvString CONVERSION_STRING_SIZE(t_buffSize) " " CONVERSION_STRING_SIZE(t_buffSize)

// Assuming t_buffSize is 50 this should generate the string:
// ConvString =>  "%" "50" "s" " " "%" "50" "s"
// Consecutive string literals are concatenated at compile time to generate
// "%50s %50s"

On the other hand if t_buffSize is a variable of type int the you will need to build the string dynamically using sprintf()

char ConvString[100]; // Big enough for two integer and 5 characters
sprintf(ConvString, "%%%ds %%%ds", t_buffSize, t_buffSize);

Then you final read is:

        if(fscanf (t_fd, ConvString, t_key, t_value) == 2)
        {
             // Do Stuff
        }
        // Ignore the rest of the line:
        fscanf(t_fd, "%*[^\n]");
        fscanf(t_fd, "\n");

Summary

#define   BUFFER_SIZE   612
#define   DO_QUOTE(X)   #X
#define   QUOTE(X)      DO_QUOTE(X)
#define   ConvString    "%" QUOTE(BUFFER_SIZE) "s %" QUOTE(BUFFER_SIZE) "s"

int ReadConfigFile(char const *in_filename)
{
    char t_key[BUFFER_SIZE];
    char t_value[BUFFER_SIZE];

    //if input filename is null
    if(!in_filename || *in_filename == '\0')
    {
        fprintf(stderr, "Invalid filename\n");
        return -1;
    }

    //open file
    FILE *t_fd   = fopen (in_filename, "r");

    if (t_fd == NULL)
    {
        fprintf(stderr, "Error opening input file: %s\n", in_filename);
        return -1;
    }

    //read individual settings lines
    char t_firstChar;
    while(fscanf(t_fd, " %c", &t_firstChar) == 1 )
    {
        if(t_firstChar != '/' && t_firstChar == '#')
        {
            // Not a comment so read the key value pair
            fseek(t_fd, -1, SEEK_CUR);

            if(fscanf (t_fd, ConvString, t_key, t_value) == 2)
            {
                printf("%s -- %s \n", t_key, t_value);
            }
        }

        // Ignore the rest of the line.
        fscanf(t_fd, "%*[^\n]");
        // Don't need this line as the scanf() in the while will ignore '\n' as white space.
        // But I have left it in for clarity.
        fscanf(t_fd, "\n");
    }

    return 0;
}


Printing calculator - Stephen Kochan exercise I'm a newbie at programming, just one month into C. Working with Stephen Kochan's programming in C. There is a question in chapter 6 to write a printing calculator where 's' tells the program to set the accumulator, 'e' tells that the execution must end. And the operators tell the operations to be performed on the accumulations.

The sample run according to the book looks like this:

10 s
=10.000000
2 /
=5.000000
55 -
=-50.000000
100.25 S
=100.250000
0 E
=100.250000

I got this to work but I'm not sure about how correct this code is.

#include<stdio.h>
// write a program for a printing calculator
// exercise 4, chapter 6, kochan

int main(void)
{
 float value, output;
 char operator;
 _Bool exit;

 printf("Please enter a value and operator to begin\n");
 scanf("%f %c", &value, &operator);

while(operator != 'e' || operator != 'E')
{
   exit = 0;

 switch(operator)
 {
    case 'S':
    case 's':
    output = value;
    printf("= %.3f\n", output);
    scanf("%f  %c", &value, &operator);
    break;

    case '+':
    output = output + value;
    printf("= %3f\n", output);
    scanf("%f  %c", &value, &operator);
    break;

    case'-':
    output = output - value;
    printf("= %.3f\n", output);
    scanf("%f  %c", &value, &operator);
    break;

    case '*':
    output = output * value;
    printf("= %.3f\n", output);
    scanf("%f  %c", &value, &operator);
    break;

    case '/':
    if(value == 0)
    printf("Division by zero\n");
    else
    output = output / value;
    printf("= %.3f\n", output);
    scanf("%f  %c", &value, &operator);
    break;

    case 'E':
    case 'e':
    output = output + value;
    printf("= %.3f\n", output);
    exit = 1;
    return 0;

    default:
    printf("Unidentified operator\n");
    return 0;

  }
}

   return 0;
}

This seems correct, and it works. Some simplifications are possible.

Don't repeat yourself

These lines appear many times in the code:

printf("= %.3f\n", output);
scanf("%f  %c", &value, &operator);

You can move this part after the switch block to reduce duplication.

Remove unnecessary elements

The exit variable is written to but never read.
It seems unused, so I suggest to remove it.

Coding style

It would be easier to read if you indent the body of case statements.

It's recommended to use braces with all if-else statements.

I suggest to put a space after #include and before <stdio.h>

Suggested implementation

Putting together the suggestions above, your implementation becomes simpler and easier to read:

#include <stdio.h>

int main(void)
{
    float value, output;
    char operator;

    printf("Please enter a value and operator to begin\n");
    scanf("%f %c", &value, &operator);

    while (operator != 'e' || operator != 'E')
    {
        switch(operator)
        {
            case 'S':
            case 's':
                output = value;
                break;

            case '+':
                output += value;
                break;

            case'-':
                output -= value;
                break;

            case '*':
                output *= value;
                break;

            case '/':
                if (value == 0)
                {
                    printf("Division by zero\n");
                }
                else
                {
                    output /= value;
                }
                break;

            case 'E':
            case 'e':
                output += value;
                printf("= %.3f\n", output);
                return 0;

            default:
                printf("Unidentified operator\n");
                return 0;
        }
        printf("= %.3f\n", output);
        scanf("%f %c", &value, &operator);
    }

    return 0;
}


Design Pattern for Swing application I have a Swing application with no real design pattern. I want to start learning to design Swing or any types of application properly. Here is the main JFrame class.

    import java.awt.Component;
    import java.awt.Dimension;
    import javax.swing.JFrame;
    import javax.swing.JTabbedPane;
    import org.text.gui.components.tabs.*;

    public class TextFrame extends JFrame {

        private static final long serialVersionUID = 1289484372051624149L;
        public static final String INBOX = "Inbox";
        public static final String CONTACT = "Contact";
        public static final String SEND = "Send";
        private JTabbedPane pane;

        public TextFrame() {
            initComponents();
            layoutComponents();
            pack();
            setLocationByPlatform(true);
            setVisible(true);
        }

        public Component getTab(String title) {
        return pane.getComponentAt(pane.indexOfTab(title));
    }

    public void setSelectedTab(String title) {
        pane.setSelectedComponent(getTab(title));
    }

    private void initComponents() {
        setTitle("Text");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        pane = new JTabbedPane();
        pane.setPreferredSize(new Dimension(225, 300));
        pane.addTab(INBOX, new InboxTab(this));
        pane.addTab(CONTACT, new ContactTab(this));
        pane.addTab(SEND, new SendTab());
    }

    private void layoutComponents() {
        add(pane);
    }
}

The tabs are JPanels with some logic in them. Any advice on a design pattern to implement or examples or anything would be greatly appreciated. I hope I included enough information.

One thing would be to separate view from functionality (you may even make the business logic invocation asynchronous). You can also make your code cleaner and smaller by creating widgets that support templating and using them.


Persist keyboard backlight color on Linux laptop System76 sells laptops that come preloaded with their Ubuntu spinoff Pop_OS. The laptop keyboards have backlights that can change color and brightness, but so far I haven't found any way to keep the setting when I restart the machine; it goes back to bright white.
Here's someone else struggling with the same problem somewhat recently. The comments link to a useful python script, but it doesn't seem to be finished to the point where it would do what's wanted. (It's primary goal seems to be a GUI, with persistence on the wishlist.)
I finally got sick of it and implemented the behavior I wanted using systemd, which I'm using to call a Python script.
Since other people have asked the same questions as me in the past, I figured I'd share my solution, but the first step is to ask for feedback.
Is this a good solution to the problem? Are there mistakes or other reasons people shouldn't use it?
#!/usr/bin/env python3

import argparse as ag
import os.path as path
import re

print("Attempting to set system76 keyboard backlight color and brightness.")

"""
Partially cribbed from
https://github.com/ahoneybun/keyboard-color-chooser/blob/master/keyboard-color-switcher.py

Called by
/etc/systemd/system/system76-kb-backlight.service
as decribed here:
https://www.howtogeek.com/687970/how-to-run-a-linux-program-at-startup-with-systemd/

Example file /etc/systemd/system/system76-kb-backlight.service
``
[Unit]
Description=Set color and brightness of system-76 laptop keyboard backlight

[Service]
Type=simple
ExecStart=systemd-cat /path_to_this_executable/set_system76_kb_backlight -g 55 -r FF -B 150

[Install]
WantedBy=multi-user.target
``
(Don't forget to enable the service.)
"""

def color_fragment(string):
    if re.fullmatch(r'^[0-9A-F]{2}$', string):
        return string
    else:
        raise ag.ArgumentTypeError(f'"{string}" is not a two-digit hex value.')

def brightness_fragment(string):
    if re.fullmatch(r'^[0-9]{1,3}$', string) and 0 <= int(string) and 255 >= int(string):
        return string
    else:
        raise ag.ArgumentTypeError(f'"{string}" is not an integer 0-255.')

arg_parse = ag.ArgumentParser(description="Set the color and brightness of the system76 keyboard backlight.")
arg_parse.add_argument('-r', help="The red RGB value (00 to FF).", default="00", type=color_fragment)
arg_parse.add_argument('-g', help="The green RGB value (00 to FF).", default="00", type=color_fragment)
arg_parse.add_argument('-b', help="The blue RGB value (00 to FF).", default="00", type=color_fragment)
arg_parse.add_argument('-B', help="The brightness (0 to 255).", default="48", type=brightness_fragment)

args = arg_parse.parse_args()
red = args.r
green = args.g
blue = args.b
brightness = args.B
color = f'{red}{green}{blue}'

ledPath = "/" + path.join('sys', 'class', 'leds', 'system76_acpi::kbd_backlight') + '/'
if not path.exists(ledPath):
    ledPath = "/" + path.join('sys', 'class', 'leds', 'system76::kbd_backlight') + '/'

regions = ['left', 'center', 'right', 'extra']
region_paths = [ledPath + f'color_{r}' for r in regions]
brightness_path = ledPath + 'brightness'
settings = {brightness_path: brightness,
            **{rp: color for rp in region_paths}}

for (p,s) in settings.items():
    with open(p, 'w') as f:
        f.write(s)

print("Successfully set system76 keyboard backlight brightness.")
arg_parse.exit(0)

Namespaces...
... are not for creating taxonomies. They are there to avoid name collisions. Also the chosen module alias for argparse seems strange. It's name is derived from argument parser so, if any, the obvious abbreviation should be ap. However, it might be better to just import the needed names, instead of creating taxonomies, since there are no name collisions in your code base.
from argparse import ArgumentTypeError, ArgumentParser
from os.path import exists, join
from re import fullmatch

Don't run business logic on module load
Currently, your script parses the command line arguments and writes to files, as soon as the module is laoded. This can be avoided by using an if __name__ == '__main__': guard and / or a main() function.
def main():
    """Runs the script."""

    arg_parse = ag.ArgumentParser(description="Set the color and brightness of the system76 keyboard backlight.")
    arg_parse.add_argument('-r', help="The red RGB value (00 to FF).", default="00", type=color_fragment)
    arg_parse.add_argument('-g', help="The green RGB value (00 to FF).", default="00", type=color_fragment)
    arg_parse.add_argument('-b', help="The blue RGB value (00 to FF).", default="00", type=color_fragment)
    arg_parse.add_argument('-B', help="The brightness (0 to 255).", default="48", type=brightness_fragment)

    args = arg_parse.parse_args()
    …

if __name__ == '__main__':
    main()

It might be even better to outsource the argument parsing into an own function.
def get_args():
    """Parses the command line arguments."""

    arg_parse = ag.ArgumentParser(description="Set the color and brightness of the system76 keyboard backlight.")
    arg_parse.add_argument('-r', help="The red RGB value (00 to FF).", default="00", type=color_fragment)
    arg_parse.add_argument('-g', help="The green RGB value (00 to FF).", default="00", type=color_fragment)
    arg_parse.add_argument('-b', help="The blue RGB value (00 to FF).", default="00", type=color_fragment)
    arg_parse.add_argument('-B', help="The brightness (0 to 255).", default="48", type=brightness_fragment)
    return arg_parse.parse_args()

def main():
    """Runs the script."""

    args = get_args()
    …

Input validation
Your input validation seems complicated. In both cases, for the RGB values and the brightness, an integer within a certain range is expected.
def parse_rgb(text):
    """Parses an RGB value from a string."""

    rgb = int(text)

    if not 0 <= rgb <= 0xff:
        raise ValueError('RGB value out of bounds.')

    return rgb

def parse_brightness(text):
    """Parses a value for the brightness from a string."""

    brightness = int(text)

    if not 0 <= brightness <= 255:
        raise ValueError('Brightness out of bounds.')

    return brightness

Note that argparse will automatically display an error message if a parser specified at type= raises a ValueError. So you can also get rid of one import and work with a built-in exception instead.
The downside of the integer parsing is, that you'll have to convert the ints back to strings then:
red = hex(args.r)[2:].upper().zfill(2)
green = hex(args.g)[2:].upper().zfill(2)
blue = hex(args.b)[2:].upper().zfill(2)
brightness = str(args.B)
…

You may also subclass an int for this use case:
class RGB(int):
    def __init__(self, value):
        if not 0 <= value <= 0xff:
            raise ValueError('RGB value out of bounds.')

    def __str__(self):
        return hex(self)[2:].upper().zfill(2)

    …

arg_parse.add_argument('-r', help="The red RGB value (0x00 to 0xff).", default=RGB(0), type=RGB)
…
red = str(args.r)


First-come first-serve job scheduling algorithm I tried to make the code for implementation of first-come first-serve job scheduling algorithm as used by operating systems.

How can I make it better?

I am using turbo C++ compiler

#include<conio.h>
#include<iostream.h>
#include<dos.h>
struct process//contains information about processes in waiting queue
{
    int waitt;
    int etime;
    char name[32];
    struct process * next;
};

void inc( struct process * q)//increases wait time of all processes in wait queue
{
     while(q!=0)
     {
         q->waitt++;
         q=q->next;
     }
}

int pop(struct process** q)//remove process from wait queue to run state returns wait time of process
{
    int wait=(*q)->waitt;
    struct process* t=*q;
    *q=(*q)->next;
    delete t;
    return wait;
}

void addnode(struct process** q)//add new process to wait queue
{
   struct process *temp=new (struct process);
   cout<<"\nEnter process name ";
   cin>>temp->name;
   do
   {
        cout<<"\nEnter process execution time ";
        cin>>temp->etime;
   }while(temp->etime<=0);//to check valid input for process burst time
   temp->next=0;
   temp->waitt=0;
   if(*q==0)
   *q=temp;
   else
   {
        struct process* t=*q;
        while(t->next!=0)
        t=t->next;
        t->next=temp;
    }
}

int main(void)
{
    clrscr();
    int e=1,wait=0,p=0,tt=1;
    struct process* q=0,*t;
    //add first process
    addnode(&q);
    e=q->etime;//Burst time of runing process
    cout<<"\nProcess "<<q->name<<" startedafter a wait time of "<<q->waitt;
    cout<<" time units \n";
    p++;
    wait=pop(&q);
    do
    {
        //to check addition of new process
        if(kbhit())
        addnode(&q);
        //increase wait time of waiting processes
        inc(q);
        //decrement time left for finishing of process
        e--;
        if(e==0)//if process ended
        {
            if(q!=0)/*if process is left in wait queue remove next process from wait queue and add  its wait time to total time*/
            {
                e=q->etime;
                cout<<"\n"<<q->name<<" started after a wait time of "<<q->waitt<<"time units\n";
                p++;
                wait+=pop(&q);
             }
        }
        delay(100);
        cout<<tt++<<"  ";//to show total time units since start of first process
    }while(q!=0||e!=0);//if process ended also no process in wait queue end loop
    cout<<"\n\nTotal no. of prcesses executed ="<<p;
    cout<<"\nTotal wait time for all prcesses executed ="<<wait;
    cout<<"\nAverage wait time for prcesses executed ="<<wait/(float)p;
    getch();
    return 0;
}

I think this question would actually benefit from both a C review (just change the cout's to printf, etc) and a C++ review since you seem to be using a very C-orientated programming style.

This post will be a C++ review.
Please note that the Turbo C++ compiler is not available to me, so my suggestions will revolve around the C++98/03 standard.

My first bit of advice would be to switch to an object-oriented approach.
Turn process into a class and create a second class, process_queue.

In process, replace char name [32] with std::string name. This way, you don't have to worry about buffer overflows.

Refactor inc(), pop(), and addnode() into member functions for the new class process_queue.

Make pop() return a process instead of an int. This is because you have a queue of processs, not a queue of ints.

Rename inc() to something more readable like increment_all_wait_times(). That's a long name, but your code will be self-documenting.

Take out the user-input logic from inc(), pop(), and addnode().
This will improve their flexibility.
A function should only do one thing, and do it well.

For function parameters, prefer the use of references over the use of pointers.
This will save you from having to check for NULL.

Here is an idea of what a process class might look like:

class process
{
public:
    process (const std::string &name, const int burst_time = 0, const int wait_time = 0) ;

    // getters
    std::string name () const ;
    int burst_time () const ;
    int wait_time () const ;
    const process* next () const ;
    process* next () ;

    void decrement_burst_time (const int time) ;

private:
    int burst_time_;
    int wait_time_;
    std::string name_;
    process *next_;

    friend  std::ostream& operator<< (std::ostream &os, const process &proc) ;
    friend class process_queue ;
};

This would encapsulate your variables and (for the most part) make them read-only.
Because the process_queue class is tightly coupled with this class, I would make it a friend class. There are two versions of the next() method for the sake of const-correctness.

Here is an idea of what a process_queue class might look like:

class process_queue
{
public:
    process_queue () ;
    ~process_queue () ;

    bool empty () const ;
    void add_node (const process &proc) ;
    void increment_all_wait_times (const int wait) ;
    process pop () ;
    size_t size () const ;

    friend std::ostream & operator<< (std::ostream &os, const process_queue &pq) ;

private:
    size_t size_ ;
    process *head_;
    process *tail_; // for O(1) insertions
};

This, once again, encapsulates your variables while still providing useful functionality.

Here's what a constructor implementation might look like:

process::process (const std::string &name, const int burst_time, const int wait_time)
    : name_ (name), burst_time_ (burst_time), wait_time_ (wait_time), next_ (NULL)
{
}

What you see here is a constructor initialization list. It is important to initialize your variables or else you may suffer from subtle bugs.

Here is a destructor for the process_queue class:

process_queue::~process_queue ()
{
    while (size_ > 0) {
        this->pop () ;
    }
}

This makes sure all of our resources (memory in this case) are cleaned up when an instance of this class goes out of scope. This strategy is called RAII. RAII is important for writing exception-safe code.

Here is an example implementation of all of the above combined (somewhat sloppily):

#include <iostream>
#include <string>
#include <stdexcept>

class process_queue ;

class process
{
public:
    process (const std::string &name, const int burst_time = 0, const int wait_time = 0) ;

    std::string name () const ;
    int burst_time () const ;
    int wait_time () const ;
    const process* next () const ;
    process* next () ;

    void decrement_burst_time (const int time) ;

private:
    int burst_time_;
    int wait_time_;
    std::string name_;
    process *next_;

    friend  std::ostream& operator<< (std::ostream &os, const process &proc) ;
    friend class process_queue ;
};

process::process (const std::string &name, const int burst_time, const int wait_time)
    : name_ (name), burst_time_ (burst_time), wait_time_ (wait_time), next_ (NULL)
{
}

std::string process::name () const
{
    return name_ ;
}

int process::burst_time () const
{
    return burst_time_ ;
}

int process::wait_time () const
{
    return wait_time_ ;
}

const process* process::next () const
{
    return next_ ;
}

process* process::next ()
{
    return next_ ;
}

void process::decrement_burst_time (const int time)
{
    burst_time_ -= time ;
}

std::ostream & operator<< (std::ostream &os, const process &proc)
{
    os  << "{Name = " << proc.name ()
        << ", Wait time = " << proc.wait_time ()
        << ", Burst time = " << proc.burst_time ()
        << ", Next = " ;

    if (proc.next () != NULL) {
        os << proc.next ()->name () ;
    }

    else {
        os << "None" ;
    }

    os << "}" ;

    return os ;
}

class process_queue
{
public:
    process_queue () ;
    ~process_queue () ;

    bool empty () const ;
    void add_node (const process &proc) ;
    void increment_all_wait_times (const int wait) ;
    process pop () ;
    size_t size () const ;

    friend std::ostream & operator<< (std::ostream &os, const process_queue &pq) ;

private:
    size_t size_ ;
    process *head_;
    process *tail_; // for O(1) insertions
};

process_queue::process_queue () : head_ (NULL), tail_ (NULL), size_ (0)
{
}

void process_queue::add_node (const process &proc)
{
    process *temp = new process (proc) ;

    if (tail_ != NULL) {
        tail_->next_ = temp ;

        if (head_ == tail_) {
            head_->next_ = temp ;
        }

        tail_ = tail_->next_ ;
    }

    else {
        tail_ = temp ;
        head_ = tail_ ;
    }

    ++size_ ;
}

void process_queue::increment_all_wait_times (const int wait)
{
    process *temp = head_ ;

    while (temp != NULL) {
        temp->wait_time_ += wait ;
        temp = temp->next_ ;
    }
}

// Pops the head off.
process process_queue::pop ()
{
    if (head_ == NULL) {
        throw std::range_error ("process_queue::pop() called while the process_queue was empty.") ;
    }

    process ret = *head_ ;
    process *temp = head_ ;
    head_ = head_->next_ ;
    delete temp ;
    --size_ ;

    return ret ;
}

bool process_queue::empty () const
{
    return (size_ == 0) ;
}

size_t process_queue::size () const
{
    return size_ ;
}

std::ostream & operator<< (std::ostream &os, const process_queue &pq)
{
    process *temp = pq.head_ ;

    while (temp != NULL) {
        os << *temp << "\n" ;
        temp = temp->next () ;
    }

    return os ;
}

process_queue::~process_queue ()
{
    while (size_ > 0) {
        this->pop () ;
    }
}

namespace scheduler
{
    void run_first_come_first_serve (process_queue &pq)
    {
        std::cout << "Running first-come-first-serve scheduler with no preemption." "\n" ;

        while (pq.empty () == false) {
            process proc = pq.pop () ;

            std::cout << "Running " << proc.name () << "\n" ;

            std::cout << proc.name () << " finished running after " << (proc.burst_time () + proc.wait_time ()) << " ns." "\n" ;
            pq.increment_all_wait_times (proc.burst_time ()) ;

            std::cout << "Queue:\n" << pq << "\n" ;
        }
    }
}

int main(void)
{
    process notepad ("notepad.exe", 500) ;
    process firefox ("firefox.exe", 1500) ;
    process excel ("excel.exe", 100) ;
    process visual_studio ("visual studio.exe", 200) ;
    process super_virus ("super virus.exe", 1000) ;

    process_queue pq ;
    pq.add_node (notepad) ;
    pq.add_node (firefox) ;
    pq.add_node (excel) ;
    pq.add_node (visual_studio) ;
    pq.add_node (super_virus) ;

    scheduler::run_first_come_first_serve (pq) ;

    return 0 ;
}


Print Consecutive numbers by comparing two parameters input 3,5 output should be 3,4,5

input 5,3 output should be 5,4,3

And the code

public static void test(int a, int b) {
        if(a>b) {
            for (int i = a; i >= b; i--) {
                System.out.print(i + "\t");
            }
        }else if(a<b) {
            for (int i = a; i <= b; i++) {
                System.out.print(i + "\t");
            }
        }
    }

It works but looks a little messy. Is it possible to do without if else thing? Only one loop.

The function name is weird.  What is it testing?  A more appropriate name might be printInclusiveRange(…, …).

Since the bounds are inclusive, I would expect that for input 3,3, the output should be 3.  Yet you output nothing.

I would also expect the output not to end with a Tab character.

Here's one solution that corrects those two problems, and also combines the loops:

public static void printInclusiveRange(int a, int b) {
    System.out.print(a);
    if (a != b) {
        int i = a;
        int step = (a < b) ? +1 : -1;
        do {
            i += step;
            System.out.print("\t" + i);
        } while (i != b);
    }
    System.out.println();  // Perhaps you want a newline here?
}


Script to execute arbitrary command on each Git project in a directory The idea is simple, most people have some one directory containing all their projects as subdirectories. When you are in the top directory and you run this script like so for-each-git.sh git status it will run the command git status in each of the folders. I have another script called git-ffwd that fetches all remotes and fast forward updates them which I usually run each morning with this script.

#!/bin/bash
for dir in $(find . -maxdepth 1 -type d); do
    (
        cd ${dir}
        if [ -d ".git" ]; then
            pwd
            "$@"
            echo
        fi
    )
done

Some explanation:

The parenthesis is so we are able to easily go back to the project directory in case the commands you push in run cd or something. (It makes a subshell.)
pwd is so we know for sure which directory is being worked on and the echo is just so a new line separates everything a little more.

I know this is a small script but I am new-ish to writing Bash scripts and want to learn.

The lines pwd; "$@"; echo seem a little ugly, though they do work. Also I can't pass multiple commands in with a ; like echo hey; echo bye because the ; ends the statement in the "$@" line, so I am wondering if there's a better way to write that line (or pass them in).

Instead of using find and testing whether .git is a directory, you could make a simplification:

for git_dir in */.git ; do
(
    cd "$git_dir/.." &&
    pwd &&
    $@
    echo
)
done

Admittedly, this causes an error when .git exists but is not a directory:

-bash: cd: blah/.git/..: Not a directory

… instead of silently skipping that entry as your script does.  But I would consider the error message to be a feature, not a bug.  =)  Note my use of && after cd to ensure that the command is not executed if the cd fails.  (That could happen if the directory lacks the executable bit.)

If you wanted to support compound commands like echo hey; echo bye, you could use eval $@.  Using eval feels a bit risky, but it's OK if the script is for your own personal use and won't be attacked.


Try/catch in a Tic-Tac-Toe game I'm looking at my code and it doesn't look very efficient. I'm simply trying to catch exceptions or prevent them from being thrown in the first place. Can you please take a look and tell me if there is a way to make my working code more efficient?

public static void GetMoveCoordinates(ref int XCoordinate, ref int YCoordinate)
    {
        bool invalidCoordinate = false;

        do
        {
            try
            {

                Console.Write("Enter x coordinate: ");
                XCoordinate = int.Parse(Console.ReadLine());
                if (XCoordinate < 1 || XCoordinate > 3)
                {
                    invalidCoordinate = true;
                    Console.WriteLine("Invalid coordiantes, please try again.");
                }
                else
                    invalidCoordinate = false;

                if (!invalidCoordinate)
                {
                    Console.Write("Enter y coordinate: ");
                    YCoordinate = int.Parse(Console.ReadLine());
                    if (YCoordinate < 1 || YCoordinate > 3)
                    {
                        invalidCoordinate = true;
                        Console.WriteLine("Invalid coordiantes, please try again.");
                    }
                    else
                        invalidCoordinate = false;
                }
            }

            catch
            {
                Console.WriteLine("Invalid coordiantes, please try again.");
                invalidCoordinate = true;
            }
                Console.WriteLine();

        } while (invalidCoordinate);

    }  // end of GetMoveCoordinates

Alright, first some styling remarks.

Indent correctly

Opening braces of your method should be at the same level below of the method signature, not indented. You seem to have done it correctly elsewhere so that might be a copying error.

Follow naming conventions

Parameters and local variables are lowerCamelCase. This means XCoordinate becomes xCoordinate and likewise for YCoordinate.

Positive beats negative beats battlestar galactica

Always prefer using "positive" expressions rather than "negative". If I'd want to use your code to say the coordinate is valid, I'd have to use if(!invalidCoordinate). Nobody likes double negation.

I can see why you might have done this (invalid input sets invalidCoordinate to true) but in that case I would just use a break; statement to exit your loop.

Change it to validCoordinate and your loop becomes while(!validCoordinate).

Braces around if statements

Some will argue this but to avoid misconceptions or problems with future changes: always place {} brackets around statements that can have it to very clearly mark their scope. Your else statements don't have this which makes it prone to logical errors (forgetting to add the braces when the else block actually needs more than just that statement).

Don't overassign

Your while loop already stops when invalidCoordinate is true. There is no point in explicitly setting it to false.

No typos

Yuck.

Don't repeat yourself

It seems to me that both x and y have to be between 1 and 3? Let's put that in a method instead of copy-pasting it and changing where needed.

Useful comments

I know that is the end of GetMoveCoordinates because your favorite awesome best-in-the-galaxy IDE - Visual Studio - will show you that. Place your cursor behind the closing brace and it will popup the method definition at the top of your editor window.

As has been noted in the comments: make sure that your comments explain why you do something. It is not clear why things have to be between 1 and 3 exactly so this is a good place to start.

After applying all this, we have this situation:

public static void GetMoveCoordinates(ref int xCoordinate, ref int yCoordinate)
{
   bool validCoordinate = true;

   do
   {
       try
       {
            Console.Write("Enter x coordinate: ");
            GetCoordinate(ref validCoordinate, ref xCoordinate);

            if (validCoordinate)
            {
                Console.Write("Enter y coordinate: ");
                GetCoordinate(ref validCoordinate, ref yCoordinate);
            }
       }

       catch
       {
           Console.WriteLine("Invalid coordinates, please try again.");
           break;
       }
       Console.WriteLine();
   } while (!validCoordinate);
}

private static void GetCoordinate(ref bool validCoordinate, ref int coordinate)
{
    coordinate = int.Parse(Console.ReadLine());
    if (coordinate < 1 || coordinate > 3)
    {
        validCoordinate = false;
        Console.WriteLine("Invalid coordinates, please try again.");
    }
}

Now it's easy to see what you can do with that try block: you move it to the helper method! And the result is this:

public static void GetMoveCoordinates(ref int xCoordinate, ref int yCoordinate)
{
   bool validCoordinate = true;

   do
   {
    Console.Write("Enter x coordinate: ");
    GetCoordinate(ref validCoordinate, ref xCoordinate);

    if (validCoordinate)
    {
        Console.Write("Enter y coordinate: ");
        GetCoordinate(ref validCoordinate, ref yCoordinate);
    }

    Console.WriteLine();
   } while (!validCoordinate);
}

private static void GetCoordinate(ref bool validCoordinate, ref int coordinate)
{
    try
    {
        coordinate = int.Parse(Console.ReadLine());
    }
    catch
    {
        Console.WriteLine("Invalid coordinates, please try again.");
        validCoordinate = false;
        return;
    }

    if (coordinate < 1 || coordinate > 3)
    {
        validCoordinate = false;
        Console.WriteLine("Invalid coordinates, please try again.");
    }
}


Retrieving remote pages and parsing html This is my code:

    <?php
$begin = microtime(TRUE);
$result = get_web_page('WEB_PAGE');

$dom = new DOMDocument();
$dom->loadHTML($result['content']);
$xpath = new DOMXPath($dom);

// Get the links
$matches = $xpath->evaluate('//li[@class = "lasts"]/a[@class = "lnk"]/@href | //li[@class=""]/a[ @class = "lnk"]/@href');
if ($matches === FALSE) {
    echo 'error';
    exit();
}
foreach ($matches as $match) {
    $links[] = 'WEB_PAGE'.$match->value;
}

$index = 0;

// For each link
foreach ($links as $link) {
    echo (string)($index).' loop '.(string)(microtime(TRUE)-$begin).'<br>';
    $result = get_web_page($link);

    $dom = new DOMDocument();
    $dom->loadHTML($result['content']);
    $xpath = new DOMXPath($dom);

    $match = $xpath->evaluate('concat(//span[@id = "header"]/span[@id = "sub_header"]/text(), //span[@id = "header"]/span[@id = "sub_header"]/following-sibling::text()[1])');
    if ($matches === FALSE) {
        exit();
    }
    $data[$index]['name'] = $match;

    $matches = $xpath->evaluate('//li[starts-with(@class, "active")]/a/text()');
    if ($matches === FALSE) {
        exit();
    }
    foreach ($matches as $match) {
        $data[$index]['types'][] = $match->data;
    }

    $matches = $xpath->evaluate('//span[@title = "this is a title" and @class = "info"]/text()');
    if ($matches === FALSE) {
        exit();
    }
    foreach ($matches as $match) {
        $data[$index]['info'][] = $match->data;
    }

    $matches = $xpath->evaluate('//span[@title = "this is another title" and @class = "name"]/text()');
    if ($matches === FALSE) {
        exit();
    }
    foreach ($matches as $match) {
        $data[$index]['names'][] = $match->data;
    }

    ++$index;
}

?>

This is what is being printed:

0 loop 1.66981506348
1 loop 2.49688410759
2 loop 3.00950098038
3 loop 3.5253970623
4 loop 4.01076102257
5 loop 4.67162799835
6 loop 5.2378718853
7 loop 5.74008488655
8 loop 6.26041197777
9 loop 6.78747105598
10 loop 7.47332000732
11 loop 8.03243994713
12 loop 8.50538802147
13 loop 9.37472701073
14 loop 11.5049209595
15 loop 12.2112920284
16 loop 12.6640410423
17 loop 13.1369791031
18 loop 13.8875179291
19 loop 14.4746370316
20 loop 14.9760200977
21 loop 15.5332159996
22 loop 16.1946868896
23 loop 17.0584990978
24 loop 17.840462923
25 loop 18.6889989376
26 loop 19.6185629368
27 loop 20.8282380104
28 loop 22.0119960308
29 loop 22.9078469276
30 loop 24.0000309944
31 loop 24.6960549355
32 loop 25.1580710411
33 loop 25.5702528954
34 loop 26.2709059715
35 loop 26.7621939182
36 loop 27.2691950798
37 loop 27.88843894
38 loop 28.6984479427
39 loop 29.4622280598
40 loop 30.2815680504
41 loop 31.1307020187

What it does is basically connects to a remote page, retrieves it and parses links from that page.
Then for each link, it retrieves it and parses it, creates a new data structure and then uses it (the part of using the structure is not included here).
The output that I added is the time that has passed since the beginning of the runtime of the script.
It takes about 30 seconds for this code to run, which is insane.
How can I improve it?

Really, the best way to optimize performance is to make the HTTP requests in parallel.  After you have done that, you could consider further optimizations with regards to parsing.

Consider using curl_multi_exec() or similar for this.

I have a REST client based on curl_multi_exec() that you can feel free to take a look at for inspiration (or just use as-is in your application based on MIT license).

https://github.com/mikecbrant/php-rest-client


Caling AJAX Method for multiple hidden ids aspx I am calling a ajax method for a number of hidden client ids on an aspx page.  The ajax method returns some html to a div provided.

So the code looks like below:

<asp:HiddenField runat="server" ID="hdnSomeProperty" Value="False"/>
<asp:HiddenField runat="server" ID="hfMyIndex" Value="0" />
<asp:HiddenField runat="server" ID="hfCustId" />
<asp:HiddenField runat="server" ID="hfCarId" />
<asp:HiddenField runat="server" ID="hfVanId" />
<asp:HiddenField runat="server" ID="hfTruckId" />
<asp:HiddenField runat="server" ID="hfMotorCycleId" />

var carNode = "<%=VechileNodeTypeEnum.Car.ToString() %>";
var selectedCarIds = $('#<%=hfCarId.ClientID %>').val();
ajaxMethod('/MyPage/MyMethod', { custId: custId, vechileNodeType: carNode, selectedIds: selectedCarIds }, '#carDiv');

var vanNode = "<%=VechileNodeTypeEnum.Van.ToString() %>";
var selectedVanIds = $('#<%=hfVanId.ClientID %>').val();
ajaxMethod('/MyPage/MyMethod', { custId: custId, vechileNodeType: vanNode, selectedIds: selectedVanIds }, '#vanDiv');

var truckNode = "<%=VechileNodeTypeEnum.Truck.ToString() %>";
var selectedTruckIds = $('#<%=hfTruckId.ClientID %>').val();
ajaxMethod('/MyPage/MyMethod', { custId: custId, vechileNodeType: truckNode, selectedIds: selectedTruckIds }, '#truckDiv');

var motorcycleNode = "<%=VechileNodeTypeEnum.MotorCycle.ToString() %>";
var selectedMotorcycleIds = $('#<%=hfMotorCycleId.ClientID %>').val();
ajaxMethod('/MyPage/MyMethod', { custId: custId, vechileNodeType: motorcycleNode, selectedIds: selectedMotorcycleIds }, '#motorcycleDiv');

Everything works as expected however I dont like the pattern of repeating the code 4 times with just a few of the proerties changed - I was think I could perhaps use a for loop and loop round 4 times - not sure how I would pass the changed properties dynamically though?

You should create a function that would wrap the ajax call and use it as many times as you wish.

var callMyMethod = function(nodeType, clientId, target) {
  var ids = $('#' + clientId).val();
  ajaxMethod('/MyPage/MyMethod', {
    custId: custId, // is it a global variable?
    vehicleNodeType: nodeType,
    selectedIds: ids
  }, target);
};

callMyMethod('<%=VechileNodeTypeEnum.Car.ToString()%>', '<%=hfCarId.ClientID%>', '#carDiv');
callMyMethod('<%=VechileNodeTypeEnum.Van.ToString()%>', '<%=hfVanId.ClientID%>', '#vanDiv');
callMyMethod('<%=VechileNodeTypeEnum.Truck.ToString()%>', '<%=hfTruckId.ClientID%>', '#truckDiv');
callMyMethod('<%=VechileNodeTypeEnum.MotorCycle.ToString()%>', '<%=hfMotorCycleId.ClientID%>', '#motorCycleDiv');

If there is some correlation between for example hfCarId.ClientID and #carId, you can remove the target argument from the function.

It should be also possible to generate these calls by iterating over Car, Van, Truck and MotorCycle but I'm not that familiar with .net to suggest it to you.


Command called 'sprinkle' I have a command called sprinkle. I'm not going to explain anything about it, because I want whoever that reviews the code to also tell me how much of the command documentation they understood.

Here is what I need help with:

Is the documentation good enough? Is it too verbose?
Does the constant domainName help you understand the code below, or is it useless?
Should the transformations array be passed around instead of being defined as a global variable?
What else can I improve in the code?

// The sprinkle command allows the user to define some transformations in a file called test.txt.
// The user can then provide some domain names such as 'go' and the application will randomly transform it, using the transformations defined in test.txt.
// Every transformation in the test.txt file must have an asterisk (*) in place of the domain name. For example, if the test file contains:
//
// *-is-awesome.com
//
// love-*.net
//
// lets-*.org
//
// Then, if the user enters 'go' in the command line, the output could be something like:
//
// go-is-awesome.com
package main

import (
    "bufio"
    "fmt"
    "log"
    "math/rand"
    "os"
    "strings"
    "time"
)

const (
    domainName = "*"
)

var transformations []string

func main() {
    var err error

    transformations, err = readLinesFromFile("test.txt")
    if err != nil {
        log.Fatal(err)
    }

    inputScanner := bufio.NewScanner(os.Stdin)
    for inputScanner.Scan() {
        fmt.Println(applyRandomTransformation(inputScanner.Text()))
    }
}

// readLinesFromFile reads a file into an array. Each element in the array is one line of the text file.
func readLinesFromFile(path string) ([]string, error) {
    var lines []string
    file, err := os.Open("test.txt")
    if err != nil {
        return nil, err
    }
    defer file.Close()

    scanner := bufio.NewScanner(file)
    for scanner.Scan() {
        lines = append(lines, scanner.Text())
    }

    return lines, nil
}

// applyRandomTransformation randomly chooses a transformation from the list of transformations, and replaces the '*' in the transformation with input
func applyRandomTransformation(input string) string {
    rand.Seed(time.Now().UnixNano())
    transformation := transformations[rand.Intn(len(transformations))]
    return strings.Replace(transformation, domainName, input, -1)
}

First, look at your documentation to see how will look to users:

  The Go Blog

  Godoc: documenting Go code

$ go doc sprinkle
The sprinkle command allows the user to define some transformations in a
file called test.txt. The user can then provide some domain names such as
'go' and the application will randomly transform it, using the
transformations defined in test.txt. Every transformation in the test.txt
file must have an asterisk (*) in place of the domain name. For example, if
the test file contains:

*-is-awesome.com

love-*.net

lets-*.org

Then, if the user enters 'go' in the command line, the output could be
something like:

go-is-awesome.com
$

Amongst other things, domain name is a misnomer.

Second, look at your sprinkle command help:

$ ./sprinkle -help
$

Third, read your code. And, fourth, run your code.

Find and fix several bugs (others have identified some of them). Since domainName is a misnomer, rename it to wildcard.

Rewrite the sprinkle command go doc description:

$ go doc
The sprinkle command transforms a random line of text from the sprinkle.txt
file by replacing asterisk (*) wildcard characters with text from stdin.

For example,

    $ cat sprinkle.txt
    *-is-awesome.com
    love-*.net
    lets-*.org
    $ echo go | ./sprinkle
    love-go.net
    $ echo go | ./sprinkle
    go-is-awesome.com
    $
$

TODO: provide sprinkle command help.


Laravel lumen : Post API method Question is quite simple, I am using dingo package, Currently below is my code for an API call.

public function publishApplicant(Request $request,$id){
    $changeStatus = \App\User::where('id', $id)->update(array('admin_published' => 1));

    if($changeStatus){
        return response()->json([
            'message' => 'Applicant published.',
            'code' => 200,
            'status' => 1
        ], 200);
    }

    return response()->json([
        'message' => 'Applicant published.',
        'code' => 500,
        'status' => 0
    ], 200);
}

What can be improved in the above code?

You could store the response in a variable and only call return once. That seems cleaner. Also, put constants like messages and HTTP codes into constant variables.


Printing a K-ary tree stored in level-order in an array I am given an array that represents a k-ary tree (I am also given the branching factor "k") that is stored in level order. My task was to print the tree in level order.

For example a trinary tree stored as {0,1,2,3,null,null,null,7,8,9,10,11,12} (It doesn't have to be full or complete) would print out as:

0
1 2 3
null null null 7 8 9 10 11 12

My solution currently works fine but it is very messy and not as elegant as I would prefer. The runtime complexity is also very bad (I don't know if Math.pow is O(1) or O(n) but if it's O(1), my code is still O(n) which is not ideal. If Math.pow is O(n) then my code is O(n2) which is garbage.

Is there another approach I am not seeing or can my existing code be optimized at all?

public static void main(String[] args) {
  int k = 3;
  Integer[] arrInt = {0,1,2,3,null,null,null,7,8,9,10,11,12};

  String ans = arrInt[0] + "\n";
  int currLvl = 1;
  int prevLvl = 0;
  //Print all values
  for(int i = 1; i < arrInt.length-1; ++i){
    //Add a line if we reach a new level
    if(i == (Math.pow(k, currLvl)+Math.pow(k, prevLvl))){
      currLvl++;
      prevLvl++;
      ans+= "\n";
    }
    ans+= " " + arrInt[i];
  }
  //EDGE CASE TO HANDLE LAST ELEMENT
  ans+= " " + arrInt[arrInt.length-1];
  System.out.println(ans);
}

Your biggest performance problem is the repeated string concatenation using the + operator.  Since Java strings are immutable, every += operation requires allocating a new string and copying the previous contents.  Use a StringBuilder instead.

Math.pow() should be avoided, since it performs floating-point arithmetic, and this task should be accomplished using just integer arithmetic.  Why not keep track of the desired width of the current row, and use an inner loop to print each row?

public static void main(String[] args) {
    int k = 3;
    Integer[] arrInt = {0,1,2,3,null,null,null,7,8,9,10,11,12};

    StringBuilder ans = new StringBuilder();
    for (int i = 0, width = 1; i < arrInt.length; i += width, width *= k) {
        for (int j = i, end = Math.min(i + width, arrInt.length); j < end; ++j) {
            ans.append((j > i) ? " " : (j > 0) ? "\n" : "")
               .append(arrInt[j]);
        }
    }
    System.out.println(ans);
}


Create a list of all possible combinations of elements into n-groups from a set of size k I'm trying to write a Java program that, given a particular number of groups and number of total participants, creates a list of all possible ways to fill that number of groups evenly using all the participants. The group number/order doesn't matter. For instance, if {} denotes one possible way to create a set of groups, [] denotes a group, and each individual is represented by a number, the groupings {[1,2],[3,4,5]} and {[4,3,5],[1,2]} should be considered equivalent and are both valid groupings for an input of 5 participants and 2 groups.

So far I've written the following code, which works by recursively finding all possible permutations and removing any duplicates (like in the example above). This works fine for small input values, but becomes extremely slow quickly. Can anyone give my any ideas on how to either optimize this code or for a more efficient way to do this (and if the latter, pseudo or java code would be great)? I know that there might not be an extremely fast way to do this, but I'd like to at least be able to run it with some reasonably small numbers and have it finish in a relatively short time period and not take up more RAM than it has too.

Let me know if the above explanation is unclear! Thanks!

private int numParticipants, numGroups, maxParticipantsPerGroup;
private ArrayList<ArrayList<ArrayList<Integer>>> participantGroups = new ArrayList<ArrayList<ArrayList<Integer>>>();

private void generateParticipantGroupings() {
    ArrayList<ArrayList<Integer>> groupings = new ArrayList<ArrayList<Integer>>();
    for (int i = 0; i < numGroups; i++)
            groupings.add(new ArrayList<Integer>());

    buildParticipantGrouping(1, groupings);
}

private void buildParticipantGrouping(int currentParticipant, ArrayList<ArrayList<Integer>> grouping) {
    if (currentParticipant > numParticipants) {
        boolean match = false;
        for (int j = 0; j < participantGroups.size(); j++) {
            int numMatches = 0;
            for (int k = 0; k < numGroups; k++) {
                for (int m = 0; m < numGroups; m++) {
                    if (grouping.get(k).equals(participantGroups.get(j).get(m))) {
                        numMatches++;
                        break;
                    }
                }

            }

            if (numMatches >= numGroups) {
                match = true;
                break;
            }
        }

        if (!match)
            participantGroups.add(grouping);
    }
    else {
        for (int i = 0; i < numGroups; i++) {
            if (grouping.get(i).size()  < maxParticipantsPerGroup)  {
                ArrayList<ArrayList<Integer>> tempGroupings = new ArrayList<ArrayList<Integer>>();
                for (int a = 0; a < numGroups; a++) {
                    tempGroupings.add(new ArrayList<Integer>());

                    for (Integer x : grouping.get(a))
                        tempGroupings.get(a).add(x);
                }

                tempGroupings.get(i).add(currentParticipant);

                buildParticipantGrouping(currentParticipant + 1, tempGroupings);
            }
        }
    }
}

EDIT: Yes, I have searched to see if I can find a previous post that asks the same question. I have not found any. If you can find a previous post asking the same question (that has answers) then I'd love to see it, but otherwise please make sure that a question is actually the same as mine before suggesting it as a duplicate.

First, determine the one or two group sizes that will apply, and how many of each you will have.  Define m, the maximum capacity of any one group, as ceil( k / n ).  Let i represent the number of groups of size m.  Solving for i, we have

m == ceil( k / n )
( m * i ) + ( ( m - 1 ) * ( n - i ) ) == k
( m * i ) + ( m * ( n - i ) ) - ( n - i ) == k
( m * n ) - ( n - i ) == k
( m * n ) - k - n == -i
k + ( n * ( 1 - m ) ) == i

Thus, there will be i groups of size m and n - i groups of size m - 1.

Then, choose an ordering of the groups.  This is like generating an integer with a given number of 1 bits.  If k happens to be divisible by 'n', there's only one possible ordering.  See Gosper's hack for a nifty way to get the next choice given the current choice, which is essential if you want to implement this as an iterator that yields the next grouping on each call to next().

class GosperIterator implements Iterator< Long > {
    private final int iParticipants, iGroups, iMaxCap, iHowManyMax;
    private long lCurrentOrder;
    public GosperIterator( int iParticipants, int iGroups ) {
        this.iParticipants = iParticipants;
        this.iGroups = iGroups;
        this.iMaxCap = Math.ceil( iParticipants / iGroups );
        this.iHowManyMax = iParticipants + ( iGroups * ( 1 - iMaxCap ) );
        // implemented only for maximum of 64 groups
        this.lCurrentOrder = ( 1L << iHowManyMax ) - 1L;
    }
    @Override public boolean hasNext() {
        return lCurrentOrder < ( 1L << iGroups );
    }
    @Override public Long next() {
        long lOut = lCurrentOrder;
        // Gosper's Hack
        long c = lCurrentOrder & -lCurrentOrder;
        long r = lCurrentOrder + c;
        lCurrentOrder = ( ( ( r ^ lCurrentOrder ) >>> 2 ) / c ) | r;
        return lOut;
    }
    // would be nice if there were a read-only iterator interface
    @Override public void remove() {
        throw new UnsupportedOperationException();
    }
}

Then, allocate each participant x to one of the not full groups which is between the first and the maximum empty group.  That means, in particular, that participant 1 always ends up in the first group, participant 2 always ends up in the first or second group (if there are two groups), etc.

To do this one grouping per next() call, you will need to produce the first grouping (all the participants in order,  say), then start removing participants in reverse order of participant number, looking for an alternative place to assign them which has a higher group number but no smaller empty group.  If no such place exists, back out to a smaller participant number.  If you get all the way to participant 1, it is time to call on Gosper again, and if there are no numbers left for Gosper, you're done.

class GroupingWithFixedLayoutIterator implements Iterator< Set< Set< Integer > > > {
    @Override public boolean hasNext() {
        // left as exercise
    }
    @Override public Set< Set< Integer > > next() {
        // left as exercise
    }
    // would be nice if there were a read-only iterator interface
    @Override public void remove() {
        throw new UnsupportedOperationException();
    }
}
class GroupingIterator implements Iterator< Set< Set< Integer > > > {
    private final int iParticipants;
    private final Iterator< Long > ilLayout;
    private Iterator< Set< Set< Integer > > issiGrouping = null;

    public GroupingIterator( int iParticipants, int iGroups ) {
        this.iParticipants = iParticipants;
        this.ilLayout = new GosperIterator( iParticipants, iGroups );
        initFixedLayoutIterator();
    }
    private final boolean initFixedLayoutIterator() {
        this.issiGrouping = ilLayout.hasNext()
            ? new GroupingWithFixedLayoutIterator( iParticipants, ilLayout.next() )
            : new EmptyIterator< Set< Set< Integer > > >(); // left as exercise
    }
    @Override public boolean hasNext() {
        return issiGrouping.hasNext() || ilLayout.hasNext();
    }
    @Override public Set< Set< Integer > > next() {
        if ( !issiGrouping.hasNext() )
            initFixedLayoutIterator();
        return issiGrouping.next();
    }
    // would be nice if there were a read-only iterator interface
    @Override public void remove() {
        throw new UnsupportedOperationException();
    }
}


python hangman solver I wrote a program that read a csv file that contain 100 rows that look like:
1;S****L;SCHOOL
2;*A*G*A*;HANGMAN

then try to guess the letters like in a hangman game. My scope is to count every right and wrong letters and then sum them up. The code works fine, I get around 1670 right + wrong attempts to guess the letters. My approach was to create a dictionary in which I store all the letters from the alphabet and read every words from the file then sum every appearance of a letter and store them in the dictionary. Somethin like
{
   "A" : 30,
   "B" : 40
}

Then I sort the dict based on every letter occurrence and first try to guess the letter with the most apparace.
My question. Is something that I can improve in order to get a smaller number of attempts?
import csv

INPUT_FILE = "words.csv"

def oppenFile():        # function to read the file
    with open(INPUT_FILE, "r", encoding="utf-8") as words:
        reader = list(csv.reader(words, delimiter=";"))
        return reader

def letterCount():      # function that count every the letter in the file and return a dict: {A : 2}
    letters = dict.fromkeys("QWERTYUIOPĂÎASDFGHJKLȘȚÂZXCVBNM", 0)
    words = oppenFile()
    for w in range(len(words)):
        for l in list(words[w][2]):
            if l not in list(words[w][1]):
                letters[l] += 1
    return letters

def checkLetters(word, wholeWord, letters):     # function that solve a word return the number of right + wrong attempts
    attempts = 0
    for letter, key in letters.items():
        if letter in wholeWord and letter not in word:
            attempts += 1
            index = [i for i, lit in enumerate(wholeWord) if lit == letter]
            letters[letter] -= len(index)
            for j in range(len(index)):
                word = word[:index[j]] + letter + word[(index[j] + 1):]

        elif '*' not in word:
            break
        else:
            attempts += 1
    return attempts

def hangman():
    words = oppenFile()
    numberOfAttempts = 0
    letters = letterCount()

    for i in range(len(words)):
        letters = dict(sorted(letters.items(), key=lambda x: x[1], reverse=True)) # sort the dict

        numberOfAttempts += checkLetters(words[i][1], words[i][2], letters)

    print(f"{numberOfAttempts} right + wrong attempts")

if __name__ == "__main__":
    hangman()

Welcome to Code Review!
PEP-8
In python, it is common (and recommended) to follow the PEP-8 style guide for writing clean, maintainable and consistent code.
Functions and variables should be named in a lower_snake_case, classes as UpperCamelCase, and constants as UPPER_SNAKE_CASE.
Type hinting
With newer python versions, you can make use of type hinting to give a brief overview of the type of variables and function parameters.
Counting letters
Python provides an inbuilt collections.Counter for you to make use of.
Comments
The comments don't really help here. Also, prefer writing docstring over comments for functions.
Variable names
You open a file, and name its pointer as words, whereas the function is returning a list of words; called reader, which in turn is stored in a variable called words?
Weird conversions
You generate a mapping of letters to their respective counts, as a dictionary (hash-map/table/lookup), then convert it to list of 2-valued tuple, sort that, and convert back to dictionary. Why? dict has \$ O(1) \$ lookup and sorting makes no sense in your case.
Iteration with index
You use the following loop structure:
for i in range(len(words)):

where, i in itself is serving no purpose. Every occurrence of usage of i is of the form words[i]. You can just iterate over the values of words list itself:
for word in words:


Python implementation of Conway's Game of life with Pygame So I've started learning programming a few months ago and this is one of my first projects. The program works, but I feel like it's a bit slow compared to the other implementations of Conway's Game of life. Is there any ways I could speed up my code ?

import numpy
import copy
import pygame
from pygame.locals import *
import random

pygame.init()

height = 400
width = 400
block_size = 4
window = pygame.display.set_mode((height,width),DOUBLEBUF)
window.set_alpha(None)
alive = (255,255,255)
dead = (0,0,0)

def check(y_axis,x_axis,grid):
    tmp_grid = copy.copy(grid)
    for y in range(1,y_axis-1):
        for x in range(1,x_axis-1):
            a = 0
            for i in range(-1,2):
                for j in range(-1,2):
                    if grid[y+i][x+j] == 1:
                        a += 1
            if grid[y][x] == 1:
                a -= 1
                if a < 2 or a > 3:
                    tmp_grid[y][x] = 0
            elif grid[y][x] == 0:
                if a == 3:
                    tmp_grid[y][x] = 1
    grid = tmp_grid
    return grid

def display(y_axis,x_axis,grid):
    rects = []
    for y in range(1,y_axis-1):
        for x in range(1,x_axis-1):
            rect = pygame.Rect(x*block_size, y*block_size, block_size, block_size)
            if grid[x][y] == 1:
                rects.append(pygame.draw.rect(window,alive,rect))
            elif grid[x][y] == 0:
                rects.append(pygame.draw.rect(window,dead,rect))
    pygame.display.update(rects)

def generate(y_axis,x_axis,grid):
    for y in range(1,y_axis-1):
        for x in range(1,x_axis-1):
            alive_or_dead = random.randint(0,1)
            if alive_or_dead:
                grid[y][x] = 1
            else:
                grid[y][x] = 0

def main():
    y_axis = height//block_size
    x_axis = width//block_size
    grid = numpy.zeros((y_axis,x_axis))
    generate(y_axis,x_axis,grid)
    while True:
        display(y_axis,x_axis,grid)
        grid = check(y_axis,x_axis,grid)

if __name__ == '__main__':
    main()

In your generate function, numpy.random.randint can do everything you need. I'd suggest renaming the function to generate_grid and just returning the generated grid.
In your display and check functions, the grid parameter knows its own size - you don't need to pass that in.
In display, your alive and dead colors could be in a tuple. Then you could index the tuple by [0] or [1] (the value of the cell) to determine the color:

rect = pygame.Rect(x*block_size, y*block_size, block_size, block_size)

rects.append(pygame.draw.rect(window, Colors[grid[x][y]], rect)

Pretty much everything with a dot (.) or an expression should be cached inside display.

pgrect = pygame.Rect
rappend = rects.append
drawrect = pygame.draw.rect

Your x/y loop can be replaced using np.apply_over_axes
The scipy.signal.convolve2d function will do most of the heavy lifting for you in terms of neighbor counting &c