texts: Is it necessary to replace this cursor in SQL Server 2005?

texts:
The Problem

I have a cursor that I am trying to replace (perhaps unnecessarily) in an attempt to clean up a stored procedure. Essentially what it is doing is counting each note for each member in a temp table and then assigning each of those notes a sequential value into the field NOTE_COUNTER (int) of the temp table. Here is the original code for it with the variables:

@lUPI_current          CHAR(32),
@lCASE_SEQ_current     INT,
@lDIFF_ENCOUNTER_DATE  INT,
@lcounter              INT

SET @lUPI_current = ''
SET @lCASE_SEQ_current = ''
SET @lDIFF_ENCOUNTER_DATE = 0
SET @lcounter = 0

DECLARE CURSOR_NOTE_COUNTER CURSOR FOR
SELECT
    MEMBER,
    CASE_SEQ,
    ENCOUNTER_DATE
FROM
    #TMP_NOTES
WHERE
    TOTAL_CALLS > 1
ORDER BY
    MEMBER,
    CASE_SEQ,
    ENCOUNTER_DATE

OPEN CURSOR_NOTE_COUNTER

FETCH NEXT FROM CURSOR_NOTE_COUNTER
INTO
  @lUPI_current,
  @lCASE_SEQ_current,
  @lDIFF_ENCOUNTER_DATE

WHILE (@@FETCH_STATUS = 0)
BEGIN
    SET @lcounter = (
                        SELECT
                            MAX(NOTE_COUNTER)
                        FROM
                            #TMP_NOTES
                        WHERE
                            MEMBER_UPI = @lUPI_current
                            AND CASE_SEQ = @lCASE_SEQ_current
                    )
UPDATE #TMP_NOTES
    SET
        NOTE_COUNTER = @lcounter + 1
    FROM #TMP_NOTES
    WHERE
        MEMBER_UPI = @lUPI_current
        AND CASE_SEQ = @lCASE_SEQ_current
        AND DIFF_ENCOUNTER_DATE = @lDIFF_ENCOUNTER_DATE

    FETCH NEXT FROM CURSOR_NOTE_COUNTER
    INTO
        @lUPI_current,
        @lCASE_SEQ_current,
        @lDIFF_ENCOUNTER_DATE
END

What I Have Tried

I tried replacing this with a CTE because of the notion that cursors should be avoided in favor of working on sets of data. Here was my attempt at that, the stumbling block being the ambiguity of the column names since it is working on the same table.

WITH RecordsBeingUpdated AS
    (
        SELECT
            MEMBER_UPI,
            CASE_SEQ,
            DIFF_ENCOUNTER_DATE,
            ROW_NUMBER() OVER (PARTITION BY MEMBER_UPI, CASE_SEQ, DIFF_ENCOUNTER_DATE ORDER BY DIFF_ENCOUNTER_DATE ASC) AS RowNum
        FROM
            #TMP_NOTES
        WHERE
            TOTAL_CALLS > 1
    )

UPDATE #TMP_NOTES
    SET
        NOTE_COUNTER = R.RowNum
    FROM
        RecordsBeingUpdated AS R
    WHERE
       MEMBER_UPI = R.MEMBER_UPI
       AND CASE_SEQ = R.CASE_SEQ
       AND DIFF_ENCOUNTER_DATE = R.DIFF_ENCOUNTER_DATE

Please tell me if there is a cleaner way to doing this. I am grateful for any time that the community can provide.


texts: Scala BitSet implemented with Java BitSet, for use in Scala Enumerations to replace ValueSet

texts:
Due to a performance profiling hotspot detailed here, I implemented my own BitSet using Java's BitSet.  This is intended to replace the Enumeration.ValueSet.  However, it's a bit awkward to use, primarily due to my likely misunderstanding of the relationships between the Enumeration class, Enumeration type and concrete Enumeration object.

In my enumeration objects, I have to have code like this:

type BitSet = alder.BitSet[this.type]
val empty = alder.BitSet[this.type]()

Elsewhere, I need to do things like this:

alder.BitSet.fromBitMask[SomeEnumeration.type](...)

For mkString I need to actually pass in the enumeration object itself.  Is there any way to make this entire edifice a little more user-friendly?

package alder

import scala.language.implicitConversions

class BitSet[E <: Enumeration](val bits: java.util.BitSet) {

  def isEmpty: Boolean = bits.isEmpty

  def nonEmpty: Boolean = !isEmpty

  override def hashCode = bits.hashCode

  override def equals(o: Any) = o match {
    case that: BitSet[E] => this.bits equals that.bits
    case _ => false
  }

  def union(that: BitSet[E]): BitSet[E] = {
    var newBits = bits
    newBits.or(that.bits)
    new BitSet[E](newBits)
  }

  def |(that: BitSet[E]): BitSet[E] = union(that)

