texts: Given Sum of sub sums of an integer find the original integer

texts:
If we are given an integer \$\text{SumofSubSums}(N)\$, and number of digits \$D\$ that \$N\$ has, we are asked to find the original  integer \$ N \$.

Example:
 If we are given \$2148\$ , and \$D = 4\$.
We need to find \$1935\$ , because
$$2148 = 1935 + \frac{1935}{10}+\frac{1935}{100}+\frac{1935}{1000}$$

Now I have a code which solves the task but it takes a lot of time to do so...

#include <iostream>
#include <cmath>
using namespace std;

    long long int Sum_of_Sub_Sums(long long int a) {
        long long int Sum = 0;
        for (a = a; a > 0; a /= 10) {
            Sum += a;
        }
        return Sum;
  }

    int main() {
        long long int maxSum[15] = { 9, 108, 1107, 11106, 111105, 1111104, 11111103, 111111102, 1111111101, 11111111100, 111111111099, 1111111111098, 11111111111097, 111111111111096, 1111111111111095 };
        long long int number;
        int numDigits;
        cin >> number >> numDigits;
        if (number < 10 && numDigits < 2) {
            cout << number;
        }
        else {
                long long int l = pow(10,numDigits-1);
                long long int r = maxSum[numDigits-1];
                long long int mid= l + (r-l)/2;
                while(Sum_of_Sub_Sums(mid)!= number){
                if(Sum_of_Sub_Sums(mid) > number){
                    r = mid;
                }
                else {
                    l = mid;
                }
                mid = l + (r-l)/2;
            }
            cout<<fixed<<mid;
        }
            return 0;
    }

how can I decrease the complexity of my code ?

\$EDIT: \$
If anyone is interested here is the working solution

#include <iostream>
#include <cmath>
using namespace std;

long long int Sum_of_Sub_Sums(long long int a) {
    long long int Sum = 0;
    for (a = a; a > 0; a /= 10) {
        Sum += a;
    }
    return Sum;
}

int main() {
    long long int number;
    long double tmp;
    int numDigits;
        cin >>number >>numDigits;
        if (number < 10 && numDigits < 2) {
      cout << number;
    } else {
        tmp=(pow(10,numDigits)-1)/(9*pow(10,numDigits-1));
        long long int current =  number/tmp;
        while (Sum_of_Sub_Sums (current) != number) {
      if (Sum_of_Sub_Sums (current) > number) {
          current--;
        } else {
          current++;
        }
        Sum_of_Sub_Sums (current);
    }
      cout << fixed << current;
    }
        return 0;
}


texts: Haskell program to extract the first words of each line of a text file

texts:
isLineTerminator c = c == '\r' || c == '\n'
leadWords [] = []
leadWords cs =
    let (pre, suf) = break isLineTerminator cs
    in  (head (words pre)) : case suf of
                            ('\r':'\n':rest) -> leadWords rest
                            ('\r':rest)      -> leadWords rest
                            ('\n':rest)      -> leadWords rest
                            _                -> []

fixLines :: String -> String
fixLines input = unlines (leadWords input)

interactWith function inputFile outputFile = do
    input <- readFile inputFile
    writeFile outputFile (function input)

main = mainWidth myFunction
  where mainWidth function = do
            args <- getArgs
            case args of
                [input, output] -> interactWith function input output
                _               -> putStrLn "error: exactly two arguments needed"
        myFunction = fixLines

Much of this program is written by the author of the book on Haskell that I'm reading, so I assume that much of it is good. However, my part is in altering the leadWords function. Does it look like a:

readable, elegant function?
efficient and optimized function?


texts: Efficiency of a linked list partitioning algorithm

texts:
I have come across a fun puzzle, sorting a linked list, and I wanted to go for quicksort. However, I am not quite sure whether my partitioning algorithm is efficient enough. I also believe that my code is not clean.

Is it possible to remove some variables or make it more efficient?

#include <iostream>
#include <cstdlib>

using namespace std;

struct Node
{
    int data;
    Node *next;
};

void printList(Node *list)
{
    Node *temp = list;
    while(temp != NULL)
    {
        cout<<temp->data<<" ";
        temp = temp->next;
    }
}

int partition(Node *list, int start, int end)
{
    Node *startPtr = list, *endPtr = list, *head = list;

    for(int i = 0; i < start; i++)
        if(startPtr == NULL || startPtr->next == NULL)
            return -1;
        startPtr = startPtr->next;

    for(int i = 0; i < end; i++)
    {
        if(endPtr == NULL || endPtr->next == NULL)
            return -1;
        endPtr = endPtr->next;
    }

    Node *temp = NULL, *temp2 = startPtr;
    int pivot = endPtr->data;

    while(temp2->next != endPtr)
    {
        if(temp2->data < pivot)
        {
            if(temp != NULL)
                temp = temp->next;
            else
                temp = startPtr;

            swap(temp->data, temp2->data);
        }
        temp2 = temp2->next;
    }
    temp = temp->next;
    swap(temp->data, endPtr->data);

    int index;
    Node *temp3 = list;

    for(index = 0; temp3->data != pivot; index++)
        temp3 = temp3->next;

    return index;
}

int main()
{
    Node *a = new Node;
    Node *b = new Node;
    Node *c = new Node;
    Node *d = new Node;
    Node *e = new Node;
    Node *f = new Node;

    a->next = b;
    a->data = 2;
    b->next = c;
    b->data = 6;
    c->next = d;
    c->data = 3;
    d->next = e;
    d->data = 1;
    e->next = f;
    e->data = 7;
    f->data = 5;

    cout<<partition(a, 0, 5)<<endl;

    return 0;
}


texts: Project Euler # 19 Counting Sundays in Python

texts:
You are given the following information, but you may prefer to do some research for yourself.
1 Jan 1900 was a Monday.
Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?

day_names = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
month_names = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September',
               'October', 'November', 'December']
month_days_common = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
month_to_days = dict(zip(month_names, month_days_common))

def is_leap(year):
    """return True if a year is leap. False otherwise."""
    if (year % 4) == 0:
        if (year % 100) == 0:
            if (year % 400) == 0:
                return True
            else:
                return False
        else:
            return True
    else:
        return False

def get_date_day_names(end_year):
    """return a list of tuples containing day name, day, month, year from 1900 to end_year(exclusive)."""
    start_year = 1900
    total = 0
    all_day_names = []
    all_months1 = []
    all_months2 = {}
    year_month_times_number_of_days = []
    final_dates = []
    for year in range(start_year, end_year):
        count = 0
        while count < 12:
            all_months1.append((year, month_names[count]))
            count += 1
    for year in range(start_year, end_year):
        if is_leap(year):
            total += 366
        else:
            total += 365
    for i in range(total):
        all_day_names.append(day_names[i % 7])
    for year, month in all_months1:
        if is_leap(year):
            if month == 'February':
                all_months2[(year, month)] = 29
            else:
                all_months2[(year, month)] = month_to_days[month]
        else:
            all_months2[(year, month)] = month_to_days[month]
    for date, number_of_days in all_months2.items():
        for i in range(number_of_days):
            year_month_times_number_of_days.append((date, i + 1))
    date_day_name = list(zip(all_day_names, year_month_times_number_of_days))
    for date_item in date_day_name:
        final_dates.append((date_item[0], date_item[1][1], date_item[1][0][1], date_item[1][0][0]))
    return final_dates

def count(day_name, day_of_the_month, end_year):
    """returns count of a given day from 1901 to end_year(exclusive)"""
    final_dates = []
    dates_1900_to_end_year = get_date_day_names(end_year)
    for date in dates_1900_to_end_year:
        if date[-1] != 1900 and date[0] == day_name and date[1] == day_of_the_month:
            final_dates.append(date)
    return len(final_dates)

if __name__ == '__main__':
    print(count('Sunday', 1, 2001))


texts: Best method to further execute the DRY principle and/or raise performance in my script? (client login/signup system)

texts:
Just for practice purposes, I written a basic client sided login/signup system that allows you to make an account, and then log into the account from my webpage. What it does is append to an object known as database for every new account made, and when you sign in, it loops through the database and see if your credentials match any account information.

There's a couple of noticable problems with my script. One being that I believe that I didn't follow the DRY principle to the fullest. I felt like I repeated myself a couple of times, and wondering if that can be avoided. The second problem is that looping through the "database" object may not be the most efficient solution, especially since the longer the table, the longer it may take. There may be a solution that is more efficient in performance that I am unaware of.

Other than that I would just like general feedback, tips, and red flags (if any) in my code. I am trying to improve myself as a JavaScript developer, and that requires feedback of my script from my peers.

TL;DR: I am a new programmer, so sorry if this is a bad question or if I have terrible code. I am still learning.

const database = []

function usp(parent) {
  return [parent.username.value, parent.password.value]
}

window.onload = () => {
  const create = document.forms.createAcount;
  const log = document.forms.logIN;

  create.addEventListener('click', (e) => {
    if(e.target == create.submit){
      const information = usp(create);
      database.push({user : information[0], pass : information[1]});
      console.log(database)
    }
  });

  log.addEventListener('click', (e) => {
    if (e.target == log.submit) {
      const information = usp(log);
      for (let x of database) {
        if (x.user == information[0] && x.pass == information[1]) {
          alert(`You successfully logged into your account! Welcome to my website ${information[0]}`)
        }
      }
    }
  })
}
#createAcount {
  background-color: skyblue;
}
#logIN {
  background-color: lightgreen;
}
<!DOCTYPE html>

      <title>SignUp!</title>
      <link rel = "stylesheet" href = 'style.css'>

Sign Up

      <form name = "createAcount" id = "createAcount">

Create a Username

        <input type = 'text' placeholder="Falkyraizu"  name = 'username' maxlength=20>

Create a password

        <input type = 'password' placeholder="password" name = 'password' maxlength=20>

Done

        <input class = 'reset' type = 'button' value = "Reset" name = 'reset'>
        <input class = 'submit' type = 'button' value = "Submit" name = 'submit'>
      </form>

Log In

      <form name = "logIN" id = "logIN">

What is your userName

        <input type = 'text' placeholder="Falkyraizu" name = "username" maxlength=20>

What is your password

        <input type = 'password' placeholder="password" name = "password" maxlength=20>

Done

        <input class = 'reset' type = 'button' value = "Reset" name = 'reset'>
        <input class = 'submit' type = 'button' value = "Submit" name = 'submit'>
      </form>

Side Note: If you notice something else that can be fixed such as my HTML, you can also include it in your response, however I would still like my main problems fixed (read above if you missed it). Thanks for the help!


texts:
Take the below code that I recently wrote:

.navbar-inverse .emphasis-text, .navbar-inverse:hover .emphasis-text, .emphasis-text {
    color: #1caa98; /* Teal */
}

While this may be a dryer way of placing teal on all these link items, would you consider this readable? It seems to me like there is a lot to read, and it's not entirely clear what these are for. It's okay if this is fine, but it would be nice to hear some opinions from outside my own eyeballs.


texts:
The following is an implementation of fixed-length sequences that makes very exotic (and hopefully fun) use of Swift 2.2 types. The question is what exactly is the cost of having the type checker guaranteeing sequence length in this way on safety? performance? readability?

protocol CountType {
    static var count: Int { get }
}

protocol DigitType : CountType {}