  def |(v: E#Value): BitSet[E] = union(BitSet(v))

  def intersection(that: BitSet[E]): BitSet[E] = {
    var newBits = bits
    newBits.and(that.bits)
    new BitSet(newBits)
  }

  def &(that: BitSet[E]): BitSet[E] = intersection(that)

  def &(v: E#Value): BitSet[E] = intersection(BitSet(v))

  def contains(v: E#Value): Boolean = bits.get(v.id)

  def containsAll(that: BitSet[E]): Boolean = intersection(that) == that

  def containsAny(that: BitSet[E]): Boolean = intersection(that).nonEmpty

  def toBitMask(): Array[Long] = bits.toLongArray

  def mkString(e: E, sep: String): String =
  {
    val vs = e.ValueSet.fromBitMask(toBitMask())
    vs.mkString(sep)
  }

}

object BitSet {

  def apply[E <: Enumeration](): BitSet[E] = new BitSet[E](new java.util.BitSet)

  def apply[E <: Enumeration](vs: E#Value*): BitSet[E] = {
    var bits = new java.util.BitSet
    for (v <- vs) {
      bits.set(v.id)
    }
    new BitSet[E](bits)
  }

  def fromBitMask[E <: Enumeration](mask: Array[Long]): BitSet[E] =
    new BitSet[E](java.util.BitSet.valueOf(mask))

}


texts:
I'm relatively new to Python scripting. I made a script that takes two raw data files and merges them into one CSV file, but it takes a long time to complete.  Are there any logic problems in this code?

input_fileVms = open( 'vms.csv', 'rb')

if site == 'eg':
    output_merge = open('mergedFileEG.csv', 'wb')
elif site== 'fm':
    output_merge = open('mergedFileFM.csv', 'wb')

dataVms = csv.reader(input_fileVms)
writerMerge = csv.writer(output_merge,quoting=csv.QUOTE_ALL)

for lineVM in dataVms:
    input_fileUsers = open( 'users.csv', 'rb')
    dataUsers = csv.reader(input_fileUsers)
    new_line = strip(lineVM)
    OSFile = open('OS.csv', 'rb')
    OS = csv.reader(OSFile)
    i = 0
    for user in dataUsers:
        if i < 4:
            i = i + 1
        else:
            user = strip(user)
            if len(user) >= 4:

                idLine = str(user[1])

                if idLine in new_line:

                    for OS in OS:
                        system = OS[0]
                        if system in new_line:

                            if len(user) < 5:
                                writerMerge.writerow((str(new_line[2] + ',' + user[2] + "," + "Missing"+ ',' +OS[1])).split(','))
                            else:
                                writerMerge.writerow((str(new_line[2] + ',' + user[2] + "," +user[4]+ ',' +OS[1])).split(','))

            input_fileUsers.close()


texts:
The end result is a bar formatted table chart that has expanding and minimising rows.

The code below works fine but I'd like to know if there is a cleaner way to achieve the same result (see JSFiddle for working example).

In the production version, the datatable & the "parent" rows (for want of a better term) will be defined at run time, hence asking if there is a better way to do it.

Points to note, I'm very much an ok-ish hobbyist coder and my background is much more vb.NET orientated than JS. It took a tonne of google searching and code example plagiarism just to get it to work, so please excuse any school-boy errors.

JSFiddle

HTML:

JavaScript:

// Creates a bar formatted table chart with expanding and retracting rows
// DataTable contains ALL the rows to be displayed, "parent" rows are
// declared twice.  The first declaration contains the button event that shows the
// child rows when clicked.  The second declaration contains the button event that
// reduces the visable rows to the parent rows.
// Two buttons are required for ease of coding and to show a + on the first
// declaration and a - in the second.

google.charts.load('current', {'packages':['table']});
google.charts.setOnLoadCallback(drawVisualization);

function drawVisualization(iRows) {

  var sRows
  if (iRows === undefined) {
    sRows = [0, 4, 10, 13]
  }
  else {
    sRows = iRows
  }

  //Create and format the DataTable visualization with bar formatter
  //This has to be done outside of the chartWrapper declaration so that
  //the bar formatter is applied.  chartWrapper does not allow for formatting
  //to be applied to the DataTable

var data = new google.visualization.DataTable();
  data.addColumn('string', '+/-');
  data.addColumn('string', 'Department');
  data.addColumn('number', 'Revenues');
  data.addRows([
                ['<button onclick="MaxDraw(0);">+</button>', 'abc', 1000],
                ['<button onclick="MinDraw(0);">-</button>', 'abc', 1000],
                ['', '123', 650],
                ['', '456', 350],
                ['<button onclick="MaxDraw(3);">+</button>', 'def', 10000],
                ['<button onclick="MinDraw(3);">-</button>', 'def', 10000],
                ['', '789', 1000],
                ['', '101', 3000],
                ['', '112', 2000],
                ['', '131', 4000],
                ['<button onclick="MaxDraw(8);">+</button>', 'ghi', 500],
                ['<button onclick="MinDraw(8);">-</button>', 'ghi', 500],
                ['', '415', 500],
                ['<button onclick="MaxDraw(10);">+</button>', 'jkl', 6000],
                ['<button onclick="MinDraw(10);">-</button>', 'jkl', 6000],
                ['', '161', 5500],
                ['', '718', 500]
                            ]);

    var table = new google.visualization.Table(document.getElementById('vis_div'));

    var formatter = new google.visualization.BarFormat({width: 220});
    formatter.format(data, 2);

  var wrapper = new google.visualization.ChartWrapper({
    chartType: 'Table',
    dataTable: data,
    options: {allowHtml: true},
    view: {rows: sRows},
    containerId: 'vis_div'
  });

  wrapper.draw();

}

MaxDraw = function DrawRows(iSelectedRow){

  if (iSelectedRow === 0){
    drawVisualization([1, 2, 3, 4, 10, 13]);
  }
  else if (iSelectedRow === 3){
    drawVisualization([0, 5, 6, 7, 8, 9, 10, 13]);
  }
  else if (iSelectedRow === 8){
    drawVisualization([0, 4, 11, 12, 13]);
  }
  else if (iSelectedRow === 10){
    drawVisualization([0, 4, 10, 14, 15, 16]);
  }
}

MinDraw = function DrawRows(iSelectedRow){
    drawVisualization([0, 4, 10, 13]);
}


texts:
I'm learning Python for 2 months now and I'm working on a little exercise app calculating percentages. I'd like to ask for a code review and comments. I'd like to make sure I'm following the right habits from the beginning.

# coding: utf-8

# In[9]:

def percA(perc, num):
    perc_a = perc/100 * num
    return perc_a

def percB(first, second):
    percB = first/second*100
    return percB

def percC(old, new):
    percC = (new - old)/old*100
    return percC

def percD(num, perc):
    perc = perc/100
    percD = num * (1 + perc)
    return percD

def percE(num, perc):
    perc = perc/100
    percD = num * (1 - perc)
    return percD

print("**************************************")
print("************** WELCOME ***************")
print("**************************************")
print("\n")
choose = input("Choose option:\nA. X% of Y\nB. X is what percent of Y\nC. By what percentage a number increased?\nD. Add percent to a number\nE.Substract percentage from a number\nYour answer: ")
if choose.isupper() == True:
    choose = choose.lower()
while choose == "a":
    if "a":
        usrperc = int(input("Provide percentage: "))
        usrnum = int(input("Provide number: "))
        result = percA(usrperc, usrnum)
        print("{0}% of {1} is {2}".format(usrperc, usrnum, result))
        break
    elif "b":
        usrperc = int(input("Provide percentage: "))
        usrnum = int(input("Provide number: "))
        result = percA(usrperc, usrnum)
        print("{0}% of {1} is {2}".format(usrperc, usrnum, result))
        break
else:
    print("Choose from range A - E")


texts: Variable bit length lossy floating point compression

texts:
I am implementing a new compression algorithm for the weights of a neural network for the Leela Chess project. the weights are roughly 100Mb of float32s which I want to compress as small as possible. Error tolerance for this application is 2^-17, so lossy compression is clearly the right answer here. All of the weights are between -5 and 5, but 99.995% are in (-.25,.25) and most reasonably closely clumped around zero.

The basic idea with this algorithm is to turn floats into integer multiples of the error tolerance, and then use a utf-8 inspired encoding to represent small values with only 1 byte.

import numpy as np
import bz2
def compress(in_path, out_path):
    with open(in_path, 'rb') as array:
        net = np.fromfile(in_path, dtype=np.float32)

    # Quantize
    net = np.asarray(net * 2**17, np.int32)

    # Zigzag encode
    net = (net >> 31) ^ (net << 1)

    # To variable length
    result = np.zeros(len(net)*3, dtype=np.uint8)
    for i in range(3):
        big = (net >= 128) << 7
        result[i::3] = (net % 128) + big
        net >>= 7

    # Delete non-essential indices
    zeroes = np.where(result == 0)[0]
    zeroes = zeroes[np.where(zeroes % 3 != 0)]
    result = np.delete(result, zeroes)

    with bz2.open(out_path, 'wb') as out:
        out.write(result.tobytes())
def decompress(in_path, out_path):
    with bz2.open(in_path, 'rb') as array:
        result = np.frombuffer(array.read(), dtype=np.uint8)

    start_inds = np.where(result<128)[0]
    not_zeroed = np.ones(len(start_inds), dtype=np.bool)

    # append zeroe so loop doesn't go out of bounds
    result = np.append(result, np.zeros(4, dtype=np.uint8))

    # Get back fixed length from variable length
    net = np.zeros(len(start_inds), dtype=np.uint32)
    for i in range(3):
        change = (result[start_inds] % 128) * not_zeroed
        net[np.where(not_zeroed)[0]] *= 128
        net += change
        start_inds += 1
        not_zeroed &= result[start_inds] >= 128

    # Zigzag decode
    net = (net >> 1) ^ -(net & 1)
    print(np.mean(net))

    # Un-quantize
    net = np.asarray(net, np.float32)
    net /= 2**17

    with open(out_path, 'wb') as out:
        out.write(version)
        out.write(net.tobytes())

compress('diff.hex','diff.bz2')
decompress('diff.bz2','round.hex')

The main type of advice I'm looking for is algorithm and performance advice, but ways to make the code readable are always nice.


texts:
I have implemented the shuffling algorithm of Fisher-Yates in C++, but I've stumbled across the modulo bias.  Is this random number generation by rand() correct for Fisher-Yates?

srand(time(NULL));
vector<int> elements;
// push numbers from 1 to 9 into the vector
for (int i = 1; i < 9; ++i)
{
    elements.push_back(i);
}

// the counter to be used to generate the random number
int currentIndexCounter = elements.size();
for (auto currentIndex = elements.rbegin(); currentIndex != elements.rend() - 1;
     currentIndex++ , --currentIndexCounter)
    {
        int randomIndex = rand() % currentIndexCounter;
        // if its not pointing to the same index
        if (*currentIndex != elements.at(randomIndex))
        {
            //then swap the elements
            swap(elements.at(randomIndex), *currentIndex);
        }
    }


texts: Make change for a given amount given denominations

texts:
Make change like at a cash register

Input is the denominations of the currency and the sum
In test case only coins are entered

Return how many of each denomination
Return the fewest possible denomination count (don't return all pennies)

Check for style, efficiency, correctness, and anything else you want to check.

// test
for (int i = 1; i <= 200; i++)
{
    Dictionary<int, int> change = MakeChange(new List<int> { 1, 5, 10, 25, 50 }, i);
    Debug.WriteLine($"sum {i}");
    int sum = 0;
    foreach (KeyValuePair<int, int> coins in change)
    {
        sum += coins.Key * coins.Value;
        Debug.WriteLine($"  coin {coins.Key}  count {coins.Value} ");
    }
    if (i != sum)
    {
        Debug.WriteLine("problem");
    }
}
// end test

private static Dictionary<int, int> MakeChange(List<int> coins, int sum)
{
    if(sum < 0 || coins.Count == 0)
    {
        throw new ArgumentOutOfRangeException();
    }
    Dictionary<int, int> change = new Dictionary<int, int>();
    foreach (int coin in coins.Distinct().Where(x => x > 0).OrderByDescending(x => x))
    {
        int j = sum / coin;  //integer math rounds down
        if (j > 0)
        {
            change.Add(coin, j);
        }
        sum -= j * coin;
        if (sum == 0)
            return change;
    }
    return null;
}


texts: Time and space complexity of base conversion code

texts:
I have an algorithm that performs the base conversion. The input is a string and two ints b1 and b2. The string represents an int in base b1 and converts it into base in b2.

My code is:

def convert_base(num_as_string, b1, b2):
    if num_as_string == '0' or num_as_string == '-0':
        return num_as_string
    base10, degree = 0, 0
    is_neg = False
    if num_as_string[0] == '-':
        is_neg, num_as_string = True, num_as_string[1:]
    if b1 == 10:
        base10 = int(num_as_string)
    else:
        for digit in num_as_string[::-1]:
            base10 += string.hexdigits.index(digit.lower()) * (b1 ** degree)
            degree += 1
    if b2 == 10:
        return '-' + str(base10) if is_neg else str(base10)
    converted = []
    while base10 > 0:
        digit = base10 % b2
        converted.append(digit)
        base10 //= b2
    res = ''
    for i in converted[::-1]:
        res += string.hexdigits[i].upper()
    return '-' + res if is_neg else res

Now I am trying to see if this can be improved in terms of time and space complexity. But I am not sure how to analyze the complexity of this code.

I know everything is constant before for digit in num_as_string[::-1]:. In this loop, it's just `O(n) where n is just number of digits of the input.

Then in while base10 > 0, it runs the look while base10 becomes 0. So, this would be something like O(number of digits in base10)

Finally, on for i in converted[::-1], this would also be O(number of digits in base10).

So, I am assuming the time complexity of this code is something like O(n) + 2 * O(number of digits in base10) which is linear.

For space, I am assuming it's O(number of digits in base10) because I store it in converted list.

Are my observations correct? If not, what am I missing? Also, can this code be improved in terms of time and space complexity?

Thanks


texts:
I have just finished learning basic-intermediate Python subjects and wanted to test myself. So here is the my basic Rock-Paper-Scissors game.

def play():
    import random

    player_score = 0
    ai_score = 0

    while True:
        try:
            user_choice = int(input("\nRock: 1"
                                    "\nPaper: 2"
                                    "\nScissor: 3"
                                    "\nWrite the number of the object you choose: "))
        except NameError:
            print("You can only enter number.")
            continue
        except ValueError:
            print("You can only enter number.")
            continue

        if user_choice not in range(1, 4):
            print("Invalid number, you have to write numbers between 1-3")
            continue

        rps = {1: "Rock", 2: "Paper", 3: "Scissor"}
        ai_choice = random.randint(1, 3)

        print(f"\nPlayer's choice: {rps[user_choice]} | AI's choice: {rps[ai_choice]}")

        if user_choice == ai_choice:
            print("Draw!")
        elif user_choice == 1:
            if ai_choice == 2:
                print("AI's paper wrapped Player's rock, AI won this round!")
                ai_score += 1
            elif ai_choice == 3:
                print("Player's rock crushed AI's scissor, Player won this round!")
                player_score += 1
        elif user_choice == 2:
            if ai_choice == 1:
                print("Players's paper wrapped AI's rock, Player won this round!")
                player_score += 1
            elif ai_choice == 3:
                print("AI's scissor cut Player's paper, AI won this round!")
                ai_score += 1
        elif user_choice == 3:
            if ai_choice == 1:
                print("AI's rock crushed Player's scissor, AI won this round!")
                ai_score += 1
            elif ai_choice == 2:
                print("Player's scissor cut AI's paper, Player won this round!")
                player_score += 1

        print(f"\nPlayer's score: {player_score} | AI's score: {ai_score}"
              f"\nGame ends when player or AI's score reach 3!")

        if player_score == 3:
            print("Game over, Player won!")
            quit()
        elif ai_score == 3:
            print("Game over, AI won!")
            proceed = input("Wanna try again and show the AI your unmatched and great wisdom?"
                            "\nWrite Y or N >: ").lower()
            if proceed == "y":
                play()
            elif proceed == "n":
                quit()
            else:
                print("Invalid command, exiting program...")
                quit()

if __name__ == "__main__":
    play()

So, what do you think? How can i make it better, what are my mistakes?


texts:
I'm new to ruby on rails, on this project I'm using Ruby 2.0 and Ruby on Rails 3.0.

I would like to know if this piece of code can be refactored, as it is

unless params["ot_code"].nil?
  ots = params["ot_code"].gsub(/\r\n?/, "").gsub(";","','").upcase
  ots[ots.length,1] = "'"
  ots =  ots.rjust(ots.length+1,"'")
end

unless params["circuit_id_multiple"].nil?
   multiple_circuit = params["circuit_id_multiple"].gsub(/\r\n?/, "").gsub(";","','")
   multiple_circuit[multiple_circuit.length,1] = "'"
   multiple_circuit = multiple_circuit.rjust(multiple_circuit.length+1,"'")
end

unless params["multiple_element_code"].nil?
   multiple_element_code = params["multiple_element_code"].gsub(/\r\n?/, "").gsub(";","','")
   multiple_element_code[multiple_element_code.length,1] = "'"
   multiple_element_code = multiple_element_code.rjust(multiple_element_code.length+1,"'")
end


texts:
Reverse digits of an integer.

Example1:

x = 123,

return 321
Example2:

x = -123,

return -321

Return 0 if the result overflows and does not fit in a 32 bit signed integer

This is my approach:

public class Solution {
    public int reverse(int A) {

        String ans = " ";
        String finalAns = " ";
        int range = 2147483647;
        if( (A > 0) && (A <= range))
            {
                ans = String.valueOf(A);
                return (Integer.parseInt(new StringBuilder(ans).reverse().toString()));
            }
        if( (Math.abs(A) > range))
            return 0;

        else if ( (A > - (range + 1)) && (A < 0) )
            {
                ans = String.valueOf(Math.abs(A));

                if( Math.abs(A) > range)
                    return 0;

                finalAns =  (new StringBuilder(ans).reverse().toString());

                double d = Double.parseDouble(finalAns);
                if( d  == (int)d )
                    return Integer.parseInt( "-" + finalAns);
                else
                    return 0;
            }
        else
            return 0;
    }
}

I have following questions regarding my code:

1) Is there a better approach to solve this question?

2) Are there any Java coding conventions that I have violated gravely?

3) Am I doing redundant steps?

Reference


texts: Potentially superfluous iOS interface system

texts:
I have written an interface system for iOS that allows interface elements to be moved around on the screen as actors move around on stage. It can operate within a ViewController environment. It relies on messaging through the Notification Centre (obviously not LocalNotification).

The central object is the ARKView object. It has 'ARKState objects associated with it that contain information about where it should be (along with colour, alpha, transform, etc.) at each 'scene'.

My question:

I have Googled many moons to find a system which does this already. It turns out that having hundreds of objects on screen all sending each other notifications is not very efficient. Perhaps I can do it with delegates? I need a system in which I can precisely specify the position and properties of every element upon pressing a button or other stimulus.

Code

ARKView/receiveNotification:

- (void)receiveNotification:(NSNotification *)notification
{
    NSDictionary *dictionary = [notification userInfo];
    if ([notification.name isEqualToString:State] && [self.stateDictionary count]!=0) {
        NSString *stateId = [dictionary objectForKey:StateId];
        NSString *sender = [dictionary objectForKey:Sender];

        [self syncStateWithId:stateId andSender:sender];
    }
}

For each ARKView object, this method above attempts to find a state object that matches the name of the notification sent from another object, if it is found, it 'syncs' the state, giving the ARKView object the attributes it needs for that scene.


texts: Adding a checkbox to a JavaScript class object

texts:
I'm working on adding checkbox functionality that controls adding new checkboxes to a div element as well a tracking checkbox behavior.  My goal is to make this dirt simple.  I've noticed that there is some JavaScript function prototypes for creating objects such as checkboxes and also controlling basic behavior such as visibility, whether its checked or disabled and maybe even adding a label or image next to the checkbox.  My plan is to add this to an array or list and how can this be done?

I just need basic class object in JavaScript to be created to track just whether its checked, visible, or disabled.   In my case when its disabled it will not be checked, but may change in a later release.  I've looked at GWT and ZWT JavaScripting libraries and they seem too complicated.  Is there a simple solution I can do myself?

Looking for some constructive criticism, a good link or two for reference, and perhaps an estimate on whether this is feasible and how would I add a checkbox to the class below, and do I also have to worry about adding events to this?  And what would be the best way to track multiple famous people in this example: a list, an array, or another class?  I'm thinking a dynamic array of some kind.

    // Constructor for dynamic checkbox classes
var FamousPerson = function (id, checkStatus, visibleStatus, enabledStatus) {
    this.id = id;  // primary key for a person for a specific row
    this.checkStatus = checkStatus;
    this.visibleStatus = visibleStatus;
    this.enabledStatus = enabledStatus;
}

FamousPerson.prototype.getId() = function () {
    return this.id;  // id is reference stored in xml or database row
};

FamousPerson.prototype.update = function (checkStatus, visibleStatus, enabledStatus) {
    // note: don't update id
    this.checkStatus = checkStatus;  // boolean 0 is not checked, 1 is checked
    this.visibleStatus = visibleStatus; // boolean 0 is not visible, 1 is visible
    this.enabledStatus = enabledStatus; // boolean 0 is not enalbed, 1 is enabled
};

FamousPerson.prototype.getCheckStatus = function () {
    return this.checkStatus;
};

FamousPerson.prototype.getVisibleStatus = function () {
    return this.visibleStatus;
};


texts:
Am trying to create a minesweeper game, I have the following code which has to many nested ifs, I want to change the code to take out the nested ifs and make it better to read. But I am stuck on how to change the nested ifs. Any help would be great. thanks

   /*method to check cells around a cell and set its value.*/
   public void setCellValues(){
            for(int i = 0; i<side; i++){
                for(int j = 0; j<side; j++){
                     if(cells[i][j].getValue() != -1){
                         if(j>=1 && cells[i][j-1].getValue() == -1) cells[i][j].incrementValue();
                         if(j<= limit && cells[i][j+1].getValue() == -1) cells[i][j].incrementValue();
                         if(i>=1 && cells[i-1][j].getValue() == -1) cells[i][j].incrementValue();
                         if(i<= limit && cells[i+1][j].getValue() == -1) cells[i][j].incrementValue();
                         if(i>=1 && j>= 1 && cells[i-1][j-1].getValue() == -1) cells[i][j].incrementValue();
                         if(i<= limit && j<= limit && cells[i+1][j+1].getValue() == -1) cells[i][j].incrementValue();
                         if(i>=1 && j<= limit && cells[i-1][j+1].getValue() == -1) cells[i][j].incrementValue();
                         if(i<= limit && j>= 1 && cells[i+1][j-1].getValue() == -1) cells[i][j].incrementValue();
                     }
                }
            }
        }
        /*This method starts chain reaction. When user click on particular cell, if cell is empty (value = 0) this
        method look for other empty cells next to activated one. If finds one, it call checkCell and in effect,
        start next scan on its closest area.
         */
        public void scanForEmptyCells(){
            for(int i = 0; i<side; i++){
                for(int j = 0; j<side; j++){
                    if(!cells[i][j].isNotChecked()){
                        if(j>=1 && cells[i][j-1].isEmpty()) cells[i][j-1].checkCell();
                        if(j<= limit && cells[i][j+1].isEmpty()) cells[i][j+1].checkCell();
                        if(i>=1 && cells[i-1][j].isEmpty()) cells[i-1][j].checkCell();
                        if(i<= limit && cells[i+1][j].isEmpty()) cells[i+1][j].checkCell();
                        if(i>=1 && j>= 1 && cells[i-1][j-1].isEmpty()) cells[i-1][j-1].checkCell();
                        if(i<= limit && j<= limit && cells[i+1][j+1].isEmpty()) cells[i+1][j+1].checkCell();
                        if(i>=1 && j<= limit && cells[i-1][j+1].isEmpty()) cells[i-1][j+1].checkCell();
                        if(i<= limit && j>= 1 && cells[i+1][j-1].isEmpty()) cells[i+1][j-1].checkCell();
                    }
                }
            }
        }


texts:
Here is my code for hacker rank question. Can somebody suggest improvement?

Question:

  We consider a word, to be beautiful if the following two conditions
  are satisfied:

  No two consecutive characters are the same.
  No two consecutive characters are in the following vowel set: a, e, i, o, u, y. Note that we consider y to be a vowel in this challenge.

Solution:

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

   public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String w = in.next();

        int result = isBeautiful(w);

        if (result == 1) {
            System.out.print("Yes");
        } else
            System.out.print("No");

    }

    static int isBeautiful(String w) {
        for (int i = 0; i < w.length() - 1; ++i) {
            if (w.charAt(i) == w.charAt(i + 1)) {
                return 0;
            }
            if ( ( isVowel(w.charAt(i)) == isVowel(w.charAt(i + 1)) && (isVowel(w.charAt(i)) == 1))) {
                return 0;
            }
        }
        return 1;
    }

    static int isVowel(char c) {
        if ( (c == 'a') || (c == 'e') || (c == 'i') || (c == 'o') || (c == 'u') || (c == 'y') ) {
            return 1;
        }
        return 0;
    }

}


texts: Simple neural network implementation in Python

texts:
A simple neural network I wrote in Python without libraries. I avoided implementing it in matrix form because I sought to get a basic understanding of the way NN's work first. For that reason I'm strongly favoring legibility over efficiency. I tried to keep my code readable and pyhonic, any style feedback would be particularly appreciated.

A quirk about this design is it does back propagation on a per training example basis and uses momentum to try and avoid over fitting to specific examples.
Also I realized I never added base values to the neurons, it seems to work alright with out them but if anyone has a more in depth understanding of why you'd want them I'd be curious to hear about that.

import math
import random

import data

def sigmoid(x):
    return 1 / (1 + math.exp(-x))

def sigmoid_prime(x):
    return x * (1.0 - x)

def loss(x,y):
    return sum([(a-b)**2 for (a,b) in zip(x,y)])

class Neuron():
    learning_rate = 0.015
    momentum_loss = 0.03

    def __init__(self, input_neurons):
        self.weights = [random.uniform(-1,1) for _ in range(input_neurons)]
        self.momentum = [0 for _ in range(input_neurons)]

    def forward(self, inputs):
        dot = sum([x*y for (x,y) in zip(inputs, self.weights)])
        self.output = sigmoid(dot)
        return self.output

    def backpropagate(self, inputs, error):
        error_values = list()
        gradient = error * sigmoid_prime(self.output)
        for i, inp in enumerate(inputs):
            self.nudge_weight(i, gradient * inp)
            error_values.append(self.weights[i]  * gradient)
        return error_values

    def nudge_weight(self, weight, amount):
        change = amount * Neuron.learning_rate
        self.momentum[weight] += change
        self.momentum[weight] *= (1 - Neuron.momentum_loss)
        self.weights[weight] += change + self.momentum[weight]

class Network():
    def __init__(self, topology):
        self.layers = list()
        for i in range(1,len(topology)):
            self.layers.append([Neuron(topology[i-1]) for _ in range(topology[i])])

    def forward(self, data):
        output = data
        for layer in self.layers:
            output = [neuron.forward(output) for neuron in layer]
        return output

    def backpropagate(self, data, output, target):
        error_values = [tval - output for (tval, output) in zip(target, output)]
        for i in range(len(self.layers)-1,0,-1):
            layer_output = [neuron.output for neuron in self.layers[i-1]]
            error_values = self.backpropagate_layer(i, error_values, layer_output)
        self.backpropagate_layer(0, error_values, data)

    def backpropagate_layer(self, layer, error_values, inputs):
        next_errors = list()
        for neuron, error in zip(self.layers[layer], error_values):
            bp_error = neuron.backpropagate(inputs,error)
            if not next_errors:
                next_errors = bp_error
            else:
                next_errors = [a+b for a,b in zip(next_errors,bp_error)]
        return next_errors

The full source code for project including the data base and some other testing code can be found here: https://github.com/RowanL3/Neural-Network


texts:
This works for the most part. I am very new to programming so be aware.

import java.util.*;
public class HangManP5
{
private static Scanner k;
public static void main(String[] args)
{
int attempts = 10;
int wordLength;
boolean solved;
k = new Scanner(System.in);

System.out.println("Hey, what's your name?");
String name = k.nextLine();
System.out.println(name+ ", hey! This is a hangman game! (Some answers have two words, usually the longer ones\n");
String word = getRandomWord();
int len = word.length();
char[] temp = new char[len];
for(int i = 0; i < temp.length; i++)
{
    temp[i] = '*';
}
System.out.print("\n");
System.out.print("Word to date: "+len+" letters.");
while (attempts <= 10 && attempts > 0)
{
    System.out.println("\nAttempts left: " + attempts);
    System.out.print("Enter letter: ");
    String test = k.next();
    if(test.length() != 1)
    {
        System.out.println("Please enter 1 character");
        continue;
    }
    char testChar = test.charAt(0);
    int foundPos = -2;
    int foundCount = 0;
    while((foundPos = word.indexOf(testChar, foundPos + 1)) != -1)
    {
        temp[foundPos] = testChar;
        foundCount++;
        len--;
    }
    if(foundCount == 0)
    {
        System.out.println("Sorry, didn't find any matches for " + test);
    }
    else
    {
        System.out.println("Found " + foundCount + " matches for " + test);
    }
    for(int i = 0; i < temp.length; i++)
    {
        System.out.print(temp[i]);
    }
    System.out.println();
    if(len == 0)
    {
        break; //Solved!
    }
    attempts--;
}
if(len == 0)
{
    System.out.println("\n---------------------------");
    System.out.println("You did iiiiiiit!");
}
else
{
    System.out.println("\n---------------------------");
    System.out.println("Better luck next time, you didn't get the word!");
    System.out.println("It was \"" + word + "\"");
}
}
public static String getRandomWord()
{
    switch(new Random().nextInt(5))
    {
        case 1:
            return "peace";
        case 2:
            return "nuts";
        case 3:
            return "dankmemes";
        case 4:
            return "fizz";
        case 5:
            return "awesome";
        default:
            throw new IllegalStateException("Something went wrong!");
    }
}
}