enum _0 : DigitType { static let count = 0 }
enum _1 : DigitType { static let count = 1 }
enum _2 : DigitType { static let count = 2 }
enum _3 : DigitType { static let count = 3 }
enum _4 : DigitType { static let count = 4 }
enum _5 : DigitType { static let count = 5 }
enum _6 : DigitType { static let count = 6 }
enum _7 : DigitType { static let count = 7 }
enum _8 : DigitType { static let count = 8 }
enum _9 : DigitType { static let count = 9 }

At this point we can do very little:

_4.count // 4
_2.count // 2

To express larger natural numbers, however, we must combine DigitTypes:

import CoreGraphics // TODO: wean off (implement `pow`)

extension DigitType {
    static func value(place place: Int) -> Int {
        return count * Int(pow(10, CGFloat(place)))
    }
}

enum __<T:DigitType, U:DigitType> : CountType { // these are two underscores `_`x2 (then, below, three, four...)
    static var count: Int {
        return T.value(place: 1) + U.value(place: 0)
    }
}
enum ___<H:DigitType, T:DigitType, U:DigitType> : CountType {
    static var count: Int {
        return H.value(place: 2) + T.value(place: 1) + U.value(place: 0)
    }
}
enum ____<Th:DigitType, H:DigitType, T:DigitType, U:DigitType> : CountType {
    static var count: Int {
        return Th.value(place: 3) + H.value(place: 2) + T.value(place: 1) + U.value(place: 0)
    }
}

... which allows us to count in types (try it in the playground):

____<_2,_0,_1,_6>.count // 2016

The point is that we can now make use of CountTypes to define sequence length:

final class Box<T> {
    var value: T
    init(_ value: T) { self.value = value }
}

struct Vector<Dimension: CountType, Element> : SequenceType {

    private let array: [Box<Element>]
    var elements: [Element] { return array.map{ $0.value } }

    subscript(index: Int) -> Box<Element> { return array[index] }

    init(_ repeatedValue: Element) {
        array = (0..<Dimension.count).map{ _ in Box(repeatedValue) }
    }

    func generate() -> Array<Element>.Generator {
        return elements.generate()
    }
}

// TODO: Matrix<Rows: CountType, Cols: CountType, Element>

We may now work with such Vectors and Matrixes with confidence that their dimension can never change:

let v = Vector<__<_4,_2>,Int>(0)
v.elements.count // 42

let w = Vector<_3,Int>(0)
w.elements // [0, 0, 0]
w[2].value = 5

for x in w {
    x // 0, 0, 5
}

(hm... the underscore syntax looks prettier in my playground...)

I was considering various alternative naming schemes for the combining enums. So, instead of underscores, we could perhaps emulate the exponent syntax for number literals (like 0.42e2 meaning 0.42 * pow(10, 2)). This would work out as following:

e4<_2,_0,_1,_6>.count // 2016

// and

let v = Vector<e2<_4,_2>,Int>(0)

The reason I decided against this and similar approaches is that there is now a rather irrelevant number 2 appearing alongside _4,_2...


texts:
I have a section of my code that seems to take a while during processing. Basically rawArray contains ~1.5 million rows and tempArray has around 1000 rows. I can see why it's slow as for each of the 1.5 million rows it has to loop through the tempArray and look for a match. Any hints for optimising this would be great!

foreach(string[] sArray in rawArray) {
    // Loop through tempArray and look for match in SRC and/or DST
    foreach (string[] sTemp in tempArray)
    {
        // SRC matches
        if (sArray[0] == sTemp[1])
        {
            // Set Octets value for upload
            if (sTemp[3] == "")
            {
                sTemp[3] = "0";
            }

            // Convert to double and increment
            sTemp[3] = (System.Convert.ToDouble(sTemp[3]) + System.Convert.ToDouble(sArray[2])).ToString();
            // Date & Time
            sTemp[5] = date;
            sTemp[6] = time;
        }

        // DST matches
        if (sArray[1] == sTemp[1])
        {
            // Set Octets value for download
            if (sTemp[2] == "")
            {
                sTemp[2] = "0";
            }

            // Convert to double and increment
            sTemp[2] = (System.Convert.ToDouble(sTemp[2]) + System.Convert.ToDouble(sArray[2])).ToString();
            // Date & Time
            sTemp[5] = date;
            sTemp[6] = time;
        }
    }
}


texts: Organizing page functions and page state using the Module pattern

texts:
So I'm developing a webpage using MVC which will be mainly JavaScript driven.

Instead of using global variables, and global functions, I would like to do it right this time. I don't want to use something to complex, because the team and I are new to large JavaScript applications. I tried implementing the Module pattern to organize my functions and page state.

This is what I came up with so far.

Am I misusing the Module pattern? What am I doing wrong? Where will I get into trouble?

<script type="text/javascript">
    var ui = (function ($) {
        var _ui = {};

        _ui.submitMainForm = function () {
            document.main.submit();
        };

        return _ui;
    } (jQuery));

    ui.tabs = (function ($) {
        var _tabs = {};

        var resourceTabs = $("#resourceTabs");
        var selectedTabPersistence = $("#SelectedTab");

        _tabs.getSelectedTab = function () {
            return selectedTabPersistence.val();
        };
        _tabs.setSelectedTab = function (value) {
            selectedTabPersistence.val(value);
        };
        _tabs.initialize = function () {
            resourceTabs.tabs({
                select: function (event, ui) { _tabs.setSelectedTab(ui.tab.hash); }
            });
            resourceTabs.tabs("select", _tabs.getSelectedTab());
        };

        return _tabs;
    } (jQuery));

    ui.filter = (function ($) {
        var _filter = {};

        var personLevels = $("#personLevels");
        var vehicleLevels = $("#vehicleLevels");
        var personLevelsRadio = $("#personLevels :radio");
        var vehicleLevelsRadio = $("#vehicleLevels :radio");

        _filter.initialize = function () {
            personLevels.buttonset();
            vehicleLevels.buttonset();
            personLevelsRadio.bind("change", function () { ui.submitMainForm() });
            vehicleLevelsRadio.bind("change", function () { ui.submitMainForm() });
        };

        return _filter;
    } (jQuery));

    $(document).ready(function () {
        ui.tabs.initialize();
        ui.filter.initialize();
    });
</script>


texts:
Using Excel, I have one sheet ("db") with data extracted from MES.
I have to analyze this data and I need: Articolo, Fase, Tipo Confezione, TURNO, Macchina, avg and median.
I searched everywhere how to get the median with SQL, but I found only how to get median for one item alone.
Then I wrote this code, and I loop each item from 1st query to get data from another query, it works but it is extremely slow!
Is there a better way to get my data or, if my code is the correct way, how I can speed up the job?
Any suggestions are appreciated.
My code:
Sub Get_Pivot()
    Dim strsql As String
    Dim cn As New ADODB.Connection, rs As New ADODB.Recordset
    Dim RangeVal As Range, DatiVal

    Sheets("db").Select 'sheet with database

    Const adOpenStatic = 3
    Const adLockOptimistic = 3
    Const adCmdText = &H1

    Set rs = New ADODB.Recordset
    cn.Open "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & ThisWorkbook.FullName & "; Extended Properties=""Excel 8.0;HDR=Yes;"";"

   ' select field from db
    strsql = "SELECT Articolo, Fase, [Tipo Confezione], TURNO, Macchina, avg(KgOra) as med FROM [db$] where Time>0 group by Articolo, Fase, [Tipo Confezione], TURNO, Macchina ;"
    rs.Open strsql, cn, adOpenStatic, adLockReadOnly, adCmdUnspecified

    rs.MoveFirst
    Sheets("pvt").Select  'sheet how to put data

    'insert header columns name
    For i = 0 To rs.Fields.Count - 1
        Cells(1, i + 1) = rs.Fields(i).Name
    Next i

    'insert data from recordest
    Range("A2").CopyFromRecordset rs

    'set range and get data from pasted recordset
    Set RangeVal = Range("A1", Cells(Range("A1").End(xlDown).Row, 7))
    DatiVal = RangeVal.Value
    Set rs = Nothing

'loop each row and run one qry to get median
For i = 2 To UBound(DatiVal, 1)
    strsql = "select last(KgOra) FROM (select top 50 percent KgOra from [db$] where " & _
            "Articolo = '" & DatiVal(i, 1) & _
            "' and Fase = '" & DatiVal(i, 2) & _
            "' and [Tipo Confezione] = '" & DatiVal(i, 3) & _
            "' and TURNO = '" & DatiVal(i, 4) & _
            "' and Macchina = '" & DatiVal(i, 5) & "');"

    rs.Open strsql, cn, adOpenStatic, adLockReadOnly, adCmdUnspecified

'if recordset exist add value at 7th filed of DatiVal
    If Not rs.EOF Then DatiVal(i, 7) = rs(0)
    rs.MoveNext
    Set rs = Nothing
Next

'then paste new data with one columns more(median columns)
whit RangeVal
.vaue = DatiVal
End With

rstErr:
    Set rs = Nothing
    Set cn = Nothing

End Sub


texts: Updating messages from a list of messages

texts:
I've not posted binding specific messages to the gridview part. This shows updating that particular message or message from a list of messages databound with an XML file. My main concern is omitting redundant code in the else part. Any suggestions?

protected void grdMessage_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    DataRow xRow;
    DataSet mdsRedirect = new DataSet();
    mdsRedirect.ReadXml(st);

    if (Request["MessageID"] != null && Convert.ToInt16(Request["MessageID"]) != 0)
    {
        //Find specific item from XML and set updated value
        mdsRedirect.Tables[0].DefaultView.RowFilter = "MessageID=" + Convert.ToInt16(Request["MessageID"]);
        if (mdsRedirect.Tables[0].DefaultView.Count > 0)
        {
            mdsRedirect.Tables[0].DefaultView[0]["MessageText"] = ((TextBox)(grdMessage.Rows[e.RowIndex].FindControl("txtupdMessage"))).Text;
            mdsRedirect.Tables[0].DefaultView.RowFilter = string.Empty;
        }
        else {
            xRow = mdsRedirect.Tables[0].Rows[e.RowIndex];
            xRow["MessageText"] = ((TextBox)(grdMessage.Rows[e.RowIndex].FindControl("txtupdMessage"))).Text;
        }
    }
    else
    {
        xRow = mdsRedirect.Tables[0].Rows[e.RowIndex];
        xRow["MessageText"] = ((TextBox)(grdMessage.Rows[e.RowIndex].FindControl("txtupdMessage"))).Text;
    }

    grdMessage.EditIndex = -1;
    mdsRedirect.WriteXml(st);
    mdsRedirect.Dispose();
    getxml();//read XML file and bind it
}


texts: Database of students in a social network

texts:
This is sourced from the Stanford Coursera self study DB class SQL quizzes.

  Students at your hometown high school have decided to organize their
  social network using databases. So far, they have collected
  information about sixteen students in four grades, 9-12. Here's the
  schema:

Highschooler (ID, name, grade)

  English: There is a high school student
  with unique ID and a given first name in a certain grade.

Friend (ID1, ID2)

  English: The student with ID1 is friends with the
  student with ID2. Friendship is mutual, so if (123, 456) is in the
  Friend table, so is (456, 123).

Likes (ID1, ID2)

  English: The student with ID1 likes the student with
  ID2. Liking someone is not necessarily mutual, so if (123, 456) is in
  the Likes table, there is no guarantee that (456, 123) is also
  present.

  DB is here

  Prompt: Find the number of students who are either friends with
  Cassandra or are friends of friends of Cassandra. Do not count
  Cassandra, even though technically she is a friend of a friend.

My answer (which works) is below, but I am wondering if there is a more succinct way of accomplishing the same results. Any feedback would be appreciated.