texts:
I just finished solving Project Euler's 50th problem, but it's awfully slow. I'd like to hear your thoughts on my code's efficiency and practices.
Problem Statement
The prime 41, can be written as the sum of six consecutive primes:
\$41 = 2 + 3 + 5 + 7 + 11 + 13\$
This is the longest sum of consecutive primes that adds to a prime below one-hundred.
The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953.
Which prime, below one-million, can be written as the sum of the most consecutive primes?
Code

let primeNumbers = [];

function isPrime(number) { // checks whether number is prime or not
    for(let i = 2; i <= number / 2; i++) { // stops checking at 1/2 of number
        if (number % i === 0) return false;
    }
    return true;
}

function storePrimes(count) {
    for(let i = 2; i < count; i++) { // starts at 2
        if (isPrime(i)) {
            primeNumbers.push(i);
        }
    }
}

function findLargestSum() {
    let termsCount = 0;
    let sumOfTerms = 0;

    primeNumbers.forEach(currentSum => { // keeps track of possible sum
        primeNumbers.forEach((startNumber, startIndex) => { // keeps track of start index
            let consecutiveCount = 0;
            let consecutiveSum = 0;
            primeNumbers.forEach((prime, primeIndex) => { // iterates through primes
                if (primeIndex >= startIndex) { // applies start index
                    consecutiveCount++;
                    consecutiveSum += prime;
                    if (consecutiveCount > termsCount && consecutiveSum === currentSum) {
                        termsCount = consecutiveCount;
                        sumOfTerms = consecutiveSum;
                    }
                }
            })
        })
    })

    return {largestSum: sumOfTerms, termsCount: termsCount};
}

function findPrimes(count) {
    storePrimes(count)
    let results = findLargestSum();
    console.log("Largest sum'o'primes of prime consecutives under " + count + " is: " + results.largestSum + " with " + results.termsCount + " terms.");
}

findPrimes(1000000);


texts:
So I semi-wrote directory size checker by copying some parts from Stackoverflow.
It works as follows:

Select a directory you want to check the size of subdirectories inside.
It goes scans all the directories inside the chosen directory. If there are also just files, that's not a problem the recursive function can deal with that as well.
It goes through every subdirectory and checks for the file size. If there's a permission problem, it returns -1 (this way we can easily tell which directories caused acces issues).
The directory name and it's "mass" gets stored in a dictionary.
The whole dictionary gets sorted.
Items that are +1GB get the "GB" tag, while the ones between 0 and 1 get the "MB" tag, just for better precision.
(I like to change between directories faster, so I added an option to give "r" as an input to scan for a second time. Closing the script and reopening it takes time imo)

Now I can see which folder is the biggest and which ones are empty, I don't know why but in Windows I need to go 1:1 and check each folder size individually, which I dislike a lot. This way I can check folders that contain hundreds of gigabytes in seconds.
I would like to know what I could have done better or what was obnoxious.
import os
from tkinter import *
from tkinter.filedialog import askdirectory

def Main():
    Tk().withdraw()  # use to hide tkinter window
    Dir = askdirectory(title="Select Folder")  # shows dialog box and return the path

    print("LOADING...")  # Sometimes it takes long to output results, this just indicates that the program is working and not broken
    sort_dict = Sorter(Dir)  # Give the directory as an input

    print("\n-SORTED-\n")
    for i in sort_dict:
        if i[1] > 1:  # continues using gigabytes
            fixed_float = float("{:.3f}".format(i[1]))
            data_type = "GB:   "
        elif i[1] < 0:  # no acces
            print(f"NO ACCES : {i[0]}")
            continue
        else:  # convert to megabytes
            mega_float = i[1] * 1024
            fixed_float = float("{:.3f}".format(mega_float))
            data_type = "MB:   "

        dflt_white_space = 8
        white_space = " " * (dflt_white_space - len(str(fixed_float)))
        print(f"{fixed_float}  {white_space + data_type + i[0]}")

    if input("\nPress 'r' to retry, press anything else to exit\n") == "r":
        Main()

def get_dir_size(Dir):  # Returns the `directory` size in bytes.
    total = 0
    try:
        for entry in os.scandir(Dir):  # print("[+] Getting the size of", directory)
            if entry.is_file():  # if it's a file, use stat() function
                total += entry.stat().st_size
            elif entry.is_dir():  # if it's a directory, recursively call this function
                total += get_dir_size(entry.path)
    except NotADirectoryError:  # if `directory` isn't a directory, get the file size
        return os.path.getsize(Dir)
    except PermissionError:  # if for whatever reason we can't open the folder, return -1
        return -1  # returns a negative size that will be visible (to use conditions) after the conversion
    return total

def get_subdirs(Dir):
    dir_array = []
    for x in os.listdir(Dir):
        dir_array.append(x)
    return dir_array

def Sorter(Dir):

    Dict = {}
    dir_array = get_subdirs(Dir)

    for x in range(len(dir_array)):
        file_size = float(get_dir_size(Dir + "\\" + dir_array[x])) / 1073741824  # Converts the bytes to GB

        Dict[dir_array[x]] = file_size

    sort_dict = sorted(Dict.items(), key=lambda x: x[1], reverse=True)
    return sort_dict

if __name__ == "__main__":
    Main()


texts:
I have two goroutines that each need to return their results to the main function. These results are of different types.

I have implemented a solution that uses a structure that holds these results. The structure is passed to the routines and each routine knows which field in the structure to use to save the results.

I am new to Golang and I am not sure if this is an elegant solution. Maybe channels are more suitable?

package main

import (
    "fmt"
    "sync"
)

type Results struct {
    x float64
    y int
}

func main() {
    var r Results
    var wg sync.WaitGroup

    wg.Add(2)

    go func(r *Results, wg *sync.WaitGroup) {
        defer wg.Done()
        r.x = 1.2
    }(&r, &wg)

    go func(r *Results, wg *sync.WaitGroup) {
        defer wg.Done()
        r.y = 34
    }(&r, &wg)

    wg.Wait()
    fmt.Println(r)
}

https://play.golang.org/p/XW1LccJvAn


texts:
I've used jQuery for a long time, and now I'm going to do some animations with vanilla JS. Here's my code so far:

var box = document.getElementById('box'),
    a1end,
    a2end,
    cdend,
    a3end,
    a4end,
    animate1 = setInterval(function() {
        if (box.style.top === (window.innerHeight - 120) + 'px') {
            clearInterval(animate1);
            a1end = true;
        }
        box.style.top = (
            +box.style.top.replace('px', '') + 1
        ) + 'px';
    }, 1),
    animate2 = setInterval(function() {
        if (box.style.left === (window.innerWidth - 120) + 'px') {
            clearInterval(animate2);
            a2end = true;
        }
        box.style.left = (
            +box.style.left.replace('px', '') + 1
        ) + 'px';
    }, 1);

checkEnd1(function() {
    box.style.background = 'greenyellow';
    box.innerText = 'Next stage starts in 5 seconds';
    var i = 4,
        cd = setInterval(function() {
            if (!i) {
                clearInterval(cd);
                cdend = true;
            }
            box.innerText = 'Next stage starts in ' + i + ' seconds';
            i--;
        }, 1000);

});
checkEnd2(function() {
    box.style.background = 'white';
    box.innerText = '';
    var animate3 = setInterval(function() {
        if (box.style.left === '20px') {
            clearInterval(animate3);
            a3end = true;
        }
        box.style.left = (
            +box.style.left.replace('px', '') - 1
        ) + 'px';
    }, 1);
});
checkEnd3(function() {
    var animate4 = setInterval(function() {
        if (box.style.top === '20px') {
            clearInterval(animate4);
            a4end = true;
        }
        box.style.top = (
            +box.style.top.replace('px', '') - 1
        ) + 'px';
    }, 1);
});
checkEnd4(function() {
    box.style.background = 'lightcyan';
    box.innerText = 'Animation complete';
});

function checkEnd1(fn) {
    (a1end && a2end) ? fn() : setTimeout(function() {
        checkEnd1(fn);
    }, 200);
}
function checkEnd2(fn) {
    (cdend) ? fn() : setTimeout(function() {
        checkEnd2(fn);
    }, 200);
}
function checkEnd3(fn) {
    (a3end) ? fn() : setTimeout(function() {
        checkEnd3(fn);
    }, 200);
}
function checkEnd4(fn) {
    (a4end) ? fn() : setTimeout(function() {
        checkEnd4(fn);
    }, 200);
}

jsFiddle demo

I've also noticed that the first animation isn't working as excepted. Out of curiousity, I tried it with jQuery's .animate() and it worked as excepted:

$('#box').animate({
    top: window.innerHeight - 120,
    left: window.innerWidth - 120
});

Note: please don't tell me to use jQuery or other libs, I want to use vanilla.

Bounty Edit

Currently, the animation goes diagonally for a while, then when it reaches the bottom, it continues to go sideways. If you tell me how to make it go diagonally all the time, I'll give you a bounty.


texts: Limit fgets input to up to a certain number of characters

texts:
This question is an extension of this other question from Stackoverflow.
The objective is to limit the input of characters read by fgets to up to a certain number of characters. And in the following code, that I've come up with as a solution, we are working with a limit of 10 characters as an example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char v[12];

    printf("Type a word with up to 10 chracters:\n");
    //Loop checks if fgets succeeded and if there is '\n' in the string:
    while (!fgets(v, 12, stdin) || strcspn(v, "\n") == 11){
        if(feof(stdin)) {
             printf("Error: End of file reached.\n");
             exit(EXIT_FAILURE);
        }
        printf("Error: The word is longer than 10 characters, try again.\n");
        for(int ch=getchar(); ch != '\n' && ch != EOF; ch=getchar());
        printf("Type a word with up to 10 chracters:\n");
    }
    v[strcspn(v, "\n")] = '\0';

    printf("%s\n", v);

    return 0;
}

It works as intended. However @chux-ReinstateMonica has pointed out that there may still be corner weaknesses and possible improvements to be made to this solution.
So, how can this code/solution be improved?


texts:
Background

I have decided to use this year's Advent Of Code to learn Haskell. I feel like I vaguely understand the language and can solve most of the problems with relative ease. However, the code I produce is not the most readable and possibly has inefficiencies. Any suggestions on how to improve readability and performance would be much appreciated.

Problem

The problem is Day 13 of AoC. It consists of a maze where each cell (x,y) is either a wall or an empty space, dictated by the population count of the following equation:

x*x + 3*x + 2*x*y + y + y*y + key (where key is some arbitrary integer)

The cell is a wall if the population count is odd. The problem then comes in two parts:

Find shortest distance between (1,1) and (31,39).
Find number of cells that can be visited in 50 or less steps (from (1,1)).

Code

The code uses BFS for both parts. I am aware that A* may quicker for Part1.

import Data.Bits (popCount)
import qualified Data.Map as Map
import Debug.Trace

-- Define all types
type Index = (Int, Int)                         -- (x,y)
type Edges = [Index]                            -- list of connecting edges
type Prob  = (Int, Int, Int)                    -- (key, width, height)
type State = (Index, Int, Map.Map Index Bool)   -- (current, steps, visited)

-- Determine if a specific cell index represents a wall
isWall :: Int -> Index -> Bool
isWall key (x,y) = odd $ popCount num
    where num = x*x+3*x+2*x*y+y+y*y+key

-- Generate all edges of a specific cell
mkEdges :: Int -> Index -> Edges
mkEdges key (x,y) = filter (not.isWall key) adjs
    where adjs = wB [(x, y-1), (x+1, y), (x,y+1), (x-1,y)]
          wB   = filter (\(a,b) -> not (a<0 || b<0))

-- Find the shortest path length
bfsPathLength :: Int -> Index -> [State] -> Int
bfsPathLength key goal t@((curr, steps, visited):rest)  | goal==curr = steps
                                                        | otherwise  = bfsPathLength key goal newStates
    where newStates         = (filter (not.isQueued) $ filter (not.isVisited) $ map mkStates $ mkEdges key curr) ++ rest
          mkStates s        = (s, steps+1, Map.insert curr True visited)
          isVisited (s,_,_) = Map.member s visited
          isQueued  (s,_,_) = elem s $ map (\(x,_,_) -> x) t

-- Calculate the number of reachable nodes from a starting position
bfsReachableLocations :: Int -> [(Int, Index)] -> [Index] -> Int
bfsReachableLocations key a@((lim,curr):rest) visited | lim <  0  = 0
                                                      | otherwise = 1 + bfsReachableLocations key newNodes (visited++[curr])
    where neighbours = filter (not.isQueued) $ filter (not.(\x -> elem x visited)) $ mkEdges key curr
          isQueued n = elem n $ map (\(_,x) -> x) a
          newNodes   = rest ++ map (\x -> (lim-1, x)) neighbours

main = do
    print $ bfsPathLength           1362 (31,39) [((1,1), 0, Map.empty)]
    print $ bfsReachableLocations   1362 [(50, (1,1))] []

The code is not as readable as I'd like. There are probably easier ways of performing some of the steps that I have no yet encountered on my short Haskell journey. Any recommendations would be appreciated.


texts:
I'm working to build out a Subscriber interface for handling at-least-once messaging semantics, so I can produce different brokers. Here's my interface thus far:

// AtLeastOnceSubscriber defines the interface for a subscriber with at-least-
// once message delivery semantics
type AtLeastOnceSubscriber interface {
    // Start creates a channel to the message broker for receiving messages
    Start(ctx context.Context) (<-chan AtLeastOnceMessage, <-chan error)
    // AckMessage will delete the given message from its respective message queue
    AckMessage(ctx context.Context, messageID string) error
    // ExtendAckDeadline will postpone resending the given in-flight message for
    // the specified duration
    ExtendAckDeadline(ctx context.Context, messageID string, newDuration time.Duration) error
}

// AtLeastOnceMessage contains the payload for a message with at-least-once
// delivery semantics
type AtLeastOnceMessage interface {
    // MessageID returns the ID that uniquely identifies this message. You can use
    // this to Ack or extend the ack deadline from the Subscriber
    MessageID() string
    // Message returns the payload from the message
    Message() []byte
    // ExtendAckDeadline extends the duration that a message can remain in-flight
    // before it will get added back to the message queue for redelivery. Call
    // this if processing the message will take longer than the existing time window.
    ExtendAckDeadline(time.Duration) error
    // Ack will signal to the message broker that this given message has been
    // processed and can be deleted
    Ack() error
}

A simple example implementation:

func (s *someConcreteImplementation) Start(ctx context.Context) (<-chan AtLeastOnceMessage, <- chan error) {
    iChan := make(chan AtLeastOnceMessage)
    eChan := make(chan error)
    go func() {
        defer close(iChan)
        defer close(eChan)
        for {
            select {
                case <-ctx.Done():
                    // do stuff to try to gracefully terminate
                    return
                default:
                    msg, err := s.getSomeThing()
                    if err != nil {
                        eChan <- err
                    } else {
                        iChan <- msg
                    }
            }
        }
    }()
    return iChan, eChan
}

A dumb example demonstration of using this interface:

ctx, cancel := context.WithCancel()
defer cancel()
c, e := myConcreteSubscriberImplementation.Start(ctx)
for {
    select {
        case msg, ok := <- c:
            if !ok {
                return // the channel has been closed
            }
            // .. do something with msg
        case err := <- e:
            fmt.Println(err)
            cancel() // probably do better stuff than this in the real world
    }
}

My main question

I've received a recommendation that my interface should expose a Stop() function to allow the caller to close the channel, but I feel like this is redundant because of the passed in context, which does the exact same thing.

Or, is this just a bad design?


texts:
I've made myself a JavaScript slider constructor. You can create new sliders and tell it what elements it should refer to.

var SliderControl = function (container, area, fill, action, actionWhenActive, actionWhenSet) {
    'use strict';
    var self = this;
    this.action = action;
    this.container = container;
    this.area = area;
    this.fill = fill;
    this.element = container.find(area);
    this.value = 0;
    this.active = false;
    this.actionWhenActive = actionWhenActive;
    this.actionWhenSet = actionWhenSet;
    $(document).on('mousemove', function (event) {
        self.move(event, self);
    });
    $(document).on('mouseup', function (event) {
        self.drop(event, self);
    });
    this.area.on('mousedown', function (event) {
        self.grab(event, self);
    });
};

SliderControl.prototype = {
    action: this.action,
    width: function () {
        'use strict';
        var calcWidth = ((this.value * 100) + '%');
        this.fill.width(calcWidth);
    },
    update: function (event, self) {
        'use strict';
        if (this.actionWhenActive === true) {
            this.action();
        }
        var direction, percent, container, area;
        direction = event.pageX - this.element.offset().left;
        percent = Math.min(Math.max(direction / this.element.width(), 0), 1.0);
        this.value = percent;
        this.width();
    },
    move: function (event, self) {
        'use strict';
        if (this.active === true) {
            this.update(event);
        }
    },
    grab: function (event, self) {
        'use strict';
        this.active = true;
        self.update(event);
        event.preventDefault();
    },
    drop: function (event, self) {
        'use strict';
        if (this.active === true) {
            this.active = false;
            this.action();
        }
    },
    setValue: function (value) {
        if (this.active === false) {
            this.value = value;
            this.width();
            if (this.actionWhenSet === true) {
                this.action();
            }
        }
    }
};

If you want to try it out, go here.

I think there's a better way to set a custom function it should run when you drop the slider (or if actionWhenActive is set to true, while you're dragging it) but I'm not sure what would be the most DRY way to do it.


texts: Project Euler problem 12: highly divisible triangular number

texts:
I am just a beginner in C++ and I tried solving this problem:

  What is the first number of the form 1 + 2 + 3 + … + n that has over five hundred factors?

But it seems my code is not that efficient because its taking ages to find the answer:

#include<iostream>
using namespace std;

void triNum(int);

int main()
{
    int res=0;
    for (int i=1;i<100000000;i++){
        res+=i;
        triNum(res);
    }
    cout<<endl;
}

void triNum(int n)
{
    int counter=0;
    for(int i=1;i<=n;i++){
        if(n%i==0){
            counter+=1;
        }
    }
    if(counter==500){
        cout<<n;
    }
}


texts: Keep database lookup in memory and get values in frequent

texts:
Is there a way to write it in more efficient and modern (Up to date design pattern) way?

 static Dictionary<string, Dictionary<string, string>> m_LUApplicationParams;
    public string LUApplicationParams(int applicationId, string GuidId, string variable)
            {
                if (m_LUApplicationParams == null)
                {
                    var blLU = new LU();
                    DataTable dt = new DataTable();
                    dt = blLU.GetLUApplicationVaribales(applicationId);

                    m_LUApplicationParams = new `Dictionary<string,Dictionary<string,string>>();`

                    for (int i = 0; i < dt.Rows.Count; i++)
                    {

                        if (!m_LUApplicationParams.ContainsKey(dt.Rows[i]["LangId"].ToString()))
                        {
                            m_LUApplicationParams.Add(dt.Rows[i]["LangId"].ToString(), new Dictionary<string, string>());
                        }

                        m_LUApplicationParams[dt.Rows[i]["LangId"].ToString()].Add(dt.Rows[i]["Variable"].ToString(), dt.Rows[i]["Content"].ToString());                                    }

                }

                return m_LUApplicationParams[GuidId].Where(y => y.Key == variable).FirstOrDefault().Value.ToString();
            }


texts:
I have a function that will try to find a bitmap within another bitmap.

If it successfully finds it, then it will return the center point of bitmap #1.

I've only seen negativity towards goto which is what this function relies on.

I would like some help optimizing my function and possibly having it work without the need of goto.

private static bool FindBitmap(Bitmap searchBitmap, Bitmap withinBitmap, out Point point)
{
    for (var outerX = 0; outerX < withinBitmap.Width - searchBitmap.Width; outerX++)
    {
        for (var outerY = 0; outerY < withinBitmap.Height - searchBitmap.Height; outerY++)
        {
            for (var innerX = 0; innerX < searchBitmap.Width; innerX++)
            {
                for (var innerY = 0; innerY < searchBitmap.Height; innerY++)
                {
                    var searchColor = searchBitmap.GetPixel(innerX, innerY);
                    var withinColor = withinBitmap.GetPixel(outerX + innerX, outerY + innerY);

                    if (searchColor.R != withinColor.R || searchColor.G != withinColor.G ||
                        searchColor.B != withinColor.B)
                    {
                        goto NotFound;
                    }
                }
            }
            point = new Point(outerX, outerY);
            point.X += searchBitmap.Width / 2; // Set X to the middle of the bitmap.
            point.Y += searchBitmap.Height / 2; // Set Y to the center of the bitmap.
            return true;

            NotFound:
            continue;
        }
    }
    point = Point.Empty;
    return false;
}


texts:
Can you please tell me how to improve this code?

<?php
 include 'configdb.php';

 if(($_SERVER['REQUEST_METHOD'] === 'POST') && !empty($_POST['email']) && !empty($_POST['password']))
 {
    $getUserData = getUserByEmail();
    if (mysqli_stmt_num_rows($getUserData) > 0)
    {
        die(
          '{
            "status":"1",
            "message":"Email Already Exists"
           }'
        );
    }
    else
    {
        insertUser();
        die('{
              "status":"0",
              "message":"Registration Successful"
          }');
    }
 }

  function insertUser()
  {
    $email = $_POST['email'];
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT);

    $insertData = mysqli_prepare($GLOBALS['connection'], "INSERT INTO users (emailID, password, com_code) VALUES(?,?,?)");

    if(false == $insertData)
    {
        handlePrepareStmtErrors("-1");
    }
    $bindParam = mysqli_stmt_bind_param($insertData, "sss", $email, $password, $com_code);
    if(false == $bindParam)
    {
        handlePrepareStmtErrors("-2");
    }
    $executeStmt = mysqli_stmt_execute($insertData);
    if(false == $executeStmt)
    {
        handlePrepareStmtErrors("-3");
    }
   }

   function getUserByEmail()
   {
    $getUserData = mysqli_prepare($GLOBALS['connection'],"SELECT emailID FROM users WHERE emailID = ?");
    if(false == $getUserData)
    {
        handlePrepareStmtErrors("-1");
    }
    $bindParam = mysqli_stmt_bind_param($getUserData,"s",$_POST['email']);
    if(false == $bindParam)
    {
        handlePrepareStmtErrors("-2");
    }
    $executeStmt = mysqli_stmt_execute($getUserData);
    if(false == $executeStmt)
    {
        handlePrepareStmtErrors("-3");
    }
    mysqli_stmt_store_result($getUserData);/*It Is Required To Get Number Of Rows By stmt_num_rows Method */
    return $getUserData;
   }

   function handlePrepareStmtErrors($code)
   {
    switch((String)$code)
    {
        case "-1":
            die('{
                "status":"-1",
                "message":"Statement prepare error"
            }');

        case "-2":
            die('{
                "status":"-1",
                "message":"Parameter binding error"
            }');
        case "-3":
            die('{
                "status":"-1",
                "message":"Statement execution error"
            }');
      }
    }
   ?>