select count(*)-1 from
(
select id2
from friend f, highschooler a
where a.name='Cassandra'
and a.id=f.id1
union
select id2
from friend f, highschooler a
where a.id=f.id1
and f.id1 in ( select id2
from friend f, highschooler a
where a.name='Cassandra'
and a.id=f.id1 ) )


texts:
I tried to solve the Super Pow - LeetCode

  Super Pow

  Medium

  Your task is to calculate ab mod 1337 where a is a positive integer and b is an extremely large positive integer given in the form of an array.

  Example 1:

Input: a = 2, b = [3]
Output: 8

  Example 2:

Input: a = 2, b = [1,0]
Output: 1024

My solution

import unittest
import logging
logging.basicConfig(level=logging.DEBUG, format="%(levelname)s %(message)s")

class Solution(object):
    def superPow(self, a, b):
        """
        :type a: int
        :type b: List[int]
        :rtype: int
        """
        digit = int("".join(map(str, b)))
        product = a ** digit
        res = product % 1337
        return res

class MyCase(unittest.TestCase):
    def setUp(self):
        self.solution = Solution()

    def test_1(self):
        a = 2
        b = [1, 0]
        answer = 1024
        check = self.solution.superPow(a, b)
        self.assertEqual(answer, check)

unittest.main()

The solution exceeded the time limit.

How could I improve my solution?


texts: Minimum swaps algorithm terminated due to timeout

texts:
I have been trying to solve this question.

  Given an unordered array consisting of consecutive integers [1, 2, 3, …, n], find the minimum number of two-element swaps to sort the array.

I was able to solve it but my solution's complexity is not good enough that it terminated due to a timeout when it runs with bigger arrays. This is a typical problem for me, I always solve the problem somehow but the complexity is not optimal and the solution does not pass the all the cast cases. If you have any suggestions for me for the future interview questions like that, I'd appreciate knowing how should I approach the questions.

function findIndice(arr,i){
  let iterator=0
  while(arr[iterator]!==i+1){
    iterator++
  }
  return iterator
}

function swap(arr,x,y){
  let temp=arr[x]
  arr[x]=arr[y]
  arr[y]=temp
}

function minimumSwaps(arr){
  let i=0;
  let counter=0;
  let size=arr.length;

  for(i=0;i<size-1;i++){
    if(arr[i]!==i+1){
      let index=findIndice(arr,i)
      swap(arr,index,i)
      counter++
    }
  }
  return counter
}


texts: Programming Puzzle - N Teams K Wins each

texts:
I found a problem here. I am sharing the problem and my attempt at solution. I would like to find out if this is the best approach possible.

  One day, at the "Russian Code Cup" event it was decided to play
  football as an out of competition event. All participants was divided
  into n teams and played several matches, two teams could not play
  against each other more than once.

  The appointed Judge was the most experienced member - Pavel. But since
  he was the wisest of all, he soon got bored of the game and fell
  asleep. Waking up, he discovered that the tournament is over and the
  teams want to know the results of all the matches.

  Pavel didn't want anyone to discover about him sleeping and not
  keeping an eye on the results, so he decided to recover the results of
  all games. To do this, he asked all the teams and learned that the
  real winner was friendship, that is, each team beat the other teams
  exactly k times. Help Pavel come up with chronology of the tournir
  that meets all the conditions, or otherwise report that there is no
  such table.

  Input

  The first line contains two integers:  \$n\$ and \$k\$ (\$1 ≤ n, k ≤ 1000\$).

  Output

  In the first line print an integer \$m\$ - number of the played
  games. The following \$m\$ lines should contain the information about all
  the matches, one match per line. The \$i\$-th line should contain two
  integers \$ai\$ and \$bi\$ (\$1 ≤ ai\$, \$bi ≤ n\$; \$ai ≠ bi\$). The numbers \$ai\$ and \$bi\$
  mean, that in the \$i\$-th match the team with number \$ai\$ won against the
  team with number \$bi\$. You can assume, that the teams are numbered from
  1 to \$n\$.

  If a tournir that meets the conditions of the problem does not exist, then print -1.

My solution:

<?php
//$n = $argv[1];
//$k = $argv[2];
$s = fopen("php://stdin", 'r');
$n = stream_get_contents($s);
$dum= explode(" ",trim($n));
$n=$dum[0];
$k=$dum[1];
if ($n * $k > ($n * ($n - 1)) / 2) {
    echo "-1\n";exit;
}
$output = $n*$k."\n";
$winMap = array();
for ($i = 1; $i <= $n; $i++) {
    $winMap[$i] = 0;
}
for ($i = 1; $i <= $n; $i++) {
    for ($j = $i + 1; $j <= $n; $j++) {
        if ($winMap[$i] < $k) {
            $output .= "$i $j\n";
            $winMap[$i] += 1;
        } else if ($winMap[$j] < $k) {
            $winMap[$j] += 1;
            $output .=  "$j $i\n";
        }
    }
}
echo $output;
?>


texts: Python script to scrape titles of public Youtube playlist

texts:
Just started in Python; wrote a script to get the names of all the titles in a public Youtube playlist given as input, but it got messier than it might have to be.

I looked around online and found HTMLParser, which I used to extract the titles, but it had problems with encoding which might have to do with there being foreign characters in the playlist HTML, so I messed around with encodes and decodes until it worked. But is there a prettier way to fix the problem?

import urllib.request
from html.parser import HTMLParser

playlistUrl = input("gib nem: ")

with urllib.request.urlopen(playlistUrl) as response:
  playlist = response.read()

html = playlist.decode("utf-8").encode('cp1252','replace').decode('cp1252')

titles = ""
class MyHTMLParser(HTMLParser):
  def handle_starttag(self, tag, attrs):
    for attr in attrs:
      if attr[0] == "data-title":
        global titles
        titles += attr[1] + "\n"

parser = MyHTMLParser()
parser.feed(html)
print(titles)

with open("playlistNames.txt", "w") as f:
  f.write(titles)


texts: Function to get daily metrics by fetching a record or evaluating a formula

texts:
I have react-redux application that allows to track different metrics on daily basis. Each metric can either have Records or store math function to calculate values. State stores normalized Metrics and Records.

This function returns either a calculated value or stored value for certain date.

export const getMetricRecordForDate = (state, metric_id, date) => {
  const resultMetric = state.metrics[metric_id]
  let result = {decimal_value: 0, date: date}
  if (resultMetric.formula) { //formula format: '_idOfMetric_*_idOfAnotherMetric_'
    let args = {}

    const metrics = resultMetric.formula.scan(/_(.*?)_/g) //Array: [..,'_idOfMetric_']
    const l = metrics.length
    for (var i=0; i<l; i++) {
      const key = "_"+metrics[i]+"_"
      args[key] = getMetricRecordForDate(state, state.metrics[metrics[i]].id, date).decimal_value

    }

    let decimal_value
    try { // statements to try args format: {_idOfMetric_: value}
      decimal_value = math.eval(resultMetric.formula, args)
    }
    catch (e) {
      decimal_value = 0;
    }

    result.decimal_value = decimal_value
  } else {
    const records = getMetricRecords(metric_id, state)
    let metricRecord
    if (records.length > 0) {
      for (var i=0; i<records.length; i++) {
        if (moment(records[i].date).isSame(date, 'day')) {
          metricRecord = records[i]
          break
        }
      }
    }
    if (metricRecord) {
      result = metricRecord
    }
  }
  return result

}

The structure of state:

{state:
  {metrics: {1: {id: 1, name: 'name', records: [1, 2]} },
  {records: {1: {id: 1, decimal_value: 0, date: '01-01-2017', metric_id: 1},
            {2: {id: 1, decimal_value: 0, date: '02-01-2017', metric_id: 1}
  }
}

So, right now this function is very slow especially for recursive calls. I was wondering if it could be optimized.

Here is the getMetricRecords function:

export const getMetricRecords = (metric_id, state) => {
  return state.metrics[metric_id].records.map( id => state.records[id])
}

I would appreciate any help (I am new to Javascript).


texts: SASS + Compass - File Structure and @Import order

texts:
I recently started using SASS and Compass in my projects. So far I am using the file structure shown below.

  sass/
    |
    |– base/
    |   |– _reset.scss       # Reset/normalize
    |   |– _typography.scss  # Typography rules
    |   ...                  # Etc…
    |
    |– components/
    |   |– _buttons.scss     # Buttons
    |   |– _carousel.scss    # Carousel
    |   |– _cover.scss       # Cover
    |   |– _dropdown.scss    # Dropdown
    |   |– _navigation.scss  # Navigation
    |   ...                  # Etc…
    |
    |– helpers/
    |   |– _variables.scss   # Sass Variables
    |   |– _functions.scss   # Sass Functions
    |   |– _mixins.scss      # Sass Mixins
    |   |– _helpers.scss     # Class & placeholders helpers
    |   ...                  # Etc…
    |
    |– layout/
    |   |– _grid.scss        # Grid system
    |   |– _header.scss      # Header
    |   |– _footer.scss      # Footer
    |   |– _sidebar.scss     # Sidebar
    |   |– _forms.scss       # Forms
    |   ...                  # Etc…
    |
    |– pages/
    |   |– _home.scss        # Home specific styles
    |   |– _contact.scss     # Contact specific styles
    |   ...                  # Etc…
    |
    |– vendors/
    |   |– _bootstrap.scss   # Bootstrap
    |   |– _jquery-ui.scss   # jQuery UI
    |   ...                  # Etc…
    |
    |
    `– main.scss             # primary Sass file

I am happy with the file structure (unless anyone would like to comment on how it could be improved)

My issue is: I am not entirely sure what the best practice is for ordering my @Imports in Primary SCSS file.

I was wondering if anyone could advise me on the best way to import.

I have not yet put together my imports for this new file structure, yet I will show my imports for a previous project.

Previous Project's Primary SCSS file:

@import "partials/defaults";
@import "partials/typography";
@import "partials/grids";
@import "partials/buttons";
@import "partials/headers";
@import "partials/footers";

I want to know which practice is best for organizing my new file structure.

Any help or advice is appreciated.


texts: Check SMART status on MacOS and pop up alert

texts:
So I don't know much about bash scripting.  I am just a beginner.  I made this script which checks the SMART status of my root volume and if it is failing then it immediately throws a pop up alert if my drive is failing.
Here's the code:

A=$( diskutil info disk0 | grep SMART )

if [ "$A" != "   SMART Status:             Verified" ]
then

osascript -e 'tell application "Finder" to activate' -e 'tell
application "Finder" to display dialog "Your Drive is failing,
Please backup all your important files now" buttons
{"OK"} with icon stop'
fi

I know this is so simple. Do you have any suggestions to improve it?


texts: Script to append a new method to a XAML code-behind file

texts:
My company is converting a VB.NET project to a C# application and I was tasked with writing a script to automate part of the process. In particular, given information about a control name and event in VB.NET, I'm trying to insert the corresponding event into the new XAML file and its code-behind.

My approach is based partially on this Stack Overflow answer.

Basically, I'm trying to insert some text before the last two lines of a file. Specifically, I'm inserting methods into a XAML code-behind file.

The XAML code-behind is pretty typical, but just for reference, here's an example:

using System.Windows;

namespace MyNamespace
{
    /// <summary>
    /// Interaction logic for myWindow.xaml
    /// </summary>
    public partial class myWindow : Window
    {
        public myWindow()
        {
            InitializeComponent();
        }

        private void DO_CANCEL_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        // I want to insert the new method here.
        // It's possible that I'll end up inserting several, but I don't know
        // how many I'll end up inserting "in advance."
    }
}

I do the following:

private static void AddEvent(MethodNameParts parts)
{
    // xamlFile is the full name and path of the .xaml file (the actual XML front-end)
    string windowsCsFile = xamlFile + ".cs";

    var lines = File.ReadAllLines(windowsCsFile);

    // Write the entire file except for the last two closing }
    // I have logic (not shown) to make sure that the file is "trimmed" properly before I run this
    // Thus, the last two lines will definitely be the "}" that closes the
    // class and the "}" that closes the namespace
    File.WriteAllLines(windowsCsFile, lines.Take(lines.Length - 2));

    // parts.CSFullLine is a string containing the C# method I want to insert
    File.AppendAllLines(windowsCsFile, new[] { parts.CSFullLine });
    File.AppendAllLines(windowsCsFile, new[] { "}", "}" });
}

Is this a good solution, or should I do something else to avoid having to do so many writes?


texts: Minimizing CSS media queries for the page title?

texts:
I am working on page titles to be responsive. The code I have works and gets the job done, but I know that this is verbose. I decided upon the widths by trial and error based on how the words were stacking on each other

Desktop

Tablet

Mobile

This is the what I currently have as code

HTML

BruxZir&reg; Solid Zirconia Crowns &amp; Bridges

CSS

#page-title, #page-title-video {
  background: url(../img/top-banner.jpg) #273344 no-repeat right top;
  padding: 0.2em 0 0.2em 1em;
}

#page-title { margin: 12px 15px 24px 15px; }
#page-title-video { margin: 12px 0 24px 0; }

#page-title h1, #page-title-video h1 {
  color: #FFFFFF;
  letter-spacing: 0.08em;
}

@media screen and (min-width: 1px) and (max-width: 321px) {
  #page-title h1, #page-title-video h1 {
    font-size: 18px;
  }
}

@media screen and (min-width: 322px) and (max-width: 569px) {
  #page-title h1, #page-title-video h1 {
    font-size: 20px;
  }
}

@media screen and (min-width: 570px) and (max-width: 749px) {
  #page-title h1, #page-title-video h1 {
    font-size: 22px;
  }
}

@media screen and (min-width: 750px) and (max-width: 950px) {
  #page-title h1, #page-title-video h1 {
    font-size: 24px;
  }
}

@media screen and (min-width: 951px) {
  #page-title h1, #page-title-video h1 {
    font-size: 36px;
  }
}


texts: JavaScript async/await function performance improvement

texts:
I have a simple async/await function which gets data from a firebase endpoint. I would like to know if there is any room for improvement performance wise.
async function getDataById(id) {
  const snapshot = await admin
    .firestore()
    .collection("collection")
    .where("id", "==", id)
    .get();
  const documents = [];
  snapshot.forEach((doc) => {
    documents.push(doc.data());
  });
  return documents;
}


texts: Checking whether four text fields are all empty

texts:
I have a code which checks if any of the 4 textfields on our server contains text. If even one of the four textboxes is not empty, the generated table won´t skip that row and will draw it, otherwise the row will be completely skipped and not shown in the table.

For that I declared the variables for the words and the Boolean, so I can later use it to hide the table row. What the code does is it checks all the possible combinations of the wordboxes and if even one on the wordboxes contains something, the checkRow variable  will be true.

This "if" statement method that I use works, however it is very hard to follow and I think it could be better done. I have documented myself but all the alternatives involve jquery - which is not supported on our webclient.
Does anyone have a suggestion how to better this code?

                var checkRow=false;
                var word1='{{WORD1}}';
                var word2 ='{{WORD2}}';
                var word3 ='{{WORD3}}';
                var word4 ='{{WORD4}}';
                if ((word1 !=''&& word2 !=''&& word3 !=''&& word4 != '') ||(word1 ==''&& word2 ==''&& word3 !='' && word4!='') || (word1 ==''&& word2 ==''&& word3 =='' && word4!='')
                || (word1 ==''&& word2 !=''&& word3 !='' && word4!='') || (word1 !=''&& word2 !=''&& word3 =='' && word4=='') || (word1 !=''&& word2 ==''&& word3 =='' && word4!='')
                || (word1 !=''&& word2 ==''&& word3 !='' && word4 =='') || (word1 ==''&& word2 !=''&& word3 !='' && word4=='') || (word1 ==''&& word2 !=''&& word3 =='' && word4!='')
                || (word1 !=''&& word2 ==''&& word3 =='' && word4 =='') || (word1 ==''&& word2 !=''&& word3 =='' && word4=='') || (word1 ==''&& word2 ==''&& word3 !='' && word4!='')) {
                    var checkRow= true;
                } else
                var checkRow= false;


texts:
I just made this responsive image solution, but I'm not sure if it's the best way to do what I'm trying to achieve. Use cases can be found at http://responsimage.com/.

/* responsimage.com v0.2.3 */
(function ($, window, Date) {

    'use strict';

    $(function() {

        var rPrefs = $('meta[name="responsimage"]'),
            rServer = rPrefs.data('server'),
            rStatic = rPrefs.data('static') || 'http://f.cl.ly/items/0M3H0q3n1Z1S1y362d09/spacer.gif',
            rLoading = rPrefs.data('loading') || 'http://f.cl.ly/items/2w2G3N2p0B400Z380J1u/loading.gif',
            rLimit = rPrefs.data('limit') || 100,
            rTimestamp = new Date(),
            rTags = $('[data-responsimage]');

        function responsimage(rInit) {
            rTags.each(function() {
                var rThis = $(this),
                    filename = rThis.data('responsimage'),
                    rWidth = rThis.width(),
                    rHeight = rThis.height(),
                    rAnchor = rThis.data('responsimage-anchor') || 5,
                    rImage;

                if(rInit) {
                    rThis.attr('src', rStatic).css('background', '#fff url(' + rLoading + ') no-repeat center');
                }

                if(rThis.css('font-family') === 'pixel-ratio-2') {
                    rWidth *= 2;
                    rHeight *= 2;
                }

                rImage = rServer.replace('width', rWidth).replace('height', rHeight).replace('anchor', rAnchor).replace('filename', filename);

                if(filename !== 'disabled') {
                    rThis.attr('src', rImage);
                }
            });
        }

        responsimage(1);

        $(window).resize(function () {
            var rNow = new Date();

            if (rNow - rTimestamp >= rLimit) {
                responsimage(false);
            }
        });

        window.onorientationchange = function() {
            setTimeout(responsimage, 0);
        };
    });
}(jQuery, window, Date));


texts:
I have the following PHP logout script and I would like to know the loopholes present in it. How can I improve it?

<?php

require_once 'config.php';

if(session_id() != "") {
    session_destroy();
}

if(isset($_COOKIE[session_name()])) {
    // Delete the session cookie
    setcookie(session_name(), "", time() - 1);
}

if(isset($_COOKIE['authUser'])) {
    $cookie_contents = $_COOKIE['authUser'];
    list($selector, $plain_token) = explode(':', $cookie_contents);

    //Empty the values
    $query = $dbh->prepare("UPDATE auth_tokens SET token=:token, expires=:expires WHERE selector =:selector");
    $query->execute(array(
        ":token" => "",
        ":expires" => "",
        ":selector" => $selector
    ));

    $count = $query->rowCount();
    if($count == 0) {
        die('Something went wrong..Could not log you out.' );
    }

    // Delete the authentication cookie
    setcookie('authUser', "", time() - 1);
}

header('Location: login.php');


texts: Help optimizing a function to count the rows in a textarea

texts:
I am writing a script to count the number of rows in a textarea, and as it will be called on every keypress I want to make sure it runs as fast as possible. I'm not aiming for a general solution: we can assume that the textarea has a monospace font and enough horizontal space for exactly 80 characters.

I've probably solved this problem in 20 different ways, and this is by far the fastest solution I've come up with:

function countRows1(txt) {
    var i, len, rows = 0;
    txt = txt.split('\n');
    len = txt.length;
    for (i = 0; i < len; i++) {
        rows += Math.ceil(txt[i].length / 80) || 1;
    }
    return rows;
}

Here's a second solution, which is slightly faster in Firefox, but otherwise between a little and 5x slower:

function countRows2(txt) {
    var i = 0, nextBreak, rows = 0;
    while ((nextBreak = txt.indexOf('\n', i)) !== -1) {
        rows += Math.ceil((nextBreak - i) / 80) || 1;
        i = nextBreak + 1;
    }
    return rows + (Math.ceil((txt.length - i) / 80) || 1);
}

The performance doesn't make any sense to me - countRows2 does the same thing as countRows1, except it doesn't create any unnecessary strings or arrays. Is indexOf with a start position just really slow, or is there some optimization only the first method is picking up on?

Finally, here's one more method, which is much slower in every browser I've tested, but beautifully concise:

function countRows3(txt) {
    return txt.match(/\n?[^\n]{1,80}|\n/g).length;
}

Here's the jsPerf I'm using to compare the three.

So I've really got three questions:

Why is countRows2 slower than countRows1?
Is there any way to optimize the regex in countRows3 so the performance is comparable to the first two?
Is there any other way to speed up this code?

ps: I can't just do something like el.scrollHeight, because I need it to shrink as text is deleted. Also, I don't want to remember the previous count and just calculate the difference, because some changes will inevitably be missed and a differential script will never right itself.


texts:
I have a code which was not refactored at all. I refactored it to some extent, but stuck at a point where I cannot think of anything further.

Tractor.java:

package com.farm;

public class Tractor implements MethodsInterface {

    private int[] position;

    private int[] field;

    private String orientation;

    public Tractor(){
        position  = new int[]{0,0};
        field = new int[]{5,5};
        orientation = "N";
    }

    public void move(String command) {
        if(command=="F"){
            moveForwards();
        }else if(command=="T"){
            turnClockwise();
        }
    }

    private void moveForwards() {
        if(orientation=="N"){
            position = new int[]{position[0], position[1]+1};
        } else if(orientation == "E"){
            position = new int[]{position[0]+1, position[1]};
        } else if(orientation == "S"){
            position = new int[]{position[0], position[1]-1};
        }else if(orientation == "W"){
            position = new int[]{position[0]-1, position[1]};
        }
        if(position[0] > field[0] || position[1] > field[1]) {
            try {
                throw new TractorInDitchException();
            } catch (TractorInDitchException e) {
                e.printStackTrace();
            }
        }

    }

    private void turnClockwise() {
        if(orientation=="N"){
            orientation = "E";
        }else if(orientation == "E"){
            orientation = "S";
        }else if(orientation == "S"){
            orientation = "W";
        }else if(orientation == "W"){
            orientation = "N";
        }
    }

    public int getPositionX() {
        return position[0];
    }

    public int getPositionY() {
        return position[1];
    }

    public String getOrientation() {
        return orientation;
    }
}

TractorInDitchException.java:

package com.farm;

public class TractorInDitchException extends Exception{

}

MethodsInterface.java:

package com.farm;

public interface MethodsInterface {

    public int getPositionX();
    public int getPositionY();
    public String getOrientation();
}

What else could be refactored?


texts:
Here is the link of the problem for which I need your help.

I came up with solution and it is working fine for all cases, but it takes more time. I need your help in reducing the runtime of code. I unable to optimised it more.

#include <iostream>
#include <string>
using namespace std;

long nChoosek( unsigned n, unsigned k )
{
    if (k > n)
        return 0;
    if (k * 2 > n)
        k = n-k;
    if (k == 0)
        return 1;
    long result = n, temp;
    for( int i = 2; i <= k; ++i ) {
        result *= (n-i+1);
        result /= i;
    }
    return result;
}

int main()
{
    int n,q,i,j,left,right;
    cin>>n;
    int arr[n];
    for(i=0;i<n;i++)
    {
        cin>>arr[i];
    }
    cin>>q;
    string s;
    while(q--)
    {
        int b=0,r,q,re;
        long res=1;
        cin>>s >>left >>right;
        if(s=="change")
        {
            arr[left-1]=right;
        }
        else
        {
            for(i=left-1;i<right;i++)
            {
                b+=arr[i];
            }
            r=(right-left+1);
            q=(b/r);
            re=(b%r);
            res*=nChoosek(r,re);
            for(i=0;i<re;i++)
            {
                res*=nChoosek((b-(i*(q+1))),(q+1));
            }
            i=0;
            while((r-re-i) > 1)
            {
                res*=nChoosek(((r-re-i)*q),q);
                i++;
            }
                            res%=3046201;
            cout<<res<<endl;
        }
    }
    return 0;
}

I also tried to replace the function nChoosek

long nChoosek( unsigned n, unsigned k )
{
    if (k > n)
        return 0;
    if (k * 2 > n)
        k = n-k;
    if (k == 0)
        return 1;
    long result = n, temp;
    for( int i = 2; i <= k; ++i ) {
        result *= (n-i+1);
        result /= i;
    }
    return result;
}

By new recursive function ncr but no change in result:

long ncr(int n,int r)
{
    if((r==0)||(n==r))
        return 1;
    else
        return (ncr(n-1,r-1)+ncr(n-1,r));
}


texts: First prime number larger than given integer

texts:
How can I test this C program for "efficiency"? The most interesting usage is that it returns negative output for large enough input, otherwise the behavior is about expected. Will you suggest how to improve the code, both the ui used in main that should be both efficient and preferably platform-indepedent and not use too much libraries for portability and optimization. I think the obvious improvement that I can make is recoding the int to unsigned int:

/*
 * NextPrime
 *
 * Return the first prime number larger than the integer
 * given as a parameter. The integer must be positive.
 */
#define PRIME_FALSE   0     /* Constant to help readability. */
#define PRIME_TRUE    1     /* Constant to help readability. */
#include <stdio.h>
#include <stdlib.h>
int nextprime(int inval) {
    int perhapsprime; /* Holds a tentative prime while we check it. */
    int testfactor; /* Holds various factors for which we test perhapsprime. */
    int found; /* Flag, false until we find a prime. */

    if (inval < 3) /* Initial sanity check of parameter. */
    {
        if (inval <= 0)
            return (1); /* Return 1 for zero or negative input. */
        if (inval == 1)
            return (2); /* Easy special case. */
        if (inval == 2)
            return (3); /* Easy special case. */
    } else {
        /* Testing an even number for primeness is pointless, since
         * all even numbers are divisible by 2. Therefore, we make sure
         * that perhapsprime is larger than the parameter, and odd. */
        perhapsprime = (inval + 1) | 1;
    }
    /* While prime not found, loop. */
    for (found = PRIME_FALSE; found != PRIME_TRUE; perhapsprime += 2) {
        /* Check factors from 3 up to perhapsprime/2. */
        for (testfactor = 3; testfactor <= (perhapsprime >> 1) + 1; testfactor
                += 1) {
            found = PRIME_TRUE; /* Assume we will find a prime. */
            if ((perhapsprime % testfactor) == 0) /* If testfactor divides perhapsprime... */
            {
                found = PRIME_FALSE; /* ...then, perhapsprime was non-prime. */
                goto check_next_prime;
                /* Break the inner loop, go test a new perhapsprime. */
            }
        }
        check_next_prime: ; /* This label is used to break the inner loop. */
        if (found == PRIME_TRUE) /* If the loop ended normally, we found a prime. */
        {

            return (perhapsprime); /* Return the prime we found. */
        }
    }

    return (perhapsprime); /* When the loop ends, perhapsprime is a real prime. */
}

int main(int argc, char *argv[]) {
    int intvar;
    if (sscanf(argv[1], "%i", &intvar) != 1) {
        printf("please use an integer parameter to compute the next prime\n");
    } else
        printf("%d => %d\n", intvar, nextprime(intvar));
    return 0;
}


texts:
I have implemented a min heap in C++, and I want to improve it in every possible way. Could you please review it and let me know your suggestions/comments?

#include <iostream>
#include <vector>
#include <algorithm>  // std::swap

class MinHeap {

    private:
    std::vector<int> heap;

    void heapify(int);
    int parent(int);
    int left(int);
    int right(int);

    public:
    void insert(int);
    int extractMin();

};

// heapifies down the index-i
void MinHeap::heapify(int i) {

    int l = left(i);
    int r = right(i);

    // find the smallest amongst the parent, it's left & right child
    int smallest;
    smallest = (l != -1 && heap[l] < heap[i]) ? l : i;
    smallest = (r != -1 && heap[r] < heap[smallest]) ? r : smallest;

    // If heap[i] (parent) is the smallest, then it is already a Heap!
    if (smallest != i) {
        std::swap(heap[i], heap[smallest]);
        heapify(smallest);
    }
}

// Returns the index of the left-child of the ith element
// Returns -1 if the index > heap size
int MinHeap::left(int i) {
    int l = (((2 * i) + 1) < heap.size() - 1) ? (2 * i) + 1 : -1;
    return l;
}

// Returns the index of the Right-child of the ith element
// Returns -1 if the index > heap size
int MinHeap::right(int i) {
    int r = (((2 * i) + 2) < heap.size() - 1)? (2 * i) + 2 : -1;
    return r;
}

// Returns the index of the Parent of the ith element
// Returns -1 if parent-index < 0
int MinHeap::parent(int i) {
    int p = (((i - 1) / 2) >= 0)? (i - 1) / 2 : -1;
    return p;
}

// Returns the minimum element from the heap and also deletes it from the heap
int MinHeap::extractMin() {

    // back-up the root, it's the min value
    int min = heap[0];

    // copy the value of the very-last element into the root and delete the last element
    heap[0] = heap.back();
    heap.pop_back();

    // heapify-down the root
    heapify(0);

    return min;
}

// inserts a value at the right-spot in the heap, ensures the heap property is maintained.
void MinHeap::insert(int value) {

    // insert the new element at the end of heap
    heap.push_back(value);

    // bubble-up the new value to its right position, thus maintaining the heap property
    int i = heap.size() - 1;
    while (heap[parent(i)] > heap[i]) {
        std::swap(heap[parent(i)], heap[i]);
        i = parent(i);
    }

}


texts: Curiously Recurring Template Pattern (CRTP) implementation

texts:
I'm implementing Curiously Recurring Template Pattern(CRTP) in Java as follows.

The Interface:

/**
 * Reason for the generic Value<T extends Value>
 * Value<IntValue> x; // legal, IntValue implements Value interface so allowed
 * Value<Integer> x;  // illegal, does not implement Value interface
 */
@SuppressWarnings("rawtypes")
public interface Value<T extends Value> {
    T deepCopy();
}

Classes implementing it:

public class IntValue implements Value<IntValue> {
    Integer value;

    public IntValue(Integer value) {
        this.value = value;
    }

    public Integer getValue() {
        return value;
    }

    @Override
    public IntValue deepCopy() {
        return new IntValue(value);
    }
}
/**
* // Valid
* List<IntValue> ints = Arrays.asList(new IntValue(Integer.valueOf(5)));
* ArrayValue<IntValue> arr = new ArrayValue<>(ints);
*
* // Invalid
* List<Integer> ints = Arrays.asList(Integer.valueOf(5));
* ArrayValue<Integer> arr = new ArrayValue<>(ints);
*/
@SuppressWarnings("rawtypes")
public class ArrayValue<T extends Value> implements Value<ArrayValue<T>> {

    List<T> values;

    public ArrayValue() {
        this(new ArrayList<>());
    }

    public ArrayValue(List<T> values) {
        this.values = values;
    }

    @SuppressWarnings("unchecked")
    @Override
    public ArrayValue<T> deepCopy() {
        List<? super Value> copyValues = new ArrayList<>();
        values.forEach(value -> copyValues.add(value.deepCopy()));
        return new ArrayValue<T>((List<T>) copyValues);
    }
}

//Static Function using the interface
@SuppressWarnings("rawtypes")
public static Value sub(Value a, Value b)
{
    if(a instanceof IntValue && b instanceof IntValue)
    {
        return new IntValue( ((IntValue)a).getValue() - ((IntValue)b).getValue());
    }
    else
    {
        throw new TypeMismatchException("Operation not supported");
    }
    return NullValue.NULL_VALUE;
}

However I have to suppress warnings multiple times throughout the implementation.

Are the uses of suppress annotation justified?


texts: Validating string lengths of link attributes

texts:
Here is a working typescript code:

A modelValidator class that validates form user input. In this basic example it must check for length of form data submitted by user, and if one of the form field is invalid, it pushes error message into an array:

export let modelValidator = function (directoryModel: I.IDirectoryLink)
{
    let myArra: Array<string> = []

    myArra.push(
        // link_title length validation
        new StringLengthValidation(
            directoryModel.link_title, 0, 3,
            `Invalid title: length must be between 0 and 5 characters`).validateLength(),

        // link_desc length validation
        new StringLengthValidation(
            directoryModel.link_desc, 0, 3,
            `Invalid short description: length must be between 0 and 1024 characters`).validateLength(),

        // link_long_desc length validation
        new StringLengthValidation(
            directoryModel.link_desc, 0, 3,
            `Invalid long description: length must be between 0 and 1024 characters`).validateLength()
    )

    return myArra
}

And here is the StringLengthValidation class that abstracts the validation process:

class StringLengthValidation
{
    private stringContent: string
    private minLength: number
    private maxLength: number
    private validationErrorMessage: string

    constructor(stringContent: string, minLength: number, maxLength: number, validationErrorMessage: string)
    {
        this.stringContent = stringContent
        this.minLength = minLength
        this.maxLength = maxLength
        this.validationErrorMessage = validationErrorMessage
    }

    public validateLength()
    {
        // If string validation invalid, return error message, else is default underfined
        if (!validator.isLength(this.stringContent, { min: this.minLength, max: this.maxLength })) {
            return this.validationErrorMessage
        }
    }
}

That's how I would have done it, but I wonder if this is the proper way:
Should I do a single instantiation of the StringLengthValidation class in a variable in the modelValidator, then call the validateLength method? That would require passing the arguments into the validateLength method instead of in the constructor function.

Anyway, what's the best way to handle this situation?


texts:
This is a singleton class which can be accessed anywhere including the shouldLock variable. I want to make sure that the variable is thread safe. Basically the shouldLock is used to keep track if the user is allowed to use any other view controllers, unless they provide a password, in the app.

Is this the proper way to make a variable thread safe? Is there an easier or better way? I got my inspiration from here.

class LockNavigation {
    static var shared = LockNavigation()

    let queue = DispatchQueue(label: "LockNavigationQueue", attributes: .concurrent)

    var _shouldLock:Bool!
    var shouldLock:Bool{
        get{
            var copy:Bool!
            queue.sync(flags: .barrier) {
                copy = _shouldLock
            }
            return copy
        }

        set{
            queue.async(flags: .barrier) {
                self._shouldLock = newValue
            }
        }
    }

    private init() {
        shouldLock = false
    }
}


texts: Sum of absolute difference of values and corresponding indices of an array

texts:
I am solving questions on arrays from here.

  Problem: You are given an array of N integers, A1, A2 ,…, AN. Return maximum value of:

  f(i, j) for all 1 ≤ i, j ≤ N.

  f(i, j) is defined as |A[i] - A[j]| + |i - j|, where |x| denotes
  absolute value of x.

  Solution approach:

  |A[i] - A[j]| + |i - j| gives us 4 cases:

Case1:|A[i] - A[j]| + |i - j| = -A[i]+ A[j] - i + j = -(A[i]+ i) + ( A[j] + j)
Case2:|A[i] - A[j]| + |i - j| = -A[i]+ A[j] + i - j = -(A[i] - i) + (A[j]-j)
Case3:|A[i] - A[j]| + |i - j| = A[i]- A[j] - i + j  = (A[i] - i) - (A[j] -j)
Case4:|A[i] - A[j]| + |i - j| = A[i]- A[j] + i - j  = (A[i] + i) - (A[j] + j)

  Cases 1 and 4 are equivalent and can be find as the difference between
  the max and min value of A[i]+i

  Cases 2 and 3 are equivalent and can be find as the difference between
  the max and min value of A[i]-i

How can I perfect this code?

def max_abs_diff(array):
    """ returns sum of absolute difference of values and corresponding indices of an array"""
    max1=[]#array to store maximum values given by A[i] + i
    min1=[]#array to store minimum values given by A[i] + i
    max2=[]#array to store maximum values given by A[i] - i
    min2=[]#array to store minimum values given by A[i] - i

    for i, elem in enumerate(array):

        max1.append(elem + i)
        min1.append(elem + i)
        max2.append(elem - i)
        min2.append(elem - i)

    return max(max(max1) - min(min1) , max(max2)-min(min2))

Test cases:

print max_abs_diff([2,2,2]) == (2)
print max_abs_diff([2,-2,2])== (5)
print max_abs_diff([-4,-2,-3,-4,-5]) == (6)
print max_abs_diff([-1]) == (0)
print max_abs_diff([-5, 1, -3, 7, -1, 2, 1, -6, 5]) == (18)
print max_abs_diff( [6, -3, -2, 7, -5, 2, 1, -7, 6]) == (20)
print max_abs_diff([-5, -2, -1, -4, -7]) == (8)


texts: Decoding and encoding JSON for a PHP service

texts:
I am writing a PHP service which will listen for JSON requests (made using jQuery) and will return the JSON responses.

The whole template for such services (there will be 5) I have shortened into this template:

<?php

// set the headers which are accepted
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: origin, content-type, accept, authorization");
//header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS, HEAD");
header("Access-Control-Allow-Methods: POST");
header('Content-Type: application/json');

// "HTTPS-only " validation
$isSecure = false;
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
    $isSecure = true;
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' || !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') {
    $isSecure = true;
}

$REQUEST_PROTOCOL = $isSecure ? 'https' : 'http';

if (!$isSecure) {
    $response['status'] = 1;
    $response['message'] = 'Connection is not secure';
    http_response_code(400);
    echo json_encode($response);
    exit;
}

// !! for debug only !!
error_reporting(E_ALL);

// get the request data
$postdata = file_get_contents("php://input");

// decode
$request = json_decode($postdata, true);

$response = [];
try {
    if (true) {
        throw new Exception();  // validation not passed case
    }

    // proccess request data .. make calculations

    // all went successfull case
    $response['status'] = 0;
    $response['message'] = 'OK';
} catch (Exception $ex) {
    $response['status'] = 3;
    $response['message'] = 'Exception';
} finally {
    if ($response['status'] === 0) {
        // set the response code to 200: OK
        http_response_code(200);
    } else {
        http_response_code(400);
    }

    // output the answer
    echo json_encode($response);
}

Here is the approach I am using:

set the allowed headers
allow only HTTPS based calls (no HTTP)
decode the input data
make data validation and analysis
throw a custom Exception if some validation is not passed
in finally block echo the accumulated response variable

I am quite experienced when it comes down to PHP services so I am looking for an advice - if the above mentioned pattern/template can be improved in any way? Add additional validation?

The basic use cases are: new user registration/login/change password/get data specific to provided object ID, pushing some data to DB etc.


texts: Is there a beter way to check input besides a switch case?

texts:
So I am running a Switch case to check if a user has filled in all the necessary fields within a form, and if not I prompt them to do so. I was wondering if there was a better way to do this, or if a switch case like this would suffice. General suggestions/naming improvements would also be appreciated.

This runs inside the unity engine, on unity C#

void CheckEmptyValues()
{
    /* Step wise checks certain Necessary values, if things are not assigned it breaks the operation
     * And prompts the user to fill in the appropriate slot
     */
    int caseSwitch = 0;
    switch (caseSwitch)
    {
        case 0:
            if (GalleryName == null || GalleryName == "Default")
            {
                Debug.Log("No Gallery name assigned, please give the gallery a proper name");
                break;
            }
            else goto case 1;
        case 1:
            //This is a rectangle
            if (gallerySize.x == 0 || gallerySize.y == 0 || gallerySize.width == 0 || gallerySize.height == 0)
            {
                Debug.Log("No gallery Sizes assigned, please set some sizes before creating a gallery");
                break;
            }
            else goto case 2;

        case 2:
            if (buttonPrev == null || buttonNext == null)
            {
                Debug.Log(" Please make sure you assigned all textures before building, or you might end up with invisible buttons");
                break;
            }
            else goto case 3;

        case 3:
            //Location they want to get their images from (individual pick, or by path loading)
            if (!indvImages && !imgByPath)
            {
                Debug.Log("Please select a place to find images.");
                break;
            }
            else goto case 4;

        case 4:
            //Enable Bullet Buttons for the gallery
            if (enbBB)
            {
                if (activeBB == null || inactiveBB == null)
                {
                    Debug.Log("Please assign the bullet button textures, or disable the bullet buttons");
                    break;
                }
                else goto case 5;
            }
            else goto case 5;

        case 5:
            if (imgByPath)
            {
                if (!ImagesInsideProject && !ImagesOutsideProject)
                {
                    Debug.Log("Images by path is selected, but no location has been assigned. Assign the location, or select individual images instead");
                    break;
                }
                //Only occurs if user fiddles with undocumented settings.
                else if (AssignGallery== null)
                {
                    Debug.Log("File path is empty, please assign a location before continuing");
                    break;
                }
                else goto case 6;
            }
            else goto case 6;

        case 6:
            //if the fullscreen function is enabled, check if the textures for the minimize/maximize are set
            if (enbFullscreen)
            {
                if (fullScreenTex == null || fullScreenTexAlt == null)
                {
                    Debug.Log("Full screen has been assigned, but no textures have been. please assign textures for the full screen button, or disable full screen mode.");
                    break;
                }
                else goto case 7;
            }
            else goto case 7;

        case 7:
            CreateGallery();
            break;
    }
}


texts:
Can anyone help me improve my instr() function?

int myInstr(wchar_t *str, wchar_t c, int start, int dir){
    int pos = 0, result = 0, len;
    wchar_t *p1;

    //Left
    if(dir == 0)
    {
        p1 = str;
        len = lstrlen(str);
        while(pos < len)
        {
            if(*p1 == c)
            {
                result = pos;
                return result;
            }
            p1++;
            pos++;
        }
    }
    else
    {
      //Right
      pos = len = lstrlen(str);
      p1 = str;
      p1 += len;
      while(pos >= 0)
      {
          if(*p1 == c)
          {
              result = pos;
              return result;
          }
          p1--;
          pos--;
      }
    }
    return 0;
}


texts:
I made a struct that will loop through a list, and return the next element on calls to the Get() method.
It also allows to remove elements from the list by calling the Evict() method, and is safe for concurrent use.

I'd appreciate any feedback: what's ok, what's not, what could be improved or changed.

package generators

import (
    "errors"
)

var (
    ErrEmpty    = errors.New("no elements were given")
    ErrConflict = errors.New("found the same element twice")
)

// InfiniteWithEvict will circle through a list of elements until cancelled,
// allowing to remove elements if needed. It is safe for concurrent use.
// It needs to be created with NewInfiniteWithEvict(),
// started with
// InfiniteWithEvict.Start()
// and cancelled by calling the function returned by InfiniteWithEvict.Start().
type InfiniteWithEvict struct {
    elems   []interface{}
    evictC  chan interface{}
    getC    chan interface{}
    indices map[interface{}]int
}

// NewInfiniteWithEvict returns an InfiniteWithEvict object.
// The contents of the slice elems will be modified by calls to Evict() method.
func NewInfiniteWithEvict(elems []interface{}) (*InfiniteWithEvict, error) {
    if len(elems) == 0 {
        return nil, ErrEmpty
    }
    m := make(map[interface{}]int)
    for idx, elem := range elems {
        if _, ok := m[elem]; ok {
            return nil, ErrConflict
        }
        m[elem] = idx
    }
    return &InfiniteWithEvict{
        elems:   elems,
        evictC:  make(chan interface{}),
        getC:    make(chan interface{}),
        indices: m,
    }, nil
}

// Start starts the generator.
// Before calling start, calls to Get() and Evict() will block.
// It returns a function that must be called when you are sure that
// no more calls to Get() or Evict() will be made.
func (p *InfiniteWithEvict) Start() func() {
    cancel := make(chan struct{})
    go p.loop(cancel)
    return func() {
        cancel <- struct{}{}
    }
}

// Get returns the next element of the list.
func (p *InfiniteWithEvict) Get() interface{} {
    return <-p.getC
}

// Evict removes an element from the list.
func (p *InfiniteWithEvict) Evict(v interface{}) {
    p.evictC <- v
}

func (p *InfiniteWithEvict) loop(cancel <-chan struct{}) {
    i := 0
    for {
        select {
        case <-cancel:
            close(p.getC)
            return
        case v := <-p.evictC:
            index, ok := p.indices[v]
            if !ok {
                continue
            }
            p.elems[index] = p.elems[len(p.elems)-1]
            p.elems = p.elems[:len(p.elems)-1]
            delete(p.indices, v)
            if len(p.elems) == 0 {
                continue
            }
            p.indices[p.elems[index]] = index
            if i == len(p.elems) {
                i = 0
            }
        case p.getC <- func() interface{} {
            if len(p.elems) == 0 {
                return nil
            }
            return p.elems[i]
        }():
            if i == len(p.elems)-1 {
                i = 0
            } else {
                i = i + 1
            }
        }
    }
}


texts:
I have to print numbers between two limits n and m, t times.
I created t variable that stores a number of test cases.
Outer for loop iterates for every test cases.
Inner for loop prints primes from m to n.
Code
#include <stdio.h>
#include <stdlib.h>

int is_prime(int);

int main(void) {
    int t, m, n;
    scanf("%d", &t);
    for (int i = 0; i < t; i++) {
        scanf("%d %d", &m, &n);
        for (int j = m; j <= n; j++) {
            if (is_prime(j)) {
                printf("%d\n", j);
            }
        }
        if (i < t - 1) printf("\n");
    }

    return 0;
}

int is_prime(int num) {
    if (num <= 1) return 0;
    for (int i = 2; i * i <= num; i++) {
        if (num % i == 0) {
            return 0;
        }
    }
    return 1;
}

Problem: http://www.spoj.com/problems/PRIME1/
Can I have review?


texts:
I'm using this form to submit articles into the database:

<form enctype="multipart/form-data" method="post" action="add.php">

  <input name="title" type="text">
  <input name="image" type="file">
  <textarea name="text"></textarea>
  <input type="submit" name="go" value="Spremi">

</form>

include ("database.php");
$upload_path = "files/images/";
$prefix= date("Hi-mdY")."-";

$file_name = $HTTP_POST_FILES['image']['name'];
$file_name = str_replace(' ', '-', $file_name);
$file_name = str_replace('_', '-', $file_name);
$file_name = strtolower($file_name);

$upload_path = $upload_path . basename($prefix.$file_name);
move_uploaded_file($_FILES['image']['tmp_name'], $upload_path);

$final_file_name = ("/files/images/".$prefix.$file_name);
$date=date("Y.m.d");

$sql="INSERT INTO articles (title, image_link,  text, date) VALUES ('$_POST[title]', '$final_file_name', '$_POST[text]', '$date')"
if (mysql_query($sql)){
    echo "done";
} else {
    echo "error
" . mysql_error();
}

And here is the problem:

One of my friends told me that the PHP code in add.php is incorrect.

This is working for me, but can someone correct the code please.

EDIT:

Thanks guys, I've corrected the code :

<form enctype="multipart/form-data" method="post" action="">

  <input name="title" type="text">
  <input name="image" type="file">
  <textarea name="text"></textarea>
  <input type="submit" name="go" value="Submit">

</form>

<?php
  if (isset($_POST['go'])){
    include ("database.php");
    $upload_path = "files/images/";
    $prefix= date("Hi-mdY")."-";

    $file_name = $_FILES['image']['name'];
    $file_name = str_replace(' ', '-', $file_name);
    $file_name = str_replace('_', '-', $file_name);
    $file_name = strtolower($file_name);

    $upload_path = $upload_path . basename($prefix.$file_name);
    move_uploaded_file($_FILES['image']['tmp_name'], $upload_path);

    $final_file_name = ("/files/images/".$prefix.$file_name);

    $title=$_POST['title'];
    $text=$_POST['text'];
    $date=date("Y.m.d");

    $title = mysql_real_escape_string($title);
    $final_file_name = mysql_real_escape_string($final_file_name);
    $text = mysql_real_escape_string($text);

    $sql="INSERT INTO articles (title, image_link,  text, date) VALUES ('$title', '$final_file_name', '$text', '$date')";
    if (mysql_query($sql)){
      echo "done";
    } else {
      echo "error
" . mysql_error();
    }
  }
?>

Now it's good?


texts: Race condition of initialization with fail safe

texts:
I have the following usecase, I have a multi threaded environment and I want to initialize some parameters only only. The thing is that when I initialize the parameters I call a function that sometimes fails and takes some time to complete, on such case I want the next thread to retry the initialization. The implementation may look something like this:

private static boolean action(int i){
    try {
        Thread.sleep(500);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    double randomVal = Math.random();
    System.out.println(String.format("%d: random val is %s", i, randomVal));
    if(randomVal < 0.8) return false;
    //SET STATIC VARIABLES
    return true;
}

In order to handle the problem I came up with the following idea, I have a AtomicBoolean which tells me whether the parameters were initialized or not and I run the initialization code in a synchronized block. Inside every synchronized block I recheck the boolean to see if no thread has initialized the variables while I waited.

private static AtomicBoolean initialized = new AtomicBoolean(false);

public static void main(String[] args) {
    ExecutorService executors = Executors.newFixedThreadPool(15);

    IntStream.range(0,15).forEach(i -> {
        executors.submit(() -> {
            if(!initialized.get()){
                synchronized (Concurrncy.class){
                    if(!initialized.get()){
                        if(action(i)) initialized.set(true);
                    }
                }
            }
        });
    });

    executors.shutdown();
}

It seems a little of to recheck the boolean twice. To all the Java master please comment on the code (also the sample code) and tell me what can be done better


texts:
I have implemented a max-Heap data structure backed by an array. I wanted to know whether this is an acceptable implementation or not.

Any improvements or suggestions are welcome.

import java.util.Arrays;
import java.util.NoSuchElementException;

public class MaxHeapDemo {

  int heap[],heapSize=0;

public MaxHeapDemo() {
    // TODO Auto-generated constructor stub
    heapSize=0;
}

/**
 * Function to build the max-heap
 * @param inputData
 */
private  void maxHeapify(int[] inputData) {

    heap= new int [inputData.length+1];
    //fill the heap from 1 index to make life easier

    //if a parent node is at ith index the the left child is at 2*i and right child is at
    //2*i+1
    //  System.out.println("data ="+Arrays.toString(data));
    //insert from the back to the front

    for (int i = 0; i < inputData.length; i++) {
        heap[heapSize+1]=inputData[i];

        heapify(inputData[i]);
        ++heapSize;
    }
}

/**
 * This method will balance the heap according to the properties of the heap
 * @param value
 * @param data
 */
private  void heapify( int value/*, int[] data*/) {

    //int index = data.length-1;
    int index = heapSize+1;
    //System.out.println("index "+index+" heap[index/2]"+heap[index/2]);
    while (index > 1 && heap[index/2] < value ){
        //swap parent with child
        int temp= heap[index/2];
        heap[index/2]= heap[index];
        heap[index]=temp;

        index/=2;
    }

}

/**
 * THis method remove the maximum element from the heap and re-balances the heap according
 * to the Max heap property
 * @return
 */
public  int removeMax() {

if(heapSize == 0)
    throw new NoSuchElementException("The heap is empty");

    int result=-1;

    result = heap[1];
    heap[1]=heap[heapSize];
    --heapSize;

    //now balance the heap according to the max heap property

    for (int i=1;i < heapSize ; i*=2){
        if (i*2 < heapSize && heap[i]< heap[i*2] && heap [i*2] > heap[i*2+1]){
            //swap the two elements
            int max= heap[i*2];
            heap[i*2]=heap[i];
            heap[i]= max;
        }else if (i*2+1 < heapSize && heap[i]< heap[i*2+1]){
            int max= heap[i*2+1];
            heap[i*2+1]=heap[i];
            heap[i]= max;
        }
    }
    System.out.println(Arrays.toString(heap));
    return result;
}
public void add(int value){
    int index = heapSize+1;
    if(index >= heap.length) heap = Arrays.copyOf(heap, heapSize + 16);
    heap[index] = value;

    while (index > 1 && heap[index/2] < heap[index]){
        //swap parent with child
        int temp= heap[index/2];
        heap[index/2]= heap[index];
        heap[index]=temp;

        index/=2;
}
}

/**
 * Main method to test the program
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub

    MaxHeapDemo heapDemo = new MaxHeapDemo();
    heapDemo.maxHeapify(new int []{3,2,6,7,9});
    System.out.println(Arrays.toString(heapDemo.heap));
    System.out.println("the maximum element is ="+heapDemo.heap[1]);
    System.out.println("remmoved max ele is = "+heapDemo.removeMax());
}
}


texts:
I am a rock climber so I made a rock climbing game. I have two conceptual objects; the climber and the route. I ended up putting them both into a single Climber class, and made route an instance method on the class.

I feel like they should be separate, but I was having problems with inheritance, which is why I merged them.

I've also removed some other code to make this more succinct. My code works but I can't help but think it could be better - any and all feedback is appreciated.

import sys

print ("""We are playing a game today at Ship Rock. All the bros are
here. Most points wins.""")

class Climber(object):
    def __init__(self, climber_name, ability):
    self.climber_name = climber_name
    self.ability = ability
    self.routes_climbed = []
    self.energy_level = 100
    self.pump_level = 0
    self.total_score = 0
    self.pitch_count = 0

    def engine(self):
        next_action = input("What next? ")
        if next_action == "climb":
            self.climb_route((str(input("Enter route name: "))), (float(input("Enter route grade: " ))))
        elif next_action == "finish":
            self.grand_finale()

    def climb_route(self, route_name, grade):
        print ("Climbing...", route_name, " Grade...", grade)
        if grade < (.9 * self.ability):
            self.pump_level += (grade * .8)
        elif grade >= (.9 * self.ability):
            self.pump_level += (grade * 1.5)
        self.energy_level -= (grade * 1.7)
        self.total_score += grade
        self.routes_climbed.append(route_name)
        self.pitch_count += 1
        if self.energy_level <= self.pump_level:
            print ("Your day is over.")
            self.grand_finale()
        self.engine()

    def grand_finale(self):
        sys.exit() #quits program

climber1 = Climber("Erich Purpur", 13.0)
climber1.engine()


texts: Function to parse an XML and find specific regex considering the size attribute of the document

texts:
I'm writing a code that, starting from an XML file:

stores the index of child elements of a tag and the child elements as
key, values in a dictionary (function get_xml_by_tag_names);
deletes keys whose values contain a certain string (the specific text
size) and puts these keys and the corresponding values into a second
dictionary (def search_delete_append);
joins, for each dictionary, the dict values and extracts their
text(def main);
replaces certain values with "" (def main);
counts the occurrences of specific regex I specify (def find_regex).

It works, but the "main" function needs to be more cleaned up. My concerns specifically regard the part in which I have to list the regex I'm interested in- they're multiple and it can become messy. Another problem is that the cleaning of the XML can be done in another separate function, but so I haven't managed to do it.

Here is the code:

import re
from xml.dom import minidom
from xml.etree import ElementTree as ET
from bs4 import BeautifulSoup

def get_xml_by_tag_names(xml_path, tag_name_1, tag_name_2):

    data = {}
    xml_tree = minidom.parse(xml_path)
    item_group_nodes = xml_tree.getElementsByTagName(tag_name_1)
    for idx, item_group_node in enumerate(item_group_nodes):
        cl_compile_nodes = item_group_node.getElementsByTagName(tag_name_2)
        for _ in cl_compile_nodes:
            data[idx]=[item_group_node.toxml()]
    return data

def find_regex(regex, text):
    l = []
    matches_prima = re.findall(regex, text)
    print("The number of", {regex}," matches is ", len(matches_prima))

def search_delete_append(dizionario, dizionariofasi):
    deletekeys = []
    insertvalues = []
    for k in dizionario:
        for v in dizionario[k]:
            if "7.489" in v:
                deletekeys.append(k)
                dizionariofasi[k] = v

    for item in deletekeys:
        del dizionario[item]

def main():
    dict_fasi = {}
    data = get_xml_by_tag_names('output2.xml', 'new_line', 'text')
    search_delete_append(data, dict_fasi)

    testo = []
    for value in data.values():
        myxml = ' '.join(value)
        tree = ET.fromstring(myxml)
        tmpstring = ' '.join(text.text for text in tree.findall('text'))
        for to_remove in (" < ", " >", ".", ",", ";", "-", "!", ":", "’", "?", "<>"):
            tmpstring = tmpstring.replace(to_remove, "")
        testo.append(tmpstring)
    testo = ''.join(testo)
    #print(testo)
    find_prima = re.compile(r"\]\s*prima(?!\S)")
    #print(find_regex(find_prima, testo))
    #################

    testo_fasi = []
    values = [x for x in dict_fasi.values()]
    myxml_fasi = ' '.join(values)
    find_CM = re.compile(r"10\.238")
    print(find_regex(find_CM, myxml_fasi)) #quanti CM ci sono?
    #print(myxml_fasi)
    for x in dict_fasi.values():
        xxx= ''.join(x)
        tree2 = ET.fromstring(xxx)
        tmpstring2 = ' '.join(text.text for text in tree2.findall('text'))
        testo_fasi.append(tmpstring2)
    testo_fasi = ''.join(testo_fasi)
    print(testo_fasi)
    find_regex(find_prima, testo_fasi)

if __name__ == "__main__":
    main()


texts:
I am a beginner in Java programming, and I created a calculator as my first Java project. Therefore, can you review my code and provide feedbacks/ tips?

import java.util.Scanner;

public class Calculator {
    public static void main(String[] args) {

        double firstnum, secondnum, answer1, answer2, answer3, answer4, answer5, answer6;
        String text;
        int loop = 0;

        Scanner input = new Scanner (System.in);

        while (loop == 0) {

        System.out.println("Enter your first number: ");
        firstnum = input. nextDouble();

        System.out.println("Please enter the operation you would like to execute: ");
        text = input.next();

        System.out.println("Enter your second number: ");
        secondnum = input.nextDouble();

        answer1= firstnum+secondnum;
        answer2= firstnum-secondnum;
        answer3= firstnum*secondnum;
        answer4= firstnum/secondnum;
        answer5= (100*(firstnum/secondnum));
        answer6= Math.pow(firstnum,secondnum);

        switch (text) {

        case "+" :
            System.out.println(answer1);
            break;

        case "-" :
            System.out.println(answer2);
            break;

        case "*" :
            System.out.println(answer3);
            break;

        case "x" :
            System.out.println(answer3);
            break;

        case "/" :
            System.out.println(answer4);
            break;

        case "%" :
            System.out.println(answer5);
            break;

        case "^" :
            System.out.println(answer6);
            break;

        default :
            System.out.println("Your operation was not recongized.");

            }
        }
    }
}


texts:
A while ago I used this code to load content into a div using jQuery load. I repeated the code for all the clicks to load different pages in the same div.

Is there any other way to do this?

$("#button1").click(function(){
    $('#div1').load('page1.php');
});

$("#button2").click(function(){
    $('#div1').load('page2.php');
});

<div id="div1">      </div>


texts: Taking a screenshot of a particular window

texts:
I've got a function which takes a screenshot of a particular window. It's important that the screenshot works whether the window is focused/covered by other windows or not, hence why I've used PrintWindow.

This function takes 45ms to complete, and I was hoping to decrease that. The end goal is to:

Take a screenshot of a window based on a handle, which works even if the window is covered by a different window
Finally return a byte[] to be exported as a PNG using NodeJS.

screenshot.cs

using System.Runtime.InteropServices;
using System;
using System.Threading.Tasks;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows;
using System.Windows.Forms;

public class main
{
   [StructLayout(LayoutKind.Sequential)]
   private struct Rect
   {
      public int Left;
      public int Top;
      public int Right;
      public int Bottom;
   }

   [DllImport("user32.dll")]
   private static extern IntPtr GetWindowRect(IntPtr hWnd, ref Rect rect);

   [DllImport("user32.dll")]
   private static extern IntPtr GetClientRect(IntPtr hWnd, ref Rect rect);

   [DllImport("user32.dll")]
   private static extern IntPtr ClientToScreen(IntPtr hWnd, ref Point point);

   [DllImport("User32.dll", SetLastError = true)]
   [return: MarshalAs(UnmanagedType.Bool)]
   static extern bool PrintWindow(IntPtr hwnd, IntPtr hDC, uint nFlags);

   public static Bitmap CaptureWindow(IntPtr handle)
   {
      var rect = new Rect();
      GetClientRect(handle, ref rect);

      var point = new Point(0,0);
      ClientToScreen(handle, ref point);

      var bounds = new Rectangle(point.X, point.Y, rect.Right, rect.Bottom);
      var result = new Bitmap(bounds.Width, bounds.Height);

      using (var graphics = Graphics.FromImage(result))
      {
         IntPtr dc = graphics.GetHdc();
         bool success = PrintWindow(handle, dc, 0);
         graphics.ReleaseHdc(dc);
      }

      return result;
   }

   public static byte[] ImageToByte(Image img)
   {
      ImageConverter converter = new ImageConverter();
      return (byte[])converter.ConvertTo(img, typeof(byte[]));
   }
}

NodeJS code

const {K, U} = require('win32-api');
const user32 = U.load();
const edge = require('edge-js');
const ss = edge.func(path.join(__dirname, 'screenshot.cs'));

var hWnd = user32.FindWindowExW(0, 0, null, Buffer.from('application\0', 'ucs2'))
ss(hWnd, function (err, r) { fs.writeFileSync("screenshot.png", r); });


texts:
The problem / background

I have a project, BusinessProject, that currently stores some static data in memory using the Singleton pattern - we'll call this class GlobalData. This project is used in multiple applications, with different requirements on what data should be loaded into memory. One application, lets call this SubProject, only needs a subset of the data. The other project, MasterProject, calls SubProject as well as other functions within BusinessProject which require other data in GlobalData to be available in memory. My goal is to use inheritance to avoid storing the overlapping data twice, as well as let the project interfacing with BusinessProject easily define the requirements needed by simply calling the desired class.

Simplified Code

public class GlobalData
{
    protected static readonly GlobalData _Instance = new GlobalData();
    protected DateTime _lastUpdateDate = DateTime.MinValue;

    public Dictionary<string, class> Lookup { get; protected set; }
    public IList<DateTime> Dates { get; set; }
    public Dictionary<string, List<double>> DataSeries { get; protected set; }

    static GlobalData() { }
    private GlobalData() { }

    // each time the Instance requested, make sure the data doesn't need to be refreshed
    public static GlobalData Instance
    {
        get
        {
            if (!DateTime.Today.Date.Equals(_Instance._lastUpdateDate.Date))
                _Instance.LoadData();
            return _Instance;
        }
    }
    protected virtual void LoadData()
    {
        ...
        _lastUpdateDate = DateTime.Today;
    }
}

public class MasterData : GlobalData
{
    protected static new readonly MasterData _Instance = new MasterData();
    ... //extra data properties

    static MasterData() { }
    private MasterData() :base() {}

    protected override void LoadData()
    {
        base.LoadData();
        ... // load extra data properties
    }
}

Conclusion

I'm looking for any feedback on my implementation of the problem ! Thank you.


texts:
I have created a quiz function in my rails application. Since I want to track responses and make it a server-side application I created a table to record the responses of the questions people answer.

create_table "responses", force: :cascade do |t|
    t.bigint "question_id"
    t.bigint "answer_id"
    t.bigint "user_id"
    t.uuid "uuid", default: -> { "uuid_generate_v4()" }
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["answer_id"], name: "index_responses_on_answer_id"
    t.index ["question_id"], name: "index_responses_on_question_id"
    t.index ["user_id"], name: "index_responses_on_user_id"
  end

Each question can have 4 possible answers association with them. I want to create and check the response directly after the user clicks on it. To do this I created this bit of logic here.

<%= @question.prompt %>

<% @question.answers.each do |a| %>
    <%= form_for @response, url: send_wager_response_path, remote: true do |f| %>
        <%= f.hidden_field :user_id, value: current_user.id %>
        <%= f.hidden_field :question_id, value: @question.id %>
        <%= f.hidden_field :answer_id, value: a.id %>
        <%= f.submit "#{a.answer.titleize}", class: 'btn btn-block btn-lg btn-primary' %>
    <% end %>
<% end %>

The problem I have with this is that I am creating 4 different forms on the question page and passing the current user id, the answer id they select, and the question id. This seems a bit not-so DRY. Is there a way to improve on this concept?

I am currently looking into a action-cable based approach since this is a head-to-head application but this is a good place to start.


texts:
With the SDL library, I'm creating an SDL_Surface* at w and h dimensions.
SDL_Color is a struct with 4 unsigned char fields: a, r, g and b for alpha, red, green and blue. c1 is the origin color, c2 the destination color, and c is the color of the pixel at position (i,j).

That gradient works fine, but it is very basic and I'm just wondering if there is any way to optimize it, whether with a better SDL use or a faster algorithm.

SDL_Surface* DrawDescendingDiagonalGradient(SDL_Color& c1, SDL_Color& c2, int w, int h)    {
    SDL_Color c;
    SDL_Surface *s = SDL_CreateRGBSurface(0, w, h, 32, 0, 0, 0, 0);
    SDL_LockSurface(s);
    for (int j = 0; j < h; j++) {
        for (int i = 0; i < w; i++) {
            c.a = c1.a * (w + h - i - j) / (w + h) + c2.a * (i + j) / (w + h);
            c.r = c1.r * (w + h - i - j) / (w + h) + c2.r * (i + j) / (w + h);
            c.g = c1.g * (w + h - i - j) / (w + h) + c2.g * (i + j) / (w + h);
            c.b = c1.b * (w + h - i - j) / (w + h) + c2.b * (i + j) / (w + h);
            PutPixel32(s, i, j, SDL_MapRGBA(s->format, c.r, c.g, c.b, c.a));
        }
    }
    SDL_UnlockSurface(s);
    return s;
}


texts: Integrating the Ace embeddable code editor for editing HTML, CSS, and JavaScript

texts:
I am currently implementing the Ace-editor embeddable code editor. In to my application.

I use a div with a certain class(example: editor_js) to render the editor the div also gets a data attribute (data-key) corresponding with the name (example: Site[tagmanager]) of a textarea. The session from the div get stored in the textarea and saved. You can see my complete Javascript code below for all three editors(html, css and Javascript). Everything seems to work, but I feel that there is a lot of room for improvement en optimization. So I was wondering if you could look it over and give me some tips and/or suggestions on how I can improve it and make more maintainable.

The html

<textarea id="editor_js" class="form-control" **name="Site[tagmanager]"** style="display: none;"></textarea>
<div **class="editor_js"** **data-key="Site[tagmanager]"**></div>

The Javascript

$(function () {

//Html editor
ace.require("ace/ext/language_tools");
$('.editor_html').each(function (index) {
    var type = $(this).attr("data-key"); // This is the name of the target textarea
    var textarea = $('textarea[name="' + type + '"]').hide(); // the textare is hidden because the editor is loaded in a div
    ace.require("ace/ext/emmet");
    var editor = ace.edit(this);
    editor.setTheme("ace/theme/chrome");
    editor.getSession().setMode("ace/mode/html");
    editor.getSession().setValue(textarea.val());
    editor.getSession().on('change', function(){
        textarea.val(editor.getSession().getValue());
    });
});

//CSS editor
$('.editor_css').each(function (index) {
    var type = $(this).attr("data-key");
    var textarea = $('textarea[name="' + type + '"]').hide();
    var editor = ace.edit(this);
    editor.setTheme("ace/theme/chrome");
    editor.getSession().setMode("ace/mode/css");
    editor.setOptions({
        enableBasicAutocompletion: true,
        enableSnippets: true,
        enableLiveAutocompletion: true,
    });
    editor.getSession().setValue(textarea.val());
    editor.getSession().on('change', function(){
        textarea.val(editor.getSession().getValue());
    });
});

//javascript editor
$('.editor_js').each(function (index) {
    var type = $(this).attr("data-key");
    var textarea = $('textarea[name="' + type + '"]').hide();
    var editor = ace.edit(this);
    editor.setTheme("ace/theme/chrome");
    editor.getSession().setMode("ace/mode/javascript");
    editor.setOptions({
        enableBasicAutocompletion: true,
        enableSnippets: true,
        enableLiveAutocompletion: true,
    });
    editor.getSession().setValue(textarea.val());
    editor.getSession().on('change', function(){
        textarea.val(editor.getSession().getValue());
    });
});

});