Things about which I am not sure:

I read that MySQLi prepare statements will prevent SQL injections. Is there any possibility to hack my db by my design?
I am planning to create a utils.php and will add handlePrepareStmtErrors function there. In that function, I am exiting the scripts if any errors are there. So only I am not using break statement there because it will not get executed. Is it right way?
I feel like my functions are not properly written, but it does what I want. I tried and registration is successful.


texts: Generate all valid combinations of n pair of parentheses

texts:
Implement an algorithm to print all valid (e.g. properly opened and
  closed) combinations of n pair of parentheses.

Following is my implementation and I think it works. Is the algorithm efficient? Do you see any coding issues?

def compute_all_parens (n, left, right, s):
    if right == n:
        print (s)
        return
    if left < n:
        compute_all_parens(n, left+1, right, s + "(")
    if right < left:
        compute_all_parens(n, left, right+1, s + ")")

# call syntax: compute_all_parens(5, 0, 0, "")


texts: Checking if multiple user-entered numbers are in the right range

texts:
str, ski = int(input("text here")), int(input("text here"))

    if str < 1 or str > 50 or ski < 1 or ski > 50:
        print("did not enter between 1 and 50")

Is there anyway to shorten the if statement in that code? I find that it is a bit too long, but I don't really know how to shorten it.

Any suggestions?


texts:
I'm creating a responsive page with bootstrap. I tested my code with my browser (Firefox and Chrome) and it works. Is the code clean or is there a better way to code it?

<%= name %>

<%= adresse %>

        <button class="btn btn-default btn-block" type="submit">Choose Address</button>

            <button class="btn-xs btn-default btn-block" id="editBtn" type="submit">Edit</button>

            <button class="btn-xs btn-warning btn-block" id="delBtn" type="submit">Delete</button>


texts:
I have been trying to pick Haskell back up so I decided to try to implement binary search as practice. I am aware that binary search in Haskell in inefficient because Haskell's lists are implemented as linked lists, but I wanted to try it anyway. I would love to know how I could improve this or how it could be more idiomatic, thanks!

search :: (Ord a) => a -> [a] -> Maybe Int
search _ [] = Nothing
search n h
  | elem == n = Just index
  | elem < n = (+index) . (+1) <$> (search n $ drop (index+1) h)
  | otherwise = search n $ take index h
  where index = length h `quot` 2
        elem = h !! index


texts: Searching for many different names in a Panda frame

texts:
Consider the following example code:
c1 = ["Mary herself","Mary is mine","John himself","John is mine","Alan himself","Alan is mine"]
s1 = pd.Series(c1)
c2 = [1,2,3,4,5,6]
s2 = pd.Series(c2)

dictionary = {"A":s1,"B":s2}

df = pd.DataFrame(dictionary)
print(df)
for i in range(6):
  name = df["A"].iloc[i]
  if "Mary" in name:
    print(name)
  if "Alan" in name:
    print(name)
  else:
    print("no")

I want to filter strings that include "Mary" or "Alan". My solution works well for only two cases, but I wonder if there is a more suitable solution for a lot more cases. For example, if I want to filter "John" and "Brown" too, I would already need four if statements.
How can I improve my code so I wouldn't have to add a new if statement for each name I want to filter?


texts: Data structure and movement for tilt maze

texts:
This is a design data structure and movement for a tilt maze. For example, this one.

My major idea is to divide into Ball, Maze, HorizontalWall and VerticalWall classes. Ball is the core class which operates on Maze, HorizontalWall and VerticalWall.

I feel my code is a bit inefficient since each time, I need to enumerate all vertical or horizontal walls, for move right/left/up/down. I'm not sure if there's a more efficient way to represent the data structure and movement implementation.

class VerticalWall: # something like |
    def __init__(self, x, y1, y2):
        self.x=x
        self.y_start = y1
        self.y_end = y2

class HorizontalWall: # soemthing like --
    def __init__(self, x1, x2, y):
        self.x_start = x1
        self.x_end = x2
        self.y = y

class Ball:
    def __init__(self, top, left, maze):
        self.top = top
        self.left = left
        self.maze = maze
    def moveRight(self):
        x_location=[]
        y_location=[]
        for i in maze.vertical_wall:
            x_location.append(i.x)
            y_location.append(i.y_start)
        while True:
            for i,x in enumerate(x_location):
                if self.left + 1 == x and y_location[i] == self.top: # met with a vertical wall
                    return
            if self.left+1==self.maze.width: # border
                    return
            else:
                self.left += 1
    def moveLeft(self):
        x_location=[]
        y_location=[]
        for i in maze.vertical_wall:
            x_location.append(i.x)
            y_location.append(i.y_start)
        while True:
            for i,x in enumerate(x_location):
                if self.left == x and y_location[i] == self.top: # met with a vertical wall
                    return
            if self.left == 0: # border
                return
            else:
                self.left -= 1
    def moveUp(self):
        x_location=[]
        y_location=[]
        for i in maze.horizontal_wall:
            x_location.append(i.x_start)
            y_location.append(i.y)
        while True:
            for i,x in enumerate(x_location):
                if self.left == x and y_location[i] == self.top: # met with a vertical wall
                    return
            if self.top == 0: # border
                return
            else:
                self.top -= 1
    def moveDown(self):
        x_location=[]
        y_location=[]
        for i in maze.horizontal_wall:
            x_location.append(i.x_start)
            y_location.append(i.y)
        while True:
            for i,x in enumerate(x_location):
                if self.left == x and y_location[i] == self.top+1: # met with a vertical wall
                    return
            if self.top + 1 == self.maze.height: # border
                return
            else:
                self.top += 1

class Maze:
    def __init__(self, height, width, target_x, target_y):
        self.height = height
        self.width = width
        self.target_x=target_x
        self.target_y=target_y
        self.horizontal_wall=[]
        self.vertical_wall=[]

if __name__ == "__main__":
    # https://www.mathsisfun.com/games/tilt-maze.html
    maze = Maze(5,5,4,4)
    maze.horizontal_wall.append(HorizontalWall(1, 2, 1))
    maze.horizontal_wall.append(HorizontalWall(4, 5, 2))
    maze.horizontal_wall.append(HorizontalWall(2, 3, 3))
    maze.horizontal_wall.append(HorizontalWall(1, 2, 4))
    maze.horizontal_wall.append(HorizontalWall(4, 5, 4))

    maze.vertical_wall.append(VerticalWall(3, 0, 1))
    maze.vertical_wall.append(VerticalWall(1, 2, 3))
    maze.vertical_wall.append(VerticalWall(3, 4, 5))

    ball = Ball(0,0,maze)
    print ('current location ', ball.top, ball.left)
    ball.moveRight()
    print ('current location ', ball.top, ball.left)
    ball.moveDown()
    print ('current location ', ball.top, ball.left)
    ball.moveLeft()
    print ('current location ', ball.top, ball.left)
    ball.moveUp()
    print ('current location ', ball.top, ball.left)


texts:
I'm wondering if anyone can code review my code below.  That's the core code of my little framework for bash in GitHub.

## ==========================================================================================
## FUNCTION : autoload_functions
## PURPOSE  : To check functions that are required, try to autoload them if NOT YET defined
##
## INPUT: array of $req_func
## OUTPUT: exit 1 - if any required function cannot be autoloaded (meaning, not found in standard
##          library location.
## ==========================================================================================
autoload_functions()
{
    local req_func=$*
    local ret_val=0

    ## check first parameter. If it's a directory, then
    ## it is where functions should be loaded from
    local new_libdir=$1
    [[ -d $new_libdir ]] && {
      shift
      LIB_DIR=$new_libdir
     }

    req_func=$* ## redeclare

    ## iterate through all $req_func, set $ret_val to 1
    ## if any required function cannot be autoloaded
    for each_func in $req_func; do
        func_name=`basename $each_func`
        ## if function undefined, try to auto-include (reference from specified location)
        type $func_name &> /dev/null || source $LIB_DIR/${each_func}.bash.inc

        ## recheck, ensure it has been defined.
        type $func_name &> /dev/null || (echo "ERROR: Missing required ${each_func}"; ret_val=1)
    done

    ## abort (exit 1) if any required func cannot be autoloaded
    [ $ret_val -eq 1 ] && exit $ret_val
} ## END: autoload_functions()


texts: Allow changing the properties of a mutable controller in a thread safe way

texts:
I have a (control engineering) controller. These controllers usually need several parameters to do their thing, and in my application it is desirable that these parameters can be changed while the controller is running - in a thread safe and well defined manner.

I came up with this design (extremely simplified):

// This is the class that the user instanciates.
public class Controller
{
    public ControllerInfo Info { get; set; }

    public void Start() { ... }
    public void Stop() { ... }

    private ControllerBody body = new ControllerBody();

    private void ControllerThreadProc()
    {
        while (true)
        {
            var elapsedTime_ms = ...;
            var currentInfo = this.Info;
            // the actual calculation is done in another class
            this.body.SingleStep(currentInfo, elapsedTime_ms);
            Thread.Sleep(currentInfo.SampleTime_ms);
        }
    }
}

// This exists as a separate class so it is possible to test the
// mathematical model without having to do it in real-time.
public class ControllerBody
{
    public void SingleStep(ControllerInfo info, long elapsedTime_ms)
    {
        var referenceValue = info.ReferenceValueGetter();
        var calculationResult = math;
        info.ControlValueSetter(calculationResult);
    }
}

// Immutable class that contains all the info necessary to do stuff.
public class ControllerInfo
{
    public Func<double> ReferenceValueGetter { get; private set; }
    public Action<double> ControlValueSetter { get; private set; }
    public int SampleTime_ms { get; private set; }
    public double SomeConstant { get; private set; }
    public double OtherConstant { get; private set; }
    ...

    public ControllerInfo(/* 1 argument per property :( */) { /* many assignments */ }
}

Usage example:

var controller = new Controller();
controller.Info = new ControllerInfo(/* values */);
controller.Start();
// later:
controller.Info = new ControllerInfo(/* new values */);
// Application is done:
controller.Stop();

Again, it should be possible to change the controller while it is running. Therefore I gave Controller a publicly settable ControllerInfo.

However, if the user decides to change the values of SomeConstant and OtherConstant in this example, it must be guaranteed that no calculation step is executed where only one of these are changed. In other words, changing a bunch of parameters must be an atomic operation. That's why ControllerInfo is not mutable.

I have identified 2 downsides to this architecture:

If I add another mathematical constant to ControllerInfo, I have to add (1) a property, (2) a parameter to the constructor (can be forgotten even if (1) has been done!), and (3) an assigment inside the constructor (can be forgotten even if (1) and (2) have been done!).
If the user wants to change a parameter while the controller is running, they must make another tedious constructor call, passing in values that have changed, as well as values that haven't changed.

To get around the usability problem, I considered introducing a ControllerInfoFactory class, which is basically a mutable copy of ControllerInfo:

public class ControllerInfoFactory
{
    public (SamePropertiesAsControllerInfo) { get; set; }

    public ControllerInfo CreateControllerInfo()
    {
        return new ControllerInfo(/* pass all parameters from this */);
    }
}

However, that makes the first problem even worse: For each property, I now also have to add the property to ControllerInfoFactory. Luckily, this time it's not possible to forget updating the CreateControllerInfo method as long as the ControllerInfo constructor has already been updated.

Now to code review:

Does this design make sense? Is the usability OK?
Can the large amount of repetitive code per property be reduced?


texts:
I have two collections that I want to retrieve from the database and associate with each other. My solution works, however I know it isn't the most elegant one. Do you have any suggestions on how to improve the algorithm?

Classes:

 public class JobAnnouncement : IDbEntity
{
    public int Id { get; set; }
    public JobAnnouncementPosition Position { get; set; }
    public int PositionId { get; set; }
    public DateTime From { get; set; }
    public DateTime To { get; set; }
    public bool IsDeleted { get; set; }
    [Required]
    public string PositionNameAdvertised { get; set; }
    public int? PortalId { get; set; }
    public JobAnnouncementPortal Portal { get; set; }
    public string OtherPortal { get; set; }
    public int? UserId { get; set; }
    public PragisUser User { get; set; }
    [Required]
    public DateTime From { get; set; }
    [Required]
    public DateTime To { get; set; }
    public int ReceivedCvCount { get; set; }
    public int InterviewedCount { get; set; }
    public int RecruitedCandidatesCount { get; set; }
    public string Comment { get; set; }
}
public class JobAnnouncementPosition
{
    public int Id { get; set; }
    public ICollection<JobAnnouncement> JobAnnouncements { get; set; }
     public ICollection<JobAnnouncementDocumentInfo> DocumentsInfo { get; set; }
    public PragisUserType PragisUserType {get;set;}
    [Range(1, int.MaxValue)]
    public int? TeamId { get; set; }
    public Team Team { get; set; }

    [Range(1, int.MaxValue)]
    public int? TechnologyId { get; set; }
    public JobAnnouncementTechnology Technology { get; set; }
    public string OtherTechnology { get; set; }

    [Range(1, int.MaxValue)]
    public int? LevelId { get; set; }
    public JobAnnouncementLevel Level { get; set; }
    public bool IsDeleted { get; set; }
     [NotMapped]
    public int JobAnnouncementsCount
    {
        get
        {
            return JobAnnouncements != null ? JobAnnouncements.Count : 0;
        }
    }
    }

Repository returning all positions that are not deleted with all associated announcements that are not deleted. I was not able to return all data on one database call as the condition of IsDelted for child entity announcements was not checked and I always got all announcements back, no matter if they were or weren't deleted.

I made two calls and then iterated over them assigning announcements to positions again:

 public IEnumerable<JobAnnouncementPosition> GetForListActive()
    {
        var announcements = _context.JobAnnouncements
            .Include(a => a.Portal)
            .Where(a => a.To.Day >= DateTime.Now.Day)
            .Where(a => a.IsDeleted == false)
            .ToList();

        var positions = _context.JobAnnouncementPositions
            .Include(a => a.Team)
            .Include(a => a.Level)
            .Include(a => a.Technology)
            .Include("DocumentsInfo.Document")
            .Where(p => p.IsDeleted == false)
            .ToList();

        foreach (var announcement in announcements)
        {
            foreach (var position in positions)
            {
                if (announcement.PositionId == position.Id)
                {
                    position.JobAnnouncements.Add(announcement);
                }
            }
        }

        var result = new List<JobAnnouncementPosition>();
        for (var i = 0; i < positions.Count; i++)
        {
            if (positions[i].JobAnnouncements != null)
            {
                result.Add(positions[i]);
            }
        }

        return result;

    }


texts:
Is it a good practice to separate Logic from Request controller in an Api ?

Without separation:

@app.mod_portal.bp.route('scan', methods=['GET'])
@login_required
def scan_all():
    print(vars(app.mod_portal.bp))

    portals = Portal.get_all(g.user.id)
    for portal in portals:
        scan(portal.id) # check for json error here

    return make_response(jsonify({'status': 'ok'}), 200)

@app.mod_portal.bp.route('<id>/scan', methods=['GET'])
@login_required
def scan(id):
    portal = Portal.get(id)

    datasets = extract_dataset_from_portal(portal.url)
    Dataset.delete_all(portal.id)

    for dataset in datasets:
        Dataset.create(dataset, portal.id)

    return make_response(jsonify({'status': 'ok'}), 200)

With separation

def logic_scan(id):
    portal = Portal.get(id)
    datasets = extract_dataset_from_portal(portal.url)
    Dataset.delete_all(portal.id)

    for dataset in datasets:
        Dataset.create(dataset, portal.id)

@app.mod_portal.bp.route('scan', methods=['GET'])
@login_required
def scan_all():

    portals = Portal.get_all(g.user.id)
    for portal in portals:
        try:
            logic_scan(portal.id)
        except # check error here

    return make_response(jsonify({'status': 'ok'}), 200)

@app.mod_portal.bp.route('<id>/scan', methods=['GET'])
@login_required
def scan(id):
    try:
      logic_scan(id)
    except # check error here
    return make_response(jsonify({'status': 'ok'}), 200)

Maybe the second example is better because I can handle different type of exception and return a different error message. What is the standard for that ? In case of separation, do you create another file for that ? like apiname_controller.py and apiname_logic.py or something like that ?


texts: Managing exceptions in aiohttp using consumer-producer pattern

texts:
I implemented a simple producer-consumer where producer produces links to fetch and several workers consume those URLs and return write data into response queue. Unfortunately, sometimes API can start responding 400-x errors and in that case we need to sleep each for some time. I have implemented it using a queue where I put not only an url, but also time to sleep in case some error happened.

class Producer(object):
    def __init__(self, url_queue, total_urls=15):
        self.url_queue = url_queue
        self.total_urls = total_urls

    async def run(self):
        count = 0
        choices = ['blah-%s' % i for i in range(15)]
        while count < self.total_urls:
            await self.url_queue.put(('http://localhost:8080/%s' % choices[count], 0))
            count += 1
            logging.info("Count: %s", count)
            if count % 1000 == 0:
                await asyncio.sleep(1)

class DownloadWorker(object):
    def __init__(self, url_queue: asyncio.Queue,
                 response_queue: asyncio.Queue):
        self.url_queue = url_queue
        self.response_queue = response_queue
        self.count = 0

    async def run(self):
        async with aiohttp.ClientSession() as session:
            while True:
                url, wait = await self.url_queue.get()
                if wait:
                    logging.info("Sleeping for %s ", wait)
                    await asyncio.sleep(wait)

                async with session.get(url) as resp:
                    try:
                        content = await resp.json()
                        await self.response_queue.put(content)
                        logging.info("Content %s", content)
                    except:
                        self.url_queue.put_nowait((url, 3.))
                        logging.exception('Error processing message')
                    finally:
                        self.url_queue.task_done()

And here is the code for running producer-worker:

  async def worker_pattern(worker_count):
    response_queue = asyncio.Queue()
    url_queue = asyncio.Queue()

    producer = Producer(url_queue)
    producers = [
        asyncio.create_task(producer.run())
    ]

    consumers = []
    for i in range(worker_count):
        worker = DownloadWorker(url_queue, response_queue)
        consumers.append(asyncio.create_task(
            worker.run()
        ))
    await asyncio.gather(*producers)

    await url_queue.join()

    for c in consumers:
        c.cancel()
    return response_queue


texts: Delete lines from a CSV file that contain fields listed in a text file

texts:
I wrote a powershell script to compare words from a text-file with a csv-column. If the word in the column matches, the line is deleted.

$reader = [System.IO.File]::OpenText($fc_file.Text)
try {
    for() {
        $line = $reader.ReadLine()
        if ($line -eq $null) { break }
        if ($line -eq "") { break }
        # process the line
        $fc_suchfeld = $fc_ComboBox.Text
        $tempstorage = $scriptPath + "\temp\temp.csv"
        Import-Csv $tempfile -Delimiter $delimeter -Encoding $char | where {$_.$fc_suchfeld -notmatch [regex]::Escape($line)} | Export-Csv $tempstorage -Delimiter $delimeter -Encoding $char  -notypeinfo
        Remove-Item $tempfile
        Rename-Item $tempstorage $tempfile_ext
    }
}
finally {
    $reader.Close()
}

My code works great, but it is very slow, due to saving and copying the csv file after every line. Is there a way to improve it?


texts: Using properties efficiently in inheritance

texts:
I have a class called Mailer which has some properties like this

public static string Cname
{
   get
   {
      return HttpUtility.HtmlDecode(HttpContext.Current.Server.UrlDecode(HttpContext.Current.Request["cname"]));
   }
   set
   {
      HttpUtility.HtmlDecode(HttpContext.Current.Server.UrlDecode(HttpContext.Current.Request["cname"]));
   }
}

I am inheriting this property from another class called EventRegistrationReplyMail
like this

public class EventRegistrationReplyMail :Mailer

and using Cname property inside this class. I doubt whether this is the correct way of doing things or not. I am just a beginner in OOP concepts, so please spare me if I am doing anything completely stupid.


texts: Part 2: Create or update record via HTTP request

texts:
This script was previously reviewed here: Part 1: Create or update record via HTTP request
I've made the changes that were suggested by @Reinderien.
Now that the code has been significantly refactored, are there any other improvements that could be made?

Description:
I have an external system that sends an HTTP request to a Jython script (in IBM's Maximo Asset Management platform).
The Jython 2.7.0 script does this:

Accepts an HTTP request: http://server:port/maximo/oslc/script/CREATEWO?_lid=wilson&_lpwd=wilson&f_wonum=LWO0382&f_description=LEGACY WO&f_classstructureid=1666&f_status=APPR&f_wopriority=1&f_assetnum=LA1234&f_worktype=CM
Loops through parameters:

Searches for parameters that are prefixed with f_ ('f' is for field-value)
Puts the parameters in a list
Removes the prefix from the list values (so that the parameter names match the database field names).

Updates or creates records via the parameters in the list:

If there is an existing record in the system with the same work order number, then the script updates the exiting record with the parameter values from the list.
If there isn't an existing record, then a new record is created (again, from the parameter values from the list).

Finishes by returning a message to the external system (message: updated, created, or other (aka an error)).

from psdi.mbo import SqlFormat
from psdi.server import MXServer
from psdi.mbo import MboSet

IGNORE_RULES = 2L

params = [
    param for param in request.getQueryParams()
    if param.startswith('f_')
]
paramdict = {
    p[2:]: request.getQueryParam(p)
    for p in params
}
resp=''
woset = MXServer.getMXServer().getMboSet("workorder",request.getUserInfo())

try:
    #Prevents SQL injection
    sqf = SqlFormat("wonum=:1")
    sqf.setObject(1,"WORKORDER","WONUM",request.getQueryParam("f_wonum"))
    woset.setWhere(sqf.format())
    woset.reset()
    woMbo = woset.moveFirst()

    if woMbo is None:
        woMbo=woset.add()
        verb = 'Created'
    else:
        verb = 'Updated'

    for k,v in paramdict.items():
        woMbo.setValue(k,v,2L)
    resp = verb + ' workorder ' + request.getQueryParam("f_wonum")
    woset.save()
    woset.clear()
    woset.close()
finally:
    woset.close()

responseBody = resp


texts: use regex to separate a list of serial numbers into multiple lists with matched prefix

texts:
The question comes from How to separate a list of serial numbers into multiple lists with matched prefix? on Stack Overflow.
Input:

sn = ['bike-001', 'bike-002', 'car/001', 'bus/for/001', 'car/002', 'bus/for/002']

Intended output:

# string with same prefix will be in the same list, e.g.:

sn1 = ['bike-001', 'bike-002']
sn2 = ['car/001', 'car/002']
sn3 = ['bus/for/001', 'bus/for/002']

The original thread already had a brilliant answer using .startswith(<sub_str>), however I still want to use regex to solve the question.
Here's what I've tried: I use re.sub() to get the prefix and re.search() to get the 3-digits serial number. I'd like to know if there is a better way (like using one-time regex function) to get the solution.
import re

sn = ['bike-001', 'bike-002', 'car/001', 'bus/for/001', 'car/002', 'bus/for/002']
sn_dict = {}
for item in sn:
    category = re.sub(r'\d{3}', "", item)
    number = re.search(r'\d{3}', item).group()
    if category not in sn_dict.keys():
        sn_dict[category] = []
    sn_dict[category].append(category + number)

After running the script we will have the following sn_dict:
{
    'bike-': ['bike-001', 'bike-002'],
    'car/': ['car/001', 'car/002'],
    'bus/for/': ['bus/for/001', 'bus/for/002']
}


texts: Vigenère Cipher problem in competitive programming

texts:
I've just started doing programming problems.
https://icpcarchive.ecs.baylor.edu/external/58/p5880.pdf
The code below works fine, but my run time is 2.715 seconds and the time limit is 3 seconds.
How can I improve speed of this code?
I've already started to use sys.stdin instead of input().
import string
import sys

while True:
    key = sys.stdin.readline().strip()
    key = int(key) if key.isdigit() else key
    if key == 0: break

    decrypted_msg = sys.stdin.readline().strip()
    decrypted_msg = int(decrypted_msg) if decrypted_msg.isdigit() else decrypted_msg
    if decrypted_msg == 0: break

    key = (len(decrypted_msg)//len(key) + 1) * key
    key = key[0:len(decrypted_msg)]

    encrypted_msg = ""

    for i in range(len(decrypted_msg)):
        key_idx = string.ascii_uppercase.index(key[i])
        deciphered_idx = string.ascii_uppercase.index(decrypted_msg[i])

        enciphered_idx = (deciphered_idx + key_idx + 1) % len(string.ascii_uppercase)
        encrypted_msg += string.ascii_uppercase[enciphered_idx]

    print(encrypted_msg)


texts: Changing a div that contains a view link

texts:
I've written some code to load a section of my application between views. While my code works, I'm wondering if there is a better way to do it. (partial views perhaps?) I currently load the views, then show/hide them depending on a button click.

@*Sidebar*@
@Html.Partial("_AdministrationSidebar")

@*PAGE CONTENT*@

@*page-content-wrapper*@

@*wrapper End*@


texts:
https://www.spoj.com/problems/ADDREV/

My answer to ADDREV challenge on SPOJ (link to the problem given above), written in JAVA, was accepted. However, the timing was 1.23 and memory used was 82M, which doesn't seem impressive/up-to-the-mark.

I'm new to competitive programming and want to know -
a. In what ways can I optimize my code to take up lesser memory and be quicker?
b. Are their any incorrect programming practices that I have unknowingly followed?
c. Which better way is available to solve this problem in Java?

My code:-

import java.util.*;
import java.lang.*;
import java.math.BigInteger;

class Main
{
    public static void main (String[] args) throws java.lang.Exception
    {
        Scanner obj = new Scanner(System.in);
        int t = obj.nextInt(); obj.nextLine(); //clears the buffer
        for(int i=1;i<=t;++i)
        {
            Scanner obj1 = new Scanner(obj.nextLine());

            StringBuffer b1 = new StringBuffer(obj1.next());
            StringBuffer b2 = new StringBuffer(obj1.next());

            b1.reverse(); b2.reverse();

            BigInteger i1 = new BigInteger(b1+"");
            BigInteger i2 = new BigInteger(b2+"");
            i1 = i1.add(i2);
            b1 = new StringBuffer(i1.toString());
            b1.reverse();
            String a = new String(b1.toString());

            for(int j=0;;j++) //To remove leading zeroes (if any)
            {
                if(a.charAt(j)!='0')
                {
                    System.out.println(a.substring(j));
                    break;
                }
            }
        }
    }
}


texts:
What I'm trying to achieve is to group all sub-arrays, which are connected (sharing the same elements) into one array.
So here is an example:

Input: [[1, 17], [3, 5], [5], [1, 3], [7], [2], [9, 8], [7, 2]];

What I am expecting to get: [[ 1, 3, 5, 17 ], [ 2, 7 ], [ 8, 9 ]]

Indexes of arrays, that are related:

0, 1, 2, 3
4, 5, 7
6

My code does what's needed, but my gut tells me that performance, amount of iterations and readability of the code can be improved, especially because it will be run on pretty long arrays.

So here is what I have:

const input = [[1, 17], [3, 5], [5], [1, 3], [7], [2], [9, 8], [7, 2]];

let i = 0;

const mergeIntersections = (array) => {
  const arrayClone = [].concat(array);
  let intersectionFound;
  let currIntersections = [];

  arrayClone.forEach(() => {
    /**
     * Subarray, which elements we'll look for
     * Removing it from the source array so it does not disturb us
     */
    const wanted = arrayClone.shift().sort((a, b) => a - b);

    /*
     * Preserving the length of the source array
     */
    arrayClone.push([]);

    let intersections = [].concat(wanted);

    wanted.forEach((wantedElement) => {
      arrayClone.forEach((arr, arrIndex) => {
        if (~arr.indexOf(wantedElement)) {
          intersections = intersections.concat(arr);
          intersectionFound = true;
          arrayClone[arrIndex] = [];
        }
        i++;
      });
    });

    if (intersectionFound) {
      currIntersections.push(Array.from(new Set(intersections)));
    } else {
      currIntersections = array;
    }

    currIntersections = currIntersections.filter(item => item.length);
  });

  if (intersectionFound) {
    return mergeIntersections(currIntersections);
  }
  return currIntersections;
};

console.log('result: ', JSON.stringify(mergeIntersections(input)));
console.log('amount of iterations: ', i);


texts: Project Euler problem 37: truncatable primes

texts:
I am working on Project Euler problem 37 and I have the following program:

#!/usr/bin/ruby -w

require 'prime'
h=11
y=0
x=0
while x < 11
    if h.prime? == true
        boo = true
        f=0
        n=h
        c=0
            while n > 0
                f += (n%10) * 10**(10-c)
                n/=10
                boo = false if n.prime? == false && n != 0
                c+=1
            end
            n=h
            c=10
            while c > 0
            n = n % (10**c)
            boo = false if n.prime? == false && n != 0
            c-=1
            end
        f /= 10 while f % 10 == 0
        if boo == true
            y+=h
            x+=1
            p h
        end
    end
h+=2
end
p y

It's designed to catch all of the eleven truncatable primes and does a good job of it, it catches the first ten is under one second, but it takes forty-nine seconds to find the last one, which happens to be, admittedly, a much larger number than the rest, is there any way to speed this up so that the eleventh one does not take so much time?


texts:
Please help me to simplify the script below. It has a lot of variables and a lot of values are getting assigned to them. Can I make it simpler?

It has to calculate the percentage of 3 test forms: pre, post and final.

DECLARE @tablefinal TABLE
(
    RowID1 INT IDENTITY(1,1),
    _CourseIDD int null,
    _courseName varchar(1000) null,
    _PRE INT NULL,
    _POST int null,
    _Feedback int null,
    _final int NULL,
    _Per decimal(18,2) null
)

DECLARE @rowCount INT,
        @currentRow INT,
        @@@CourseID INT,
        @@@CourseName varchar (1000)  --,  @STUDENT_ID int = 1078

DECLARE @tableCourse TABLE
(
    RowID INT IDENTITY(1,1),
    _COURSE_ID INT NULL,
    _COURSE_NAME varchar (1000) NULL
)

INSERT INTO @tableCourse (_COURSE_ID , _COURSE_NAME)
SELECT  COURSE_ID,
        COURSE_NAME
FROM DLC_COURSE C
WHERE COURSE_ID IN
(
    SELECT CS.COURSESHD_COURSE_ID
    FROM DLC_COURSE_SCHEDULE CS
    INNER JOIN DLC_STUDENT_PAYMENT SP ON
        CS.COURSESHD_ID = SP.STUDENT_PAYMENT_COURSESHD_ID
    WHERE SP.STUDENT_PAYMENT_STUDENT_ID = @STUDENT_ID
    AND CS.COURSESHD_STATUS=1
)
AND C.COURSE_STATUS=1

SELECT  @rowCount = @@RowCount,
        @currentRow = 1

WHILE @currentRow<=@rowCount
BEGIN
    SELECT  @@@CourseID = _COURSE_ID,
            @@@CourseName = _COURSE_NAME
    FROM @tableCourse
    WHERE RowID = @currentRow

    --do activity
    --select @@@CourseID as CID, @@@CourseName as CN
    SET @currentRow = @currentRow + 1

    DECLARE @@Pre INT = 0,
            @@Course INT = 0,
            @@Post INT = 0,
            @@Feedback INT = 0,
            @@Final INT = 0

    SELECT @@Pre = Count(*)
    FROM DLC_ASSESSMENT_RESULT
    WHERE RESULT_STUDENT_ID = @STUDENT_ID
    AND RESULT_COURSE_ID = @@@CourseID
    AND RESULT_STATUS='Pass'
    AND RESULT_ASSESSMENT_TYPE=2

    SELECT @@Course = ISNULL(COUNT(C.COURSE_ID),0)
    FROM DLC_COURSE C
    WHERE COURSE_ID IN
    (
        SELECT CS.COURSESHD_COURSE_ID
        FROM DLC_COURSE_SCHEDULE CS
        INNER JOIN DLC_STUDENT_PAYMENT SP
            ON CS.COURSESHD_ID = SP.STUDENT_PAYMENT_COURSESHD_ID
        WHERE SP.STUDENT_PAYMENT_STUDENT_ID = @STUDENT_ID
        AND CS.COURSESHD_STATUS = 1
        AND CS.COURSESHD_ENDDATE < GETDATE()
        AND CS.COURSESHD_COURSE_ID = @@@CourseID
    )
    AND C.COURSE_STATUS=1

    SELECT @@Post = Count(*)
    FROM DLC_ASSESSMENT_RESULT
    WHERE RESULT_STUDENT_ID = @STUDENT_ID
    AND RESULT_COURSE_ID = @@@CourseID
    AND RESULT_STATUS = 'Pass'
    AND RESULT_ASSESSMENT_TYPE = 1

    SELECT @@Feedback = Count(*)
    FROM FEEDBACK_RESULTS
    WHERE QUESTION_ID IN
    (
        SELECT QUESTION_ID
        FROM FEEDBACK_QUESTIONS
        WHERE QUESTION_COURSE = @@@CourseID
        AND STATUS_ID = 1
    )
    AND EMP_ID = @STUDENT_ID

    SELECT @@Final = COUNT(*)
    FROM DLC_ASSESSMENT_RESULT
    WHERE RESULT_STUDENT_ID = @STUDENT_ID
    AND RESULT_COURSE_ID = @@@CourseID
    AND RESULT_STATUS = 'Pass'
    AND RESULT_ASSESSMENT_TYPE = 3

    --declare @@Pre int= 0, @@Course int = 0 , @@Post int  = 0, @@Feedback int = 0  , @@Final  int  = 0

    DECLARE @per decimal (18,2)

    --select isnull(@@Pre,0), isnull(@@Post,0) , isnull(@@Final,0)
    SET @per = ((ISNULL(@@Pre,0) + ISNULL(@@Post,0) + ISNULL(@@Final,0) ) / 3.00   * 100)

    INSERT INTO @tablefinal
    SELECT  ISNULL(@@Course,0) AS COURSE,
            @@@CourseName,
            ISNULL(@@Pre,0) AS PRE,
            ISNULL(@@Post,0) AS Post,
            ISNULL(@@Feedback,0) AS Feedback,
            ISNULL(@@Final,0) AS Final,
            @per
  END

SELECT *
FROM @TABLEFINAL