texts: Is there a better way to create constants in javascript?

texts:
Isn't there a better way to create my constants that I can use elsewhere in my code ?

export default class AppConstants {
}

Object.defineProperty(AppConstants, 'APP_NAME', { value: 'iVoc'})
/*
*...
*Other constants
*/


texts:
I wrote a little C++ sorting routine for my Algorithm studies, but I feel that a lot can be skipped out.

I am aware that modern sort takes Iterators and comparator functions, let's disregard that for now. I just want to clean up this code. Specifically, I don't like the if and value variables.

I have looked into other solutions, but they didn't clear up much for me.

void SelectionSorter::sort(std::vector<int> &v){

    int currentIndex = 0;

    while (currentIndex < v.size()) {

        int indexOfSmallestItem = -1;
        int value = v[currentIndex];
        bool shouldSwap = false;

        for (int i = currentIndex; i < v.size(); i++) {
            if (v[i] < value) {
                value = v[i];
                indexOfSmallestItem = i;
                shouldSwap = true;
            }
        }

        if (shouldSwap) {
            int temp = v[currentIndex];
            v[currentIndex] = v[indexOfSmallestItem];
            v[indexOfSmallestItem] = temp;
        }

        currentIndex++;
    }
}


texts: Create Django objects on the fly. Better way to do it? And is the view the best place?

texts:
I have a model Sachbearbeiter that has a OneToOneField to the User model in django.contrib.auth.

class Sachbearbeiter(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    ...

I created a view to enable certain people to create a new Sachbearbeiter. There are three things that need to be done:

When a Sachbearbeiter is created, a corresponding User must be created automatically.
The Sachbearbeiter.user must point to the corresponding User automaticallly.
When a User is created, the username must match the given email address.

I implemented this in my view.

def sachbearbeiter_create(request):
    user_form = UserForm(request.POST or None)
    sachbearbeiter_form = SachbearbeiterForm(request.POST or None)

    if request.method == 'POST':
        if user_form.is_valid() and sachbearbeiter_form.is_valid():
            user = user_form.save(commit=False)
            user.username = user.email
            user.save()
            sachbearbeiter = sachbearbeiter_form.save(commit=False)
            sachbearbeiter.user = user
            sachbearbeiter.save()

    ...

    return render(request, 'sachbearbeiter/detail_neu.html', {'user_form': user_form, 'sachbearbeiter_form': sachbearbeiter_form})

And those are the forms:

class SachbearbeiterForm(ModelForm):
    class Meta:
        model = Sachbearbeiter
        fields = ["verein", ]

class UserForm(ModelForm):
    class Meta:
        model = User
        fields = ["first_name", "last_name", "email"]

    def __init__(self, *args, **kwargs):
        self.base_fields['first_name'].required = True
        self.base_fields['last_name'].required = True
        self.base_fields['email'].required = True

        super(UserForm, self).__init__(*args, **kwargs)

I have two questions:

I have the feeling there is a better way to create to instances and link them to each other, than what I did in the view. Are there any improvements I could do?
Is the view really the right place to implement that logic?


texts: Using prototype to simulate extending a 'base class' object in JavaScript

texts:
I'm investigating using prototypes in JavaScript to simulate using 'base classes' which can be 'extended'. I've created an example where dialogBox is my 'base' and welcomeMessage is the 'extension'.

// OBJECT CONSTRUCTORS

var dialogBox = function(xPosition, yPosition, width, height){
    this.x = xPosition;
    this.y = yPosition;
    this.width = width;
    this.height = height;
    this.draw = function(){
        STAGE.fillRect(this.x, this.y, this.width, this.height);
        STAGE.strokeRect(this.x, this.y, this.width, this.height);
    };
};

var welcomeMessage = function(messageString){
    this.message = messageString;
    this.addMessage = function(){
        STAGE.strokeText(this.message, this.x + 10, this.y + 10, this.width-10);
        console.log(this.message);
    };
};
welcomeMessage.prototype = new dialogBox();

This works as intended (or at least gives the appearance of working as intended) - see this fiddle.

However, the way I have to instantiate these objects seems rather inelegant:

var box1 = new dialogBox(20, 20, 300, 100);

var box2 = new welcomeMessage('hello there');
box2.x = 20;
box2.y = 140;
box2.width = 300;
box2.height = 100; // wouldn't it be great if I could pass these properties as args?

I wrote these constructors using the MDN Object.prototype reference and am following their example quite closely, but I've observed from reading around Stack Overflow / Code Review many examples where prototyping is used very differently, often in relation to getters and setters. This is leading me to question if I have quite grasped the 'proper' use of prototype.

Any feedback is welcome, but I am particularly interested in identifying any potential problems my approach could cause when applied to more complex situations.


texts: Converting bits to decimal (integer) string is so slow

texts:
I am implementing myself a BigInteger class. It can natively handle very very big digits in very short time.

2 ^ 200000 == Time Elapsed : 12.343
Number of binary digits : 200001

The only problem is, when I do std::cout << foo;, I have to wait for very very long. Because my BigInteger class has to perform a std::string multiplication and a std::string increment on very single bit. As the number of bits increases, it might even take ages to finish.

Printing foo took 160.485 second(s) // It is so so long!!!

I have actually optimized my outputting algorithm to the best of my abilities. Some tricks include using reference, using array temp variables for fast caching. But for very very big numbers, it is still not fast enough.

Here is my code :

void BigInteger::doubleNumberString_1A63(std::string &string_input, std::string &string_tmp)
{
    int64_t i;
    int32_t t, t_1 = 0, t_2;

    string_tmp = "";

    char buffer[1024];
    int32_t n = 0;

    for(i = string_input.size() - 1; i >= 0; i--)
    {
        t = t_1 + (string_input[i] - '0') * 2;

        t_1 = t / 10;
        t_2 = t % 10;

        buffer[n++] = (char)('0' + t_2);
        if(n == sizeof(buffer)){string_tmp.append(buffer, n); n = 0;}
    }

    if(t_1 >= 1) buffer[n++] = (char)('0' + t_1);
    if(n) string_tmp.append(buffer, n);
}

void BigInteger::incrementNumberString_1A63(std::string &string_input, std::string &string_tmp, int32_t inc_val = 1)
{
    int64_t i;
    int32_t t, t_1 = 0, t_2;

    string_input = "";

    char buffer[1024];
    int32_t n = 0;

    for(i = 0; i < string_tmp.size(); i++)
    {
        t = t_1 + (string_tmp[i] - '0') + inc_val;

        t_1 = t / 10;
        t_2 = t % 10;

        inc_val = 0;

        buffer[n++] = (char)('0' + t_2);
        if(n == sizeof(buffer)){string_input.append(buffer, n); n = 0;}
    }

    if(t_1 >= 1) buffer[n++] = (char)('0' + t_1);
    if(n) string_input.append(buffer, n);

    std::reverse(string_input.begin(), string_input.end());
}

void BigInteger::printRawBinaryToDecimal(std::ostream &os) const
{
    const BigInteger &num = (*this);

    int64_t i;
    int64_t num_sz = num.size();

    if(BIG_INTEGER_INTEGER_DIGIT_BASE_A8F23ABC == 2)
    {
        std::string buf_base10 = "0";
        std::string buf_basetmp;

        // num.operator[](i) // --> Access each bit
        for(i = num_sz - 1; i >= 0; i--)
        {
            doubleNumberString_1A63(buf_base10, buf_basetmp);
            incrementNumberString_1A63(buf_base10, buf_basetmp, BigInteger::IntegerUnit::toDigit(num.operator[](i)));
        }

        os << buf_base10;
    }
}

std::ostream &operator << (std::ostream &os, const BigInteger &num)
{
    num.printRawBinaryToDecimal(os); return os;
}

Here we go, for each bit, the BigInteger class has to call doubleNumberString_1A63 and incrementNumberString_1A63, and it is the traditional method (and slow of course). Could anyone greatly improve it or suggest even a faster algorithm? I would really appreciate it.


texts:
What is a good way to compose std::function objects in C++?

I tried the following, and it seems to work well:

template<typename ... Fs>
struct compose_impl
{
    compose_impl(Fs&& ... fs) : functionTuple(std::forward_as_tuple(fs ...)) {}

    template<std::size_t> struct int2type{};

    template<size_t N, typename ... Ts>
    auto apply(int2type<N>, Ts&& ... ts)
    {
        return std::get<N>(functionTuple)(apply(int2type<N+1>(),std::forward<Ts>(ts)...));
    }

    static const size_t size = sizeof ... (Fs);
    template<typename ... Ts>
    auto apply(int2type<size-1>, Ts&& ... ts)
    {
        return std::get<size-1>(functionTuple)(std::forward<Ts>(ts)...);
    }

    template<typename ... Ts>
    auto operator()(Ts&& ... ts)
    {
        return apply(int2type<0>(), std::forward<Ts>(ts)...);
    }

    std::tuple<Fs ...> functionTuple;
};

template<typename ... Fs>
auto compose(Fs&& ... fs)
{
    return compose_impl<Fs ...>(std::forward<Fs>(fs) ...);
}

With this, one can compose functions as long as the signatures fit together. Example:

auto f1 = [](std::pair<double,double> p) {return p.first + p.second; };
auto f2 = [](double x) {return std::make_pair(x, x + 1.0); };
auto f3 = [](double x, double y) {return x*y; };
auto g = compose(f1, f2, f3);

std::cout << g(2.0, 3.0) << std::endl;   //prints '13', evaluated as (2*3) + ((2*3)+1)

Comments and suggestions for improvement are welcome!


texts: Custom Web Api asynchronous filter implementation

texts:
Following the tutorial from Filip W's blog, I've ended up creating my own implementation for a custom ActionFilter.

This logs the execution name, action, parameters and elapsed time of every ApiController in my solution.

The post is a bit old (2013), that's why I'm still thinking it must be a better/simpler way to do this, any suggestion? improvements?

public sealed class LogActionFilter : FilterAttribute, IActionFilter
{
    private readonly Stopwatch _stopwatch = new Stopwatch();

    public bool AllowMultiple => false;

    public async Task<HttpResponseMessage> ExecuteActionFilterAsync(HttpActionContext actionContext,
        CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
    {
        await InternalActionExecuting(actionContext);

        if (actionContext.Response != null)
            return actionContext.Response;

        HttpActionExecutedContext executedContext;
        try
        {
            var response = await continuation();
            executedContext = new HttpActionExecutedContext(actionContext, null)
            {
                Response = response
            };
        }
        catch (Exception exception)
        {
            executedContext = new HttpActionExecutedContext(actionContext, exception);
        }

        await InternalActionExecuted(executedContext);
        _stopwatch.Reset();

        return executedContext.Response;
    }

    private Task InternalActionExecuting(HttpActionContext actionContext)
    {
        _stopwatch.Start();
        return Log("Executing", actionContext, 0);
    }

    private Task InternalActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        _stopwatch.Stop();
        return Log("Executed", actionExecutedContext.ActionContext, _stopwatch.ElapsedMilliseconds);
    }

    private Task Log(string action, HttpActionContext actionContext, long elapsedTime)
    {
        return Task.Run(() =>
        {
            var controllerName = actionContext.ControllerContext.ControllerDescriptor.ControllerName;
            var actionName = actionContext.ActionDescriptor.ActionName;
            var parameters = string.Join(", ", actionContext.ActionArguments.Values.Select(x => x).ToArray());

            var message = $"{action}: ctrl: {controllerName}, act: {actionName}, params: {parameters}" +
                          $"{(elapsedTime > 0 ? "took (ms): " + elapsedTime : string.Empty) }";

            Trace.WriteLine(message, "Action filter log");
        });
    }
}


texts: Increase performance of removing character from String

texts:
I wrote this function as part of interview practice. This method removes a character from a given string.

I was wondering how I could make this code more efficient when it comes to runtime/space. I think my code is O(n) and I'm not sure if I can increase the efficiency. However, perhaps using things such as StringBuffer or StringBuilder would increase it a bit? I'm not sure as I'm still a bit new to Java.

public static String takeOut(String str, char c) {
    int len = str.length();
    String newstr = "";
    for (int i = 0; i < len; i++) {
        if (str.charAt(i) != c) {
            newstr = newstr + str.charAt(i);
        }
    }
    return newstr;
}


texts: Construct binary tree from inorder and postorder traversal

texts:
The problem is taken from here.  The tree is guaranteed not to have duplicate elements.

My questions is, instead of creating new arrays leftInOrder, rightInOrder, leftPostOrder, rightPostOrder, I could simply pass the indexes to the same input arrays to the recursive function. Does that help in any way?

Basically, any way Java would pass the entire array by value to the recursive function, creating new arrays and passing them only would reduce the load on the stack. I would like to know if this is the best method.

    import java.util.Arrays;
    public class Solution {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) { val = x; }
    }
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        if(inorder==null || inorder.length<1)return null;
        int rootVal=postorder[postorder.length-1];
        TreeNode root= new TreeNode(rootVal);

        int mid=0;
        for(int i=0;i<inorder.length;i++){
            if(inorder[i]==rootVal){
                mid=i;
                i=inorder.length;
            }
        }

        int leftCount=mid;

        int[] leftInOrder= Arrays.copyOfRange(inorder,0,mid);
        int[] rightInOrder= Arrays.copyOfRange(inorder,mid+1,inorder.length);

        int[] leftPostOrder= Arrays.copyOfRange(postorder,0,leftCount);
        int[] rightPostOrder= Arrays.copyOfRange(postorder,leftCount,postorder.length-1);

        root.left=buildTree(leftInOrder,leftPostOrder);
        root.right=buildTree(rightInOrder,rightPostOrder);

        return root;

    }
}


texts:
This code takes a list of ints and sums their pairs, storing the summed pairs in an array sumPairs, then returning that array. If the supplied array toSum has an odd number of elements, it returns the sumPairs with the last element of the toSum as the last element of sumPairs. Any suggestions for improving my code, or accomplishing this task in a better way, would be most appreciated!

public static int[] collapse(int[] toSum) {
    int[] sumPairs = new int[toSum.length / 2 + toSum.length % 2];
    for (int i = 0, j = 0; i < toSum.length - 1; i+=2, j++) {
        sumPairs[j] = toSum[i] + toSum[i + 1];
    }
    if (toSum.length % 2 == 1 && sumPairs[sumPairs.length - 1] == 0) {
        sumPairs[sumPairs.length - 1] = toSum[toSum.length - 1];
    }
    return sumPairs;
}


texts: Merge consecutive numbers in array into a range

texts:
Input: I have sorted array of numbers [ 12, 15, 16, 17, 19, 21, 22 ]

Output: I need to merge all consecutive numbers into a dash-separated ranges like this "12, 15-17, 19, 21, 22"

I came up with such code (jsbin - https://jsbin.com/dusuvihiko/edit?js,console):

const input = [ 12, 15, 16, 17, 19, 21, 22 ];

const output = input.reduce((acc, curr, i, arr) => {
  if (curr - 1 === arr[i - 1] || i === 0) {
    acc.currSet.push(curr);
  } else {
    if (acc.currSet.length > 2) {
      acc.out.push(`${acc.currSet.shift()}-${acc.currSet.pop()}`);
    } else {
      acc.out.push(acc.currSet.join(','));
    }
    acc.currSet = [curr];
  }
  if (i === arr.length - 1) {
    if (acc.currSet.length > 2) {
      acc.out.push(`${acc.currSet.shift()}-${acc.currSet.pop()}`);
    } else {
      acc.out.push(acc.currSet.join(', '));
    }
  }
  return acc;
}, {
  out: [],
  currSet: [],
})
console.log(output.out.join(', '));

But I can see it looking ugly and not really optimized (code duplicating)

I would appreciate any suggestions on how to improve the code and make it look better and possibly work faster


texts: Swift iOS rewrite a function that use Firebase database without updating a global variable

texts:
I'm learning swift programming and i built a music trivia app for iOS that use firebase real time database.
I have a function that before the game start get the number of record for each category of the game and update a class variable that is a tuple called records.
var records = (classical: 0, mix: 0, casual: 0)

private func getNumberOfRecords(category: String)  {
    var ref: DatabaseReference!
    ref = Database.database().reference().child(category)
    ref.observeSingleEvent(of: .value) { snapshot in
        let enumerator = snapshot.children
        while((enumerator.nextObject() as? DataSnapshot) != nil) {
            switch category {
            case "casual":
                records.casual += 1

            case "classical":
                records.classical += 1

            case "mix":
                records.mix += 1

            default: print("Error loading record from category \(category)")
            }
        }
    }
}

Here is how I call the function and because it's asynchronous the response I receive from firebase and I need to know the number of records before call another function that will load the game data from the database i use DispatchQueue and wait 3 seconds.
getNumberOfRecords(category: "classical")
getNumberOfRecords(category: "casual")
getNumberOfRecords(category: "mix")
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
  loadDataFromDB(records: records.classical, category: "classical")
  loadDataFromDB(records: records.casual, category: "casual")
  loadDataFromDB(records: records.mix, category: "mix")
}

Now this is working but it's pretty ugly, especially using the function getNumberOfRecords to update the global tuple records. I don't know how can I rewrite this because if i make getNumberOfRecords return a tuple rather than update the global one is always 0 when i pass it as parameter of the function loadDataFromDB inside the DispatchQueue.
Thanks in advance to anyone will have time to read this.


texts: Convert a string like 4h53m12s to a total number of seconds in JavaScript

texts:
At the moment I have this:

function getValue(str)
{
 let result = 0;

 var regex = /(\d+[a-z]+)/g;
 match = regex.exec(str);

 while (match != null)
 {
  var match_str  = match[0];
  var last_char  = match_str[match_str.length-1];

  if ( last_char == 'h' )
   result += parseInt(match_str) * 3600;
  if ( last_char == 'm' )
   result += parseInt(match_str) * 60;
  if ( last_char == 's' )
   result += parseInt(match_str);

  match = regex.exec(str);
 }

 return result;
}

console.log( getValue("4h12m32s") );

It feels quite clumsy though. Also checking invalid values like 4hs feels difficult.

Is there any clever trick for something similar?


texts:
I am trying to prevent CSRF for my login page (linked from here), and for this I am going to use a random token generator to create a UUID for the session.

The function that I have so far is as such:

function UUID()
{
    mt_srand((double)microtime()*10000);
    $charid = strtoupper(md5(uniqid(rand(), true)));
    $hyphen = chr(45);
    $uuid =  substr($charid, 0, 8).$hyphen
            .substr($charid, 8, 4).$hyphen
            .substr($charid,12, 4).$hyphen
            .substr($charid,16, 4).$hyphen
            .substr($charid,20,12);
    return $uuid;
}

This function is working perfect and on a loop of 30 runs it gives me this result:

  E1BDBF20-A481-AD53-648F-C89E5242B934
  E2329CE9-B79D-999A-C61F-65C3C3976EBE
  B2FE5771-60DE-9E9B-ADF2-1A78B6BD8BC4
  77384406-B472-8192-E301-50CCA1E0CC10
  7854EF9F-991F-90D9-ACA5-07C01C25F355
  EB4D6BC0-6AB1-9020-0C94-BCB81C540EA9
  0AAABBCC-B53F-AF23-2D18-92B971AFD76C
  298FAE1A-F25A-7BF9-ECA9-3C5E80CCBC82
  0533A8D8-AC1F-3A94-FD51-8A95B69DB9C7
  CC650B31-14B6-8709-9E6C-84AA307E77DA
  52AEE9D4-FAC4-7AEC-DB31-882CA61A6AE6
  EED5154B-7425-ED7C-95A1-2239A79F0FAC
  42094233-09D7-BB08-8404-908889B5AB6C
  1A3C9D28-4FF3-5A4B-1994-AFE189D02C01
  4F5D3BC5-C94A-CFD5-87C1-4E2903811DF0
  6BC0612C-93EE-DE33-299B-44888BCCC670
  D7029641-ED26-C136-C5BB-6A6C932A1354
  AB3CF87D-8FA1-C38F-13AA-BFEEA016122C
  687DC395-CF5C-2797-F825-9122D179D6B4
  7970708B-F266-B308-6DA5-49DB190C9326
  ABF5494D-C8B3-976D-42D6-FE108BFF593E
  F0A3A1C0-3A57-EED3-54FB-60C644C8F329
  7A687548-B0B3-E266-E473-74E9BE6D45BE
  A445E134-A9FD-E554-D6E7-E6D1DE9D1046
  F8FCE8F8-7B2C-92E4-00B3-9F834BCE1E9A
  982E093A-0D93-AEAC-DEC3-EFEFA9401EEE
  353E75FC-80B5-6177-F987-4EAF77BC4F97
  8262F39E-F4C0-B60B-9007-A533BC043600
  3810166A-38AC-1275-2593-922CD25E42C6
  59E6A361-8FEA-FE81-B75E-927FC439159E

But it seems like there is a better way of creating this, although I have tried to use com_create_guid, this did not give quite the result I wanted.


texts: Given an integer, return its binary representation. You cannot use any Integer.toXXXString methods

texts:
Here is my code:

package com.app;

public class Solution {

    public String toBinaryString(int n) {
        char[] buffer = new char[32];
        for (int i = 0; i < buffer.length; i++) {
            buffer[i] = '0';
        }
        int i = buffer.length - 1;
        while (n != 0) {
            if (n % 2 != 0) {
                buffer[i] = '1';
            }
            i--;
            n >>>= 1;
        }
        return new String(buffer);
    }
}

And I also wrote a few tests:

package com.app;

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;

class SolutionTest {

    @Test
    void one() {
        Solution solution = new Solution();
        assertEquals("00000000000000000000000000000001", solution.toBinaryString(1));
    }

    @Test
    void minusOne() {
        Solution solution = new Solution();
        assertEquals("11111111111111111111111111111111", solution.toBinaryString(-1));
    }

    @Test
    void intMin() {
        Solution solution = new Solution();
        assertEquals("10000000000000000000000000000000", solution.toBinaryString(Integer.MIN_VALUE));
    }

    @Test
    void intMax() {
        Solution solution = new Solution();
        assertEquals("01111111111111111111111111111111", solution.toBinaryString(Integer.MAX_VALUE));
    }

    @Test
    void even() {
        Solution solution = new Solution();
        assertEquals("00000000000000000000000001111100", solution.toBinaryString(124));
    }

    @Test
    void odd() {
        Solution solution = new Solution();
        assertEquals("00000000000000000000000000100101", solution.toBinaryString(37));
    }
}

The problem seems to be pretty easy. However, it took me some time to make it work with negative numbers and some edge cases. So I'd greatly appreciate if you noticed any bugs in my code.


texts:
I'm writing a sudoku col/row validator, what is does is:

Reads user input on how many Sudoku instances to validate.
Reads the sudoku matrix grid 9x9 (for me, in my specific case 9x9) into a 2d array. Each line read/row should contain something like: 8 2 1 3 6 4 9 7 5.
Validates each row and column by flipping a 9 bit bitset to test whether all columns and rows contains nums from 1-9.

Please note that the only purpose of this program is to validate sudoku columns/rows as specified and not to completely validate it. i.e also checking each sudoku block.

How can I improve my code? I believe there's lots to it, naming conventions, fundamental approach...etc..etc.

#include <iostream>
#include <sstream>
#include <bitset>

namespace Constants
{
    constexpr int ROW_COL_SIZE = 9;
    const std::string STR_YES = "YES";
    const std::string STR_NO = "NO";
}

template<unsigned int N>
class Sudoku
{
private:
    int m_matrix[N][N] {{0}};
public:
    void ReadRows();
    std::string strIsValid() const;
};

template<unsigned int N>void Sudoku<N>::ReadRows()
{
    for(unsigned int row{0}; row<N; row++)
    {
        static std::string line;
        std::getline(std::cin, line);
        std::istringstream issline(line);
        int readnum {0};
        for(unsigned int i{0}; i<N; i++)
        {
            issline >> readnum;
            m_matrix[row][i] = readnum;
        }
    }
}

template<unsigned int N>std::string Sudoku<N>::strIsValid() const
{
    //9bit default ctor all zeroes, 000000000
    std::bitset<N> bitRow[N];
    std::bitset<N> bitCol[N];
    for(int i{0}; i<N; i++)
    {
        for(int j{0}; j<N; j++)
        {
            bitRow[i].flip(m_matrix[i][j]-1); //verify nums 1-9 row, bitset index is 0 not 1.
            bitCol[i].flip(m_matrix[j][i]-1); //verify nums 1-9 col
        }
        if(!bitRow[i].all() && !bitCol[i].all())
        {
            return Constants::STR_NO;
        }
    }
    return Constants::STR_YES;
}

int main(int, char**)
{
    int instances {0};
    std::cin >> instances;
    std::cin.clear();
    std::cin.ignore();

    for(int i{0}; i<instances; i++)
    {
        std::cout << "Instance " << i+1 << std::endl;
        Sudoku<Constants::ROW_COL_SIZE> sudokuInstance;
        sudokuInstance.ReadRows();
        std::cout << sudokuInstance.strIsValid() << std::endl << std::endl;
    }

    return 0;
}


texts:
I'm trying to keep the code as clean as possible. Is this the best approach? I don't use jQuery that often.

// ==============================================
// Trigger longer description on product page
// ==============================================
var longDescription = $j("#js-long-description");
var shortDescription = $j("#js-shortened-description");
var showHide = $j("#js-trigger-long-description");
var inSpeed = 500;
var outSpeed = 100;

longDescription.hide();

showHide.on("click", function () {

    var buttonTxt = longDescription.is(':visible') ? 'Read More' : 'Read Less';

    showHide.text(buttonTxt);

    if (longDescription.is(':visible')) {

        shortDescription.fadeIn(inSpeed);
        longDescription.fadeOut(outSpeed);

    } else {

        shortDescription.fadeOut(outSpeed);
        longDescription.fadeIn(inSpeed);

    }
});


texts:
I am doing the POJ 1002 question. My code works fine but the website says the compilation time is more than 2000ms, which is not accepted. How can I improve my time-wise performance?
Problem Statement

Input — The input will consist of one case. The first line of the input specifies the number of telephone numbers in the directory (up to 100,000) as a positive integer alone on the line. The remaining lines list the telephone numbers in the directory, with each number alone on a line. Each telephone number consists of a string composed of decimal digits, uppercase letters (excluding Q and Z) and hyphens. Exactly seven of the characters in the string will be digits or letters.
Output — Generate a line of output for each telephone number that appears more than once in any form. The line should give the telephone number in standard form, followed by a space, followed by the number of times the telephone number appears in the directory. Arrange the output lines by telephone number in ascending lexicographical order. If there are no duplicates in the input print the line:
No duplicates.

import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;

public class Main{

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    int total = scan.nextInt();
    scan.nextLine();                // But why?
    String[] numbers = new String[total];
    Map<String, Integer> dict = new TreeMap<String, Integer>();

    for(int i = 0; i < total; i++) {
        numbers[i] = scan.nextLine();
        numbers[i] = convert(numbers[i]);
        if(!dict.containsKey(numbers[i])) {
            dict.put(numbers[i], 1);
        } else {
            dict.put(numbers[i], dict.get(numbers[i]) + 1);
        }
    }

    scan.close();

    boolean hasDuplication = true;
    for(String number: dict.keySet()) {
        if(dict.get(number) > 1) {
            hasDuplication = false;
            System.out.println(number + " " + dict.get(number));
        }
    }
    if(hasDuplication) {
        System.out.println("No duplicates.");
    }
}

public static String convert(String raw) {
    raw = raw.replaceAll("-", "");
    raw = raw.toLowerCase();
    String number = "";
    for(int i = 0; i < raw.length(); i++) {
        number += parse(raw.charAt(i));
    }
    number = number.substring(0, 3) + "-" + number.substring(3);
    return number;
}

public static char parse(char digit) {
    if(digit >= 'a' && digit < 'q') {
        digit = (char) ((digit-'a') / 3 + '2');
    } else if(digit > 'q' && digit < 'z') {
        digit = (char) ((digit-'q') / 3 + '7');
    }
    return digit;
}

}


texts:
I would appreciate critique and comments in regards of thread-safety on a basic type I'm trying to create.

In C#, the Lazy<T> type is initialized only once, and only when needed the first time.

My type, called Snoozy<T>, is similar, but differs in one important aspect:

The value can be reinitialized when necessary (but only when read).

The purpose is to not perform the value factorization unless someone needs the new value. This could prevent e.g. unnecessary heavy calculations.

Example: A bank account stores a long list of events describing withdrawals and deposits. To get the current balance, all transactions need to be summed up. This could potentially be a very CPU-intensive operation, but the adding of new transactions is rare whereas reading the balance is frequent. When adding a new transaction, there is really no need to recalculate the balance until someone explicitly wants to read it.

This is the code I've come up with so far:

public class Snoozy<T>
{
    private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();
    private readonly Func<T> _factory;
    private T _value;
    private bool _isStale;

    public Snoozy(Func<T> valueFactory)
    {
        _factory = valueFactory;
        _isStale = true;
    }

    public T Value
    {
        get
        {
            _lock.EnterUpgradeableReadLock();

            if (_isStale)
            {
                _lock.EnterWriteLock();

                _value = _factory();
                _isStale = false;

                _lock.ExitWriteLock();
            }

            _lock.ExitUpgradeableReadLock();

            return _value;
        }
    }

    // This is how the consumer signals that the underlaying value has changed.
    public void Poke()
    {
        _lock.EnterWriteLock();
        _isStale = true;
        _lock.ExitWriteLock();
    }

    public static implicit operator Snoozy<T>(T value)
    {
        return new Snoozy<T>(() => value);
    }

    public static implicit operator T(Snoozy<T> snoozy)
    {
        return snoozy.Value;
    }
}


texts:
What is benefit of using uppercased() / lowercased() over the following approach ? (Other than making it more readable)

Any comments on perf ?

Can this be further improved ?

Example : for input : ABcDe, Expected Output is : abCdE

var solve = {(str: String) -> String in
    var arr = [Character]()
    for char in str.unicodeScalars {
        char.value > 96 ? arr.append(Character(UnicodeScalar(char.value - 32)!)) : arr.append(Character(UnicodeScalar(char.value + 32)!))
    }
    return String(arr)
}

solve("Nipun")


texts: PHP array return array vs passing as reference

texts:
I'm not sure if Code Review is the proper SE site. If not, please point me in the right direction.

Let's assume we have a simple function, where you can pass an array and it will do some work on it. For simplicity sake, let's just assume you pass an array of integers to the function and it doubles them

I was wondering what's the correct way to do this, either by passing an array, and returning that array, which is AFAIK a pass by value in PHP and finally overwriting the initial variable, or simply passing a reference to that array.

Option 1, pass by value:

public function doubleValue(array $input): array
{
    foreach ($input as $key=>$val) {
        $input[$key] += $val;
    }

    return $input;
}

// called as $foo = $someClass->doubleValue($foo);

Option 2, pass by reference:

public function doubleValue(array &$input): void
{
    foreach ($input as $key=>$val) {
        $input[$key] += $val;
    }
}

// called as $someClass->doubleValue($foo);

My assumption would be, that pass by reference has to be faster, as it doesn't need to copy the array to that function, copy it back and assign it to the variable, but I could be wrong (at least ex. the built in sort function works this way). Are there any metrics about it? What is the recommended approach?


texts:
I have a Parent and a Child class, each with their own state. The Parent maintains an array of children saving their values from their state.

React 101 says that I should lift the state up from the child and set the array from there. There's also this question that asks how to access child's state on SO, with a popular answer that suggest Refs could be used. However the docs say Refs should be used (sparingly) for accessing elements, not state.

So I've come up with what I think is half way between lifting state up, and passing props down. The intent being that it reduces clutter in the Parent state:

//Parent Component
import React, { Component } from 'react';

class Parent extends Component {

    constructor(props) {
        super(props);
        this.state = {
            field1: '',
            field2: '',
            children: [],
        };
        this.handleChange = this.handleChange.bind(this);
    }

    handleChange(event) {
        const target = event.target;
        const value = target.type === 'checkbox' ? target.checked : target.value;
        const name = target.name;
        this.setState({[name]: value});
    }

    // Push children into the Parent's array
    handleAddChild(child) {
        this.setState((prevState) => ({
            children: [...prevState.children, child]
        }));
    }

    render() {
        return (
            <form>

                    <input name="field1" type="number" value={this.state.field1} onChange={this.handleChange} />

                    <input name="field2" type="number" value={this.state.field2} onChange={this.handleChange} />

                <input name="save" type="button" value="save" onClick={this.handleSave} />
            </form>

                //Pass the addChild method down through props
                <Child onSave={this.handleAddChild} />

        );
    }
}

// Child Component
import React, { Component } from 'react';

class Child extends Component {
    constructor(props) {
        super(props);
        this.state = {
            field3: '',
            field4: '',
        };
        this.handleChange = this.handleChange.bind(this);
    }

    handleChange(event) {
        const target = event.target;
        const value = target.type === 'checkbox' ? target.checked : target.value;
        const name = target.name;
        this.setState({[name]: value});
    }

    handleSave(event) {

        // Pass the state up to the Parent
        this.props.onSave(this.state);
    }

    render() {
        return (
            <form>

                    <input name="field3" type="number" value={this.state.field3} onChange={this.handleChange} />

                    <input name="field4" type="number" value={this.state.field4} onChange={this.handleChange} />

                <input name="save" type="button" value="save" onClick={this.handleSave} />
            </form>
        );
    }
}

Is this an acceptable way to access a child's state? Am I going to run into any issues doing it this way?


texts: Finding the prime factors of a number in Python 2

texts:
I’ve created a function that takes a number and, if it’s prime, tells you so, or if it’s composite, gives you the prime factors of the number (and if it’s 1, tells you that it’s neither).
Theoretically it should work for an infinitely large number, but at 8 digits it starts to slow down significantly, particularly if the prime factors are large. I’m fairly new at Python, so I’d welcome any feedback, especially on how to make it faster.
I’m aware that there are things I could have done more efficiently from the start — some of which I’ve become aware from looking at other Python questions in this same vein on this site — but while I would find advice like ‘this bit’s ill-conceived, rip it out and write something else entirely’ helpful, I’d prefer best-practices things, and ways to make it faster without totally changing the premises (as it were).
I haven’t annotated it because (as far as I’m aware), it’s fairly basic; any old hack could write this, but obviously I can annotate if you’d like.
Thanks!
Here’s the code (in Python 2):
import math
def prime_factors(y):
 n = y
 def is_prime(x):
    count = 0
    if x > 1:
      for i in range(2, x):
        if x % i != 0:
          count += 1
        else:
          return False
          break
    else:
        return True
    if count != 0:
        return True
    if x == 2:
      return True
 def make_p_lst(x):
   z = []
   for i in range(2, x):
     if is_prime(i) == True:
       z.append(i)
   return z

 c = 0
 c = int(math.sqrt(y) + 1)
 prime_lst = []
 prime_lst = make_p_lst(c)
 p = is_prime(y)
 if p == True and y != 1:
   print '%s is prime.' % (y)
   return 'Thus, its\' only factors are 1 and itself.'
 elif y != 1:
   print '%s is composite, here are its\' prime factors: ' % (y)
   factors_lst = []
   while is_prime(y) != True:
      for i in prime_lst:
        if y % i == 0:
          y = y/i
          factors_lst.append(i)
   factors_lst.append(y)
   factors_lst.sort()
   if factors_lst[0] == 1:
     factors_lst.remove(1)
   n = factors_lst
   return n
 else:
   return '1 is neither prime nor composite.'
print prime_factors(871)


texts: Learning Java: Celcius to Fahrenheit Conversion

texts:
This is a short Celcius to Fahrenheit conversion calculator that calculates the average of all entries before exiting. This program performs exactly to the required specification.
I have some concern about the cleanliness of the multiple variable declaration and initialization to zero in a single line. I've seen this done on a few sites, and it works, but is it conventional to see Java variables initialized in this way?
Regarding assigning everything zero, is it more or less appropriate to give a variable a value when declaring it?
I'm also concerned with the double conversion variable in the if statement, is this is scoped properly, or should conversion be declared with the other variables?
These were just a few of points I noticed myself, please review for syntax, convention, and readability.
package temperature;

import java.util.Scanner;

public class Temperature {

public static void main(String[] args) {
    int counter = 0;
    double input = 0;
    double celciusInputs, fahrenheitInputs = celciusInputs = 0;

    Scanner in = new Scanner(System.in);

    do {
      System.out.print("Enter Temp in Centigrade or <= -100.0 to quit: ");
      input = in.nextDouble();
      if (input > -100.0) {
        double conversion = ((9.0/5.0) * input) + 32.0;
        System.out.printf("Temperature: F(%.1f) C(%.1f)\n", conversion, input);
        celciusInputs += input;
        fahrenheitInputs += conversion;
        counter += 1;
      }
    } while (input > -100.0);

    // Calculate averages
    celciusInputs /= counter;
    fahrenheitInputs /= counter;

    System.out.printf("Average: Centigrade (%.1f) Average: Fahrenheit(%.1f)",
            celciusInputs, fahrenheitInputs);

    in.close();
  }
}


texts: Counting the most frequently appearing character in a string (i.e. the statistical mode)

texts:
This is my sample code to find maximum occurrence of characters in string in C#.

How can I make it better?

public static int GetMaximumOccurence(string str)
{
    int _maxcount = 0;

    foreach (char c in str)
    {
        int ix = str.IndexOf(c);
        int count = 0;
        while (ix!=-1)
        {
            StringBuilder _s = new StringBuilder();
            _s.Append(str);
            _s[ix] = ' ';
            str = _s.ToString();

            count++;

            ix = str.IndexOf(c);
        }

        if (count > _maxcount)
        {
            _maxcount = count;
        }
    }

    return _maxcount;
}


texts: A C function for returning the address of the calling function

texts:
Suppose you are given two functions, foo and bar, and neither of them are inlined. Now, if foo calls for bar and bar calls for called_from, bar receives the address of the caller, that is, the address of foo. I know that there is no real need for such computation as it is always possible to simply pass an enumeration that indicates the caller, yet I was in the mood for hacking the stack.

My code compiles on Visual Studio.

main.cpp:

#include <stdio.h>

/************************************************************************
* Suppose that foo() calls for bar() and bar() calls for called_from(). *
* Now if neither bar() and foo() are inlined functions, bar() receives  *
* the address of foo() from the function called_from().                 *
************************************************************************/
void* called_from() {
    __asm {
        mov eax, [ebp]
        mov eax, [eax]     // foo's ebp
        mov eax, [eax + 4] // foo's return address
        mov edx, eax;      // we might need a copy of
                           // the foo's return address

        sub eax, 5;        // the adress of the instruction 'call foo'
        mov bl, [eax]      // the opcode of the call instruction
        inc eax            // [eax] points to the address of foo

        mov eax, [eax];    // load the caller's address

        cmp bl, 0xE8
        je RelationalAddress // the address is relational

        cmp bl, 0xFF
        je Exit              // the adress is absolute
        jmp Abort

        RelationalAddress:
        add eax, edx         // convert relational address
                             // to an abolute one
        jmp Exit

        Abort:
        mov eax, 0           // failure, return null pointer
        Exit:
    }
}

// We need the macro as otherwise it will obscure the actual caller.
#define is_called_from(n) (called_from() == (void*) n)

Here are a few tests:

void foo();
void bar();
void baz();

int main() {
  printf(
      "main:\t0x%p\n"
      "foo: \t0x%p\n"
      "bar: \t0x%p\n"
      "baz: \t0x%p\n"
      "\n",
      main,
      foo,
      bar,
      baz);

  foo();
  bar();
  baz();

  getchar();
  return 0;
}

void foo() {
  printf("This is foo:\n"
         "called from %p\n"
         "that is, from ",
         called_from());

  if (is_called_from(main))
  {
      puts("main.\n");
  }
  else if (is_called_from(bar))
  {
      puts("bar.\n");
  }
  else
  {
      puts("somewhere else.\n");
  }
}

void bar() {
  printf("This is bar:\n"
         "called from 0x%p\n"
         "\n",
         called_from());

  foo();
}

void baz() {
  printf("This is baz:\n"
         "called from 0x%p\n"
         "\n",
         called_from());

  foo();
}


texts: Combine Medical Response Files Prior To Table Load

texts:
This is a script I wrote to:

Combine multiple text files into one CSV
Append the source file's name to each line of data

This script currently takes about 3 seconds per 10,000 lines read - this is so long in comparison to a working batch/Perl script I have that I'm wondering what I'm doing wrong.

Comments about whether this is even the best approach is welcome - anything that gets me one combined file with the source file name appended to each line is welcome. I chose to use StreamReader because the source files are very large.

Powershell

# Powershell -executionpolicy bypass -file (.ps1 file path)

[System.IO.DirectoryInfo]$ResponsesFolder = (folder path)
[System.IO.DirectoryInfo]$pathCombinedResponsesCSV = ($ResponsesFolder.Parent.FullName + [IO.Path]::DirectorySeparatorChar + $ResponsesFolder.BaseName + "_Combined_Responses.csv")

if (Test-Path $pathCombinedResponsesCSV) {
    Remove-Item $pathCombinedResponsesCSV
}

$streamWriter = New-Object System.IO.StreamWriter $pathCombinedResponsesCSV
Write-Host $pathCombinedResponsesCSV

$files = Get-ChildItem -Path ($ResponsesFolder.ToString() + "*.*") -File
$totalFiles = $files.Count

$fileindex = 0

$files | ForEach-Object {
    $streamReader = New-Object System.IO.StreamReader $_.FullName

    [int]$fileindex = $fileindex + 1
    Write-Host ("File " + $fileindex + " of " + $totalFiles)

    [string]$fileName = $_.Name

    [int]$lineIndex = 0

    while (([string]$line = $streamReader.ReadLine()) -ne $null) {
        $streamWriter.WriteLine($line + "|" + $fileName)
        $lineIndex = $lineIndex + 1

        if ($lineindex % 10000 -eq 0) {
            Write-Host $lineindex "lines of" $fileName "loaded"
        }
    }

    $streamReader.Close(); $streamReader.Dispose()

}

$streamWriter.Close(); $streamWriter.Dispose()

Batch/Perl

pushd (UNC folder path)

copy *.TXT *.csv

REM Add filename to end of each record.
net use b: /delete /y
net use b: (UNC folder path)
for /f %%a IN ('dir /b (UNC folder path)*.csv"') do (perl -i.bak -p -e "s/\n/|$ARGV\n/" %%a )

copy *.csv Consolidated_Magic_File.csv


texts:
I have two code snippets and the following questions:

Which uses the best practice and why?
Which one is good for performance?

Code 1

jQuery( function( $ ) {

    // Responsive video
    var $area = $( "#sidebar" );
    $area.fitVids();

    // Image gallery
    var $slider = $( ".owl-carousel" );
    $slider.owlCarousel();

});

Code 2

// Global jQuery variable
var $ = jQuery;

/**
 * Responsive video
 */
var fitvidsInit = function() {
    var $area = $( "#sidebar" );
    $area.fitVids();
};

/**
 * Slides
 */
var sliderInit = function() {
    var $slider = $( ".owl-carousel" );
    $slider.owlCarousel();
};

/**
 * Execute code
 */
$( function() {
    fitvidsInit();
    sliderInit();
} )

I also have to defined the variable $ because this is in WordPress.


texts:
This script converts a server load value into percentage, compares it with non desired state ($warning and $critical) and returns all information in NRPE (Nagios Remote Plugin Executor) friendly output.

Desired output:

CPU_CORES=1 load=0.30 | load_in_percent=30;95;100
(And the main thing exit code.)

Goal: Use so much less external commands how is possible. Why? I would like to have the script independent. The second thing is just training purpose of bash scripting.

#!/usr/bin/env bash

set -o errexit -o pipefail

warning=95
critical=100

# 1. Find out a load was before 15 minutes.
# citation: "Frankly, if your box spikes above 1.0 on the one-minute average, you're still fine. It's when the 15-minute average goes north of 1.0 and stays there that you need to snap to."
# source: Andre Lewis, https://scoutapm.com/blog/understanding-load-averages
read -r _ _ quarter_load_average _ _ < /proc/loadavg

# 2. Count all cores.
# citation: "How the cor es are spread out over CPUs doesn't matter. Two quad-cores == four dual-cores == eight single-cores. It's all eight cores for these purposes."
# source: Andre Lewis, https://scoutapm.com/blog/understanding-load-averages
while read -a row; do
  if [[ ${row[0]} = "cpu" ]] && [[ ${row[1]} = "cores" ]]; then
    cpu_cores=$(( cpu_cores + "${row[3]}" ))
  fi
done < /proc/cpuinfo

# 3. Convert load value into percentage.
# citation: "Sometimes it's helpful to consider load as percentage of the available resources (the load value divided by the number or cores).
# source: https://access.redhat.com/solutions/30554
load_mlt=$(echo "$quarter_load_average*100/1" | bc)
load_prc=$(( "$load_mlt" / "$cpu_cores" ))

# 4. Compare result with desired status and prepare returned value.
if [[ -z "$load_prc" ]]; then
  returned_text="LOAD UNKNOWN - check script"
  returned_code=3
else
  returned_text="CPU_CORES=$cpu_cores load=$quarter_load_average | load_in_percent=$load_prc;$warning;$critical"
  if [[ $load_prc -gt $critical ]]; then
    returned_code=2
  elif [[ $load_prc -gt $warning ]]; then
    returned_code=1
  else
    returned_code=0
  fi
fi

echo "$returned_text"
exit $returned_code


texts:
I was reading this post and saw quite few improvements. So I tried to rewrite it using Java 8 features. Any improvements you can spot, please feel free to mention.

public static void main(String[] args) {

    boolean runAgain = false;
    Double result = .0;
    List<Double> inputs = new ArrayList<Double>();
    Scanner scanner = new Scanner(System.in);
    do {
        System.out.print("Enter the first number : ");
        inputs.add(scanner.nextDouble());
        System.out.print("Enter the second number : ");
        inputs.add(scanner.nextDouble());
        System.out.print("Enter the operator : ");
        String op = scanner.next();

        result = calculateAnswer(inputs, op);
        System.out.println("Answer : "+result);

        System.out.print("Do you want to try again?[Y/N] : ");
        runAgain = scanner.next().equals("Y")?true : false;

    } while (runAgain);

    System.out.println("Program finished!");
    scanner.close();
}

static Double calculateAnswer(List<Double> inputs, String operator){

    Operations[] ops = Operations.values();
    Operations correctOp = Arrays.asList(ops).stream()
            .filter(op -> op.getSymbol().equals(operator))
            .findFirst().get();

    return correctOp.getResult(inputs.get(0), inputs.get(1));
}

enum Operations{
    ADD(){
        @Override
        String getSymbol() {
            return "+";
        }
        @Override
        Double getResult(Double d1, Double d2) {
            return d1 + d2;
        }
    },SUB{
        @Override
        String getSymbol() {
            return "-";
        }
        @Override
        Double getResult(Double d1, Double d2) {
            return d1 - d2;
        }
    },MUL{
        @Override
        String getSymbol() {
            return "*";
        }
        @Override
        Double getResult(Double d1, Double d2) {
            return d1 * d2;
        }
    },DIV{
        @Override
        String getSymbol() {
            return "/";
        }
        @Override
        Double getResult(Double d1, Double d2) {
            return d1 / d2;
        }
    };

    abstract Double getResult(Double d1, Double d2);

    abstract String getSymbol();
}


texts:
This is the code for my first CS1 project, I hope to be posting my code here to track my progress of learning the language of C++.  I shouldn't be too shabby, since I know C considerably well and have reviewed C++ code here before.

  Write a program that allows the user to enter a time in seconds and
  then outputs how far an object would drop if it is in freefall for
  that length of time.  Assume that the object starts at rest, there is
  no friction or resistance from air, and there is a constant
  acceleration of 32 feet per second due to gravity.  Use the equation:

  $$
\text{distance} = \dfrac{\text{acceleration} \cdot\text{time}^2}{2}
$$

rock.cpp:

/**
 * @file rock.cpp
 * @brief Determines the height that a rock falls (in feet) after a given time
 * @author syb0rg
 * @date 9/8/14
 */

#include <iostream>
#include <cmath>

int main(void)
{
    // initialize variables on declaration
    double time = 0;
    double acceleration = 32.174;

    std::cout << "Enter the time in seconds that a rock will fall: ";
    std::cin >> time;

    double feetFallen = (acceleration * pow(time, 2)) / 2;

    std::cout << "The rock fell " << feetFallen << " feet." << std::endl;
}


texts: Rewrite from .. where .. select to more compact one

texts:
This is the code:

public DateTime GibSomeStartDate(IEnumerable<int> partnerNumbers, DateTime startTime)
{
     return (from contract in this.databaseContext.Contract
             where partnerNumbers.Contains(contract.Pnr) && contract.SomeDateTime >= startTime
             select contract.SomeDateTime).Min();
}

databaseContext Instance is child of Entity Framework DbContext

My refactorings objectives:

make it compact
check if from where select finds nothing. In this
situation Min() will cause an Excetion


texts: WordPress plugin development - plugin-name.php file and plugin files/folders structure

texts:
I am creating my first WP/WooCommerce plugin. I was following instructions from WordPress Codex during development, but I wanted to review it here, to make sure I am on the right path. First things I would like to get reviewed are plugin-name.php file and plugin file/folders structure.

Questions/doubts:

I was using singleton classes. Is that ok?
Did I miss something in plugin-name.php file? Is everything needed there?
Is order of code OK in plugin-name.php file? Are if statements OK?
About project folder and files structure, is it ok to put my global.css and functions.php in the root of the plugin, along with plugin-name.php file, or should I move them into folder(s)? If yes, how should I name those folders?
If there is something that should be different beside these things I mentioned above, please let me know.

plugin-name.php file:

<?php
/**
 * Plugin Name:     {Plugin name}
 * Plugin URI:      https://github.com/tahireu/{plugin_name}
 * Description:     {Description}
 * Version:         1.0.0
 * Author:          Tahireu
 * Author URI:      https://github.com/tahireu/
 * License:         GPL
 * License URI:     http://www.opensource.org/licenses/gpl-license.php
 */

/*
 * Prevent intruders from sneaking around
 * */
defined( 'ABSPATH' ) or die( 'No script kiddies please!' );

/*
 * Variables
 * */
const {PLUGIN_NAME}_TEXT_DOMAIN = "wc-{plugin-name}";

/*
 * Load {PLUGIN_NAME}_Activator class before WooCommerce check
 * */
require plugin_dir_path( __FILE__ ) . 'includes/class-{plugin_name}-activator.php';

/*
 * Check if WooCommerce is installed and active
 * */
include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
if ( is_plugin_active( 'woocommerce/woocommerce.php' ) ) {

    /*
     * Current plugin version - https://semver.org
     * This should be updated as new versions are released
     * */
    define( 'WC_{PLUGIN_NAME}_VERSION', '1.0.0' );

    /*
     * Load functions and classes
     * */
    require plugin_dir_path( __FILE__ ) . 'functions.php';
    require plugin_dir_path( __FILE__ ) . 'admin/class-{plugin-name}-admin.php';
    require plugin_dir_path( __FILE__ ) . 'public/class-{plugin-name}-public.php';

    /*
     * Create database table on plugin activation
     * */
    function create_table(){
        {PLUGIN_NAME}_activator::create_{plugin-name}_table();
    }

    register_activation_hook( __FILE__, 'create_table' );

    /*
     * Do the work
     * */
    {PLUGIN_NAME}_admin::on_load();
    {PLUGIN_NAME}_public::on_load();

} else {

    /*
     * Abort and display info message
     * */
    {PLUGIN_NAME}_activator::abort();

}

Plugin files/folders structure:


texts:
I have a template I've been using with Swift for UIViewController and UIView subclasses without a .xib or .storyboard. I want to know how this stacks up against other people's implementations. One weird thing about it is you have to use contentView to access the view, which is kind of similar to UITableViewCell.

Example of a view controller / view that was made using the template:

MyViewController:

import UIKit

class MyViewController: UIViewController {

    // MARK: - View

    var contentView: MyView {
        guard let contentView = self.view as? MyView else {
            fatalError("Cannot create content view")
        }
        return contentView
    }

    // MARK: - View lifecycle

    override func loadView() {
        self.view = MyView()

        // Relationships between view controller and view
        contentView.addingButton.addTarget(self, action: #selector(myButtonTapped), for: .touchUpInside)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    // MARK: Actions

    func amyButtonTapped(sender: UIButton) {
        // ...
    }

    // MARK: - Memory manager

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

MyView

import UIKit

class OneWayView: UIView {

    // MARK: - Subviews var
    let myButton: UIButton = {
        let button = UIButton(type: .custom)
        button.translatesAutoresizingMaskIntoConstraints = false
        button.setTitle(NSLocalizedString("myButton", comment: ""), for: .normal)
        button.setTitleColor(.orange, for: .normal)
        button.setTitleColor(.lightGray, for: .highlighted)
        return button
    }()

    // MARK: - View lifecycle

    override init(frame: CGRect) {
        super.init(frame: frame)

        // Setup this view
        addSubview(myButton)
        myButton.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
        myButton.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


texts:
I have two buttons, + and -, to add a zoom attr to a container. I'm not sure how I can rewrite this in fewer line of code.

jsFiddle

var ZOOM_OFFSET = 20;
var MAX_ZOOM = 60;
var MIN_ZOOM = 0;

$('.schedule-zoom .zoom-btn:not(.disable)').click(function(){
  var action_button = $(this);
  var zoom_out_button = $('.schedule-zoom .zoom-out');
  var zoom_in_button = $('.schedule-zoom .zoom-in');

  var container = $('.fixed-container');
  if (container.attr("zoom") === undefined) {
    container.attr("zoom", 0);
  }
  var zoom_value = parseInt(container.attr("zoom"));

  if (action_button.hasClass("zoom-in")) {
    zoom_out_button.removeClass("disable");

    if(zoom_value < MAX_ZOOM) {
      container.attr("zoom", zoom_value + ZOOM_OFFSET);
    } else {
      action_button.addClass("disable");
    }
  }

  else if (action_button.hasClass("zoom-out")) {

    zoom_in_button.removeClass("disable");
    if(zoom_value > MIN_ZOOM) {
      container.attr("zoom", zoom_value - ZOOM_OFFSET);
    } else {
      action_button.addClass("disable");
    }
  }

  container.html(container.attr("zoom"));

});

    0

    <button class="zoom-btn zoom-in">+</button>
    <button class="zoom-btn zoom-out">-</button>


texts: Calculating energy from mass and light speed

texts:
I'm learning Java JDK 1.8 since one day and I'm using Java's methods to the first time. I have never used Java before because I'm a Python/Django developer.

I created a method which let to get energy in function of two parameters: mass and light speed. I would like to know if my method is well-written or if I made some mistakes about method, call, etc.

import java.util.Scanner;

public class methodes {

    public static double Energie(double m, double c)
      {
       return (double) (m*Math.pow(c, 2));
      }

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        int C = 300000 ;
        double m ;

        System.out.println("Valeur de la masse en kg : ");
        m = sc.nextDouble();

        double E = Energie(m,C);
        System.out.println("Pour " + m + " kg donné, l'énergie équivaut à " + E + " Joules");

    }

}


texts:
I wrote a program that receives 2 strings (Input and Search) in the Search string. The sign '+' indicates that if the substring before the '+' exists in the Input string. (The search string cannot start with '+' and there cannot be a '+' followed by another '+').

Can you review it for best coding practices and efficiency?

boolean notgood = false;
boolean break1 = false;
boolean break2 = false;
int counter = 0;

if (search.charAt(0)=='+'||search.charAt(0)=='*') {

    System.out.println("Invalid search striNG.");
    continue;
}
//////////////////////////////////////////////
for (i=0; i<search.length() && notgood==false; i++) {

    if (search.charAt(i)!='*' && search.charAt(i)!='+') {
        counter++;
    }
    if (counter == search.length()) {
        System.out.println("Invalid SEARCH string.");
        notgood=true;
        break;
    }

    if ((search.charAt(i)=='*')||(search.charAt(i)=='+')) {

        if (i!=search.length()-1) {

            if ((search.charAt(i+1)=='*')||(search.charAt(i+1)=='+')) {

                System.out.println("INvalid search string.");
                notgood=true;
                break1=true;
            }
        }
    }
}
////////////////////////////////////////////
for (i=0; i<search.length() && !break1; i++) {

    int c=0;

    if (search.charAt(i)=='+') {

        String word = search.substring(0,i);

        for (int j=0; j<input.length() && !break2; j++) {

            if ((input.charAt(j) == word.charAt(c)) && c<word.length()) {
                c++;
            }
            if (c>=word.length()) {

                System.out.println("Search string matches input string.");
                break1=true;
                break2=true;

            }
        }
        if (c<word.length()) {
            System.out.println("Search string doesn't match input string.");
        }
    }

For example, for Input = 'abcd' and Search = 'ab+cd+', the result should be the strings match.


texts: Traversing a multidimensional structure and applying strip() to all strings

texts:
I'm trying to apply string.strip() to all the leafs that are strings in a multidimensional collection, but my Python is a bit rusty (to say the least). The following is the best I've come up with, but I suspect there's a much better way to do it.

def strip_spaces( item ):
    if hasattr( item, "__iter__" ):
        if isinstance( item, list ):
            return [strip_spaces( value ) for value in item]
        elif isinstance( item, dict ):
            return dict([(value,strip_spaces(value)) for value in item])
        elif isinstance( item, tuple ):
            return tuple([ strip_spaces( value ) for value in item ])
    elif isinstance( item, str ) or isinstance( item, unicode ):
        item = item.strip()
    return item


texts:
What is the best way to considerably decrease the size of the following code without sacrificing functionality, and to make it more readable, and well, make it look professional?

class Compiler
{
    public string Compile(TextReader src)
    {
        string rtn = SourceTemplate.Top;

        var preprocessor = new PreProcessor();

        Parser[] ParserRounds = {
                                    new PredefinedConstantParser(),
                                    new VariableDeclarationParser(),
                                    new ConditionalExpressionParser(),
                                    new FunctionCallParser()//,
                                  //new FunctionParser
                                };

        foreach (var l in preprocessor.Process(src))
        {
            var line = l;

            foreach (var parser in ParserRounds)
            {
                line = parser.Parse(line);
            }

            rtn += "\t\t\t" + line + "\n";
        }

        return rtn + SourceTemplate.Bottom;
    }

    public static void Start(string[] args)
    {
        TextReader src = File.OpenText(args[0]);

        var com = new Compiler();
        var source = com.Compile(src);

        string target = args[0].TrimEnd(".hack".ToCharArray());
        target += ".cs";
    }

    public void SaveToFile(string source, string target)
    {
        TextWriter wsrc = File.CreateText(target);
        wsrc.WriteLine(source);
        wsrc.Close();
    }
}

In my personal opinion, the above code looks like a mess at this stage. Also, please suggest good and expressive variable names instead of rtn , src etc.  Should I also make this class generic?


texts: Generating a word bigram co-occurrence matrix

texts:
I have written a method which is designed to calculate the word co-occurrence matrix in a corpus, such that element(i,j) is the number of times that word i follows word j in the corpus.

Here is my code with a small example:

import numpy as np
import nltk
from nltk import bigrams

def co_occurrence_matrix(corpus):
    vocab = set(corpus)
    vocab = list(vocab)

    # Key:Value = Word:Index
    vocab_to_index = { word:i for i, word in enumerate(vocab) }

    # Create bigrams from all words in corpus
    bi_grams = list(bigrams(corpus))

    # Frequency distribution of bigrams ((word1, word2), num_occurrences)
    bigram_freq = nltk.FreqDist(bi_grams).most_common(len(bi_grams))

    # Initialise co-occurrence matrix
    # co_occurrence_matrix[current][previous]
    co_occurrence_matrix = np.zeros((len(vocab), len(vocab)))

    # Loop through the bigrams in the frequency distribution, noting the
    # current and previous word, and the number of occurrences of the bigram.
    # Get the vocab index of the current and previous words.
    # Put the number of occurrences into the appropriate element of the array.
    for bigram in bigram_freq:
        current = bigram[0][1]
        previous = bigram[0][0]
        count = bigram[1]
        pos_current = vocab_to_index[current]
        pos_previous = vocab_to_index[previous]
        co_occurrence_matrix[pos_current][pos_previous] = count

    co_occurrence_matrix = np.matrix(co_occurrence_matrix)

    return co_occurrence_matrix

test_sent = ['hello', 'i', 'am', 'hello', 'i', 'dont', 'want', 'to', 'i', 'dont']
m = co_occurrence_matrix(test_sent)

Output:

[[0. 2. 0. 0. 0. 0.]
 [0. 0. 0. 1. 0. 2.]
 [0. 1. 0. 0. 0. 0.]
 [0. 0. 0. 0. 1. 0.]
 [1. 0. 0. 0. 0. 0.]
 [0. 0. 1. 0. 0. 0.]]

Whilst the example shown works fine, when I scale this up to a much larger corpus, I get the following Killed:9 error. I assume this is because the matrix is very large.

I am looking to make this method more efficient so that I can use it for large corpuses! (A few million words.)


texts: Why is this program for extracting IDs from a file so slow?

texts:
This is roughly what my data file looks like:

# Monid      U        B       V       R       I      u       g        r       i       J      Jerr     H      Herr      K      Kerr   IRAC1    I1err  IRAC2    I2err  IRAC3    I3err  IRAC4    I4err  MIPS24  M24err  SpT    HaEW       mem comp
Mon-000001  99.999  99.999  21.427  99.999  18.844  99.999  99.999  99.999  99.999  16.144  99.999  15.809   0.137  16.249  99.999  15.274   0.033  15.286   0.038  99.999  99.999  99.999  99.999  99.999  99.999  null   55.000        1  N
Mon-000002  99.999  99.999  20.905  19.410  17.517  99.999  99.999  99.999  99.999  15.601   0.080  15.312   0.100  14.810   0.110  14.467   0.013  14.328   0.019  14.276   0.103  99.999   0.048  99.999  99.999  null  -99.999        2  N

...and it's a total of 31mb in size. Here's my python script that pulls the Mon-###### IDs
(found at the beginning of each of the lines).

import re

def pullIDs(file_input):
    '''Pulls Mon-IDs from input file.'''

    arrayID = []
    with open(file_input,'rU') as user_file:
        for line in user_file:
            arrayID.append(re.findall('Mon\-\d{6}',line))
    return arrayID

print pullIDs(raw_input("Enter your first file: "))

The script works but for this particular file it ran for well into 5 minutes and I eventually just killed the process due to impatience. Is this just something I'll have to deal with in python? i.e. Should this be written with a compiled language considering the size of my data file?

Further info:
  This script is being run within Emacs. This, by the checked answer, explains why it was running so slow.


texts: Parallel Calls to External WCF Service - ASP.NET Web Api

texts:
I have come across a situation where I feel running some code in parallel will greatly improve performance, but I am concerned about the implementation and am looking for some confirmation. Take the following controller resources
[HttpGet]
[Route("{id}")]
public IHttpActionResult Get(int id)
{
     return Ok(_context.Get(id));
}

[HttpGet]
[Route("async/{id}")]
public async Task<IHttpActionResult> Get(int id)
{
     return Ok(await _context.GetAsync(id));
}

The contents of Get(...) function are fairly straight forward. A WCF call is made using the passed id to retrieve document a object. That document object contains a list of associated material numbers for which I need to make a separate WCF call for each to gather additional data
public DocumentModel Get(int id)
{
     //Call to WCF service
     DocumentModel model = _documents.Get(id);

     //For each material, make a call to WCF service
     //Potential for bottle neck due to possibility of large number of associated materials
     foreach (Material material in model.Materials)
         model.MaterialModels.Add(_materials.Get(material.Number));

     return model;
}

It is worth noting that I am using a library developed and maintained by a colleague to call WCF services that are hosted on the same VM, so lets just say that I don't have access to modify this library for sake of the question. Retrieving a material looks like the following
public MaterialModel Get(string number)
{
     using(var client = new MaterialClient(out WcfResult result))
    {
         client.Get(number, out Material material, out Result result);
         return new MaterialModel(material);
    }
}

Everything works as expected, but as previously noted its possible for a significant number of materials to be returned (~20-60). Typically, I wouldn't encounter a problem like this since I would be utilizing HATEOAS and supplying the resource for each material in the DocumentModel object, however; this is an API for internal business use and the business requires all the data be in the response so I am left with little choice. So I made a separate implementation that will retrieve that material data in parallel
public async Task<DocumentModel> GetAsync(int id)
{
     //Call to WCF service
     DocumentModel model = _documents.Get(id);
     IEnumerable<Task<MaterialModel>> tasks = model.Materials.Select(material =>
          _materials.GetAsync(material.Number));

     MaterialModel[] result = await Task.WhenAll(tasks);
     model.MaterialModels.AddRange(result);
     return model;
}

Here is where my concern is. There are no Async implementations in the library, so my initial thought was to just do the following
public Task<MaterialModel> GetAsync(string number)
{
     //This concerns me
     return Task.Run(() =>
     {
         using(var client = new MaterialClient(out WcfResult result))
         {
              client.Get(number, out Material material, out Result result);
              return new MaterialModel(material);
         }
     });
}

Both implementations work, but when I run them both side by side the one making calls in parallel is significantly faster and diagnostics shows the flow is what I expected as well

Is this an acceptable implementation or are there some pitfalls to this I may not be aware about?


texts: Calculate divisors using prime factorization

texts:
For learning purpouses I wrote a class that is supposed to find all divisors for a given integer. My class makes use of primes and prime factorization to speed things up a bit.
What can I improve in my class?

Are there any microoptimiztations that could speed up the process? Any bad practices that should be avoided? I am by no means an expert at math, so feel free to be very nit-picky. :)

DivisorFinder Class

public class DivisorFinder
{
    /// <summary>
    /// The number that is searched for divisors
    /// </summary>
    private int _number;

    /// <summary>
    /// Search new divisors for a given integer
    /// </summary>
    /// <param name="number">Integer that is searched for divisors</param>
    public DivisorFinder(int number)
    {
        _number = number;
    }

    /// <summary>
    /// Find prime numbers up to a given maximum
    /// </summary>
    /// <param name="upperLimit">The upper limit</param>
    /// <returns>All prime numbers between 2 and upperLimit</returns>
    private IEnumerable<int> FindPrimes(int upperLimit)
    {
        var composite = new BitArray(upperLimit);
        var sqrt = (int) Math.Sqrt(upperLimit);

        for (int p = 2; p < sqrt; ++p)
        {
            if (composite[p])
                continue;

            yield return p;

            for (int i = p * p; i < upperLimit; i += p)
                composite[i] = true;
        }

        for (int p = sqrt; p < upperLimit; ++p)
            if (!composite[p])
                yield return p;
    }

    /// <summary>
    /// Search prime factors in a given IEnumerable of prime numbers
    /// </summary>
    /// <param name="primesList">The IEnumerable of previously calculated prime numbers</param>
    /// <returns>IEnumerable of prime factors</returns>
    private IEnumerable<(int, int)> FindPrimeFactors(IEnumerable<int> primesList)
    {
        foreach (var prime in primesList)
        {
            if (prime * prime > _number)
                break;
            int count = 0;
            while (_number % prime == 0)
            {
                _number = _number / prime;
                count++;
            }

            if (count > 0)
                yield return ((prime, count));
        }

        if (_number > 1)
            yield return (_number, 1);
    }

    /// <summary>
    /// Find all divisors of the target number
    /// </summary>
    /// <returns>IEnumerable of integers that divide the target without reminder</returns>
    public IEnumerable<int> FindDivisors()
    {
        var primes = FindPrimes((int) (Math.Sqrt(_number) + 1));
        var factors = FindPrimeFactors(primes);
        var divisors = new HashSet<int> {1};

        foreach (var factor in factors)
        {
            var set = new HashSet<int>();
            for (int i = 0; i < factor.Item2 + 1; i++)
            {
                foreach (int x in divisors)
                {
                    set.Add((int) Math.Pow(x * factor.Item1, i));
                }
            }

            divisors.UnionWith(set);
        }

        return divisors;
    }
}

Usage

var number = 2147483644;
var divisorFinder = new DivisorFinder(number);
var divisors = divisorFinder.FindDivisors();
Console.WriteLine($"Divisors: [{string.Join(", ", divisors)}]");

Performance for this example: ~6 milliseconds on a i5-6600K @ 3.50GHz

Credits:

The class was inspired by the python example from Bruno Astrolino.

Furthermore the prime sieve function was adapted from Dennis_E.


texts:
I have written a simple code for Runge-Kutta fourth order integration to solve a system of ordinary differential equations and parallelized it using OpenMP. I don't know if it is the best we can do for maximum performance of the code with little effort.

I need all values of to be returned, so I kept values in all steps.
I also create threads in each time step and paralleled in position, i.e.
pragma opm parallel is inside the loop over time.

Here is my try: (link to gitlab repository)

//RHS for a system of equations
void xprsys(const int n,const vector<double>& x, vector<double>& f)
{
    /*
     * n : number of equations
     * x : value in each time step
     * f : RHS of equtions dx/dt = f
     */
    double sum1=0;
    #pragma omp parallel for reduction(+:sum1)
    for (int i=0; i<n; i++){
        sum1 = 0;
        for(int j=0; j<n; j++)
            sum1 += sin(x[j]-x[i]);
        f[i] = M_PI + 2.0 * sum1;
    }
}

void SolveRK4(const int n, double h,vector<double> x,
     vector<vector<double>>& x_vec,
          int nstep, vector<double>& times)
{
    /*
     * times : vector contains the time 0 : t_final step dt
     * x_vec : [nstep by N] 2 Dimensional vector
     * dim1  : defined as typedef vector<double> dim1
     */

    times[0] = 0.0;
    dim1 y(n);
    dim1 f1(n),f2(n),f3(n),f4(n);
    double half_h = 0.5 * h;
    double h_sixth = h/6.0;
    // x_vec[nstepxN]

    for (int i=0; i<n; i++)
        x_vec[0][i] = x[i];

    for (int k=1; k<nstep; k++){
        times[k] = k*h;
        xprsys(n,x,f1);

        #pragma omp parallel for
        for(int i=0; i<n; i++)
            y[i] = x[i] + half_h * f1[i];

        #pragma omp master
        xprsys(n,y,f2);
        #pragma omp barrier

        #pragma omp for
        for(int i=0; i<n; i++)
            y[i] = x[i] + half_h * f2[i];

        #pragma omp master
        xprsys(n,y,f3);
        #pragma omp barrier

        #pragma omp for
        for(int i=0; i<n; i++)
            y[i] = x[i] + h * f3[i];

        #pragma omp master
        xprsys(n,y,f4);
        #pragma omp barrier

        #pragma omp for
        for(int j=0; j<n; j++) {
            x[j] = x[j] + h_sixth * (f1[j] + f4[j] + 2.0 * (f2[j] + f3[j]));
            x_vec[k][j] = x[j];
        }
    }
}


texts:
As a first step to attempting the Weekend Challenger Reboot, I decided to first implement a regular 'tic-tac-toe' game and then expand it later to be 'ultimate tic-tac-toe'.

Below is the code for the tic-tac-toe board. It's fully functional and unit tested, but I'm not too happy about the getWinner() method. This method's purpose is to check to see if there is any winner in the game, and to return the identity of said winner if they exist.

The reasons I don't like it are:

The method is very long, which immediately sets off warning flags in my mind.
It makes use of a 'flag' type variable that tracks if we've found a winner yet. I don't like flag variables because they're really something that I got in the habit of doing back when I did procedural programming, and therefore probably shouldn't exist in an object-oriented design.
There's an awful lot of continue and break statements which seem to indicate poorly-designed loops.
I'm pretty sure that if there is no winner, this method is O(n2).

This is the code for the getWinner() method:

public class Board {
    private final Player[][] fields;
    ...
    public Player getWinner() {
        Player winner = null;
        boolean isWon = false;

        // check columns (same x)
        for (int x = 0; x < fields.length; x++) {
            Player value = fields[x][0];

            if (value == null) {
                continue;
            }
            for (int y = 1; y < fields[x].length; y++) {
                Player current = fields[x][y];
                if (current == null || !current.equals(value)) {
                    break;
                }
                if (y == fields[x].length -1) {
                    isWon = true;
                    winner = value;
                }
            }
            if(isWon) {
                break;
            }
        }

        if (! isWon) {
            // check rows (same y)

            for (int y = 0; y < fields[0].length; y++) {
                Player value = fields[0][y];
                if (value == null) {
                    continue;
                }
                for (int x = 1; x < fields.length; x++) {
                    Player current = fields[x][y];
                    if (current == null || !current.equals(value)) {
                        break;
                    }
                    if (x == fields.length -1) {
                        isWon = true;
                        winner = value;
                    }
                }
                if(isWon) {
                    break;
                }
            }

        }
        if (! isWon) {
            // check diagonal (bottom left to top right

            Player value = fields[0][0];
            if (value != null) {
                for (int i = 1; i < fields.length; i++) {
                    if (fields[i][i] != value) {
                        break;
                    }
                    if (i == fields.length -1) {
                        isWon = true;
                        winner = value;
                    }
                }
            }
        }

        if (! isWon) {
            // check anti-diagonal (top left to bottom right)
            int length = fields.length;
            Player value = fields[0][length-1];
            if (value != null) {
                for (int i = 1; i < length; i++) {
                    if (fields[i][length-i-1] != value) {
                        break;
                    }
                    if (i == length -1) {
                        isWon = true;
                        winner = value;
                    }
                }
            }
        }
        return winner;
    }
    ...
}

The rest of the code is mostly irrelevant. Something important to be aware of is that the board will always be a perfect square -- eg. 3x3 or 4x4 or 5x5. The Player is a simple enum:

public enum Player {
    X("X"),
    O("O");

    private String str;
    private Player(String str) {
        this.str = str;
    }

    @Override public String toString() {
        return str;
    }
}


texts: Searching for three positive integers as a solution to an equation

texts:
I recently ran into a question on M.SE asking,

  For positive integers x, y, z find a solution s.t. \$ \frac{x}{y+z} + \frac{y}{x+z} + \frac{z}{x+y} = 4 \$

so rather than think, I made a quick brute force c++ program to check for solutions:

unsigned lim = 251;
for(double x=1; x<lim; x++) {
    for(double y=1; y<lim; y++) {
        for(double z=1; z<lim; z++) {
            printf("x=%.0f, y=%.0f, z=%.0f\n",x,y,z);
            if( std::abs((x/(y+z) + y/(x+z) + z/(y+x)) - 4) <= 1E-15) {
                printf("solution: x=%.0f, y=%.0f, z=%.0f\n",x,y,z);
            }
        }
    }
}

All of this being within main, of course. This is obviously slow so I was looking for optimizations. A couple of my thoughts were to remove the std::abs call because the inside expression must be positive, perhaps I could simply check == 4 rather than account for precision. I couldn't figure out a way to drop a for loop, because you can't isolate a variable. Otherwise I'm not sure what to do.

Questions:

How can this code be sped up? My goal is lim=1E3 in under a minute. As of now it takes 31.0643 s for lim=251.
Can the for-loops be reduced? As of now formatting is not really an issue for me, but can this be simplified down to a single expression and/or loop? Or maybe look a little cleaner, without sacrificing optimization?

Update: After some research I'm now aware that the smallest known solution to this has numbers with 81 digits. I'm not concerned with this, just the above questions.


texts:
Can anybody find anything to pick apart in this script?

#  Copyright (c) 2019. Legorooj

import sys
import os

docstring = '''
add_alias [alias] [command]'''
if len(sys.argv) <= 1:
    print(docstring)
else:
    alias, cmd = sys.argv[1], sys.argv[2]
    print('Adding alias...')
    os.system(f'echo "alias {alias}={cmd}" >> ~/.bashrc && source ~/.bashrc')
    print('Alias added')

If ran like:

add_alias bob "echo bob", it adds an alias as if you ran

echo "alias bob="echo bob"" >> ~/.bashrc && source ~/.bashrc


texts: Sorted insert on a doubly linked list (HackerRank)

texts:
I've decided to do a simple linked list question to brush up my Java & CS.

This is the solution for

  Given a reference to the head of a doubly-linked list and an integer,
  \$data\$ , create a new DoublyLinkedListNode object having data value
  \$data\$
  and insert it into a sorted linked list while maintaining the sort.
  Full question

   /*
     * For your reference:
     *
     * DoublyLinkedListNode {
     *     int data;
     *     DoublyLinkedListNode next;
     *     DoublyLinkedListNode prev;
     * }
     *
     */
    static DoublyLinkedListNode sortedInsert(DoublyLinkedListNode head, int data) {
        DoublyLinkedListNode nodeToInsert = new DoublyLinkedListNode(data);
        if (head == null) return nodeToInsert;
        DoublyLinkedListNode current = head;
        while (current != null) {
            if (data < current.data && current.prev == null) {
                current.prev = nodeToInsert;
                nodeToInsert.next = current;
                return nodeToInsert;
            }
            if (data >= current.data && current.next == null) {
                current.next = nodeToInsert;
                nodeToInsert.prev = current;
                break;
            }
            if (data >= current.data && data <= current.next.data) {
                DoublyLinkedListNode temp = current.next;
                current.next = nodeToInsert;
                nodeToInsert.prev = current;
                temp.prev = nodeToInsert;
                nodeToInsert.next = temp;
                break;
            }
            current = current.next;
        }
        return head;
    }

This passes all test cases.


texts: Calculating distance with Euclidean, Manhattan, and Chebyshev in C#

texts:
I am by no means proficient at being able to take mathematical concepts and converting them to code. I was wondering if you guys could look at it and make suggestions on how I could fix it or if my thinking is correct on these. I used a combination of the wikipedia pages for each of these as well as http://theory.stanford.edu/~amitp/GameProgramming/Heuristics.html to come up with my solutions.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Algorithms
{
    public static class Heuristics
    {
        // implementation for integer based Manhattan Distance
        public static int ManhattanDistance(int x1, int x2, int y1, int y2)
        {
            return Math.Abs(x1 - x2) + Math.Abs(y1 - y2);
        }

        // implementation for floating-point  Manhattan Distance
        public static float ManhattanDistance(float x1, float x2, float y1, float y2)
        {
            return Math.Abs(x1 - x2) + Math.Abs(y1 - y2);
        }

        // implementation for integer based Euclidean Distance
        public static int EuclideanDistance(int x1, int x2, int y1, int y2)
        {
            int square = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2);
            return square;
        }

        // implementation for floating-point EuclideanDistance
        public static float EuclideanDistance(float x1, float x2, float y1, float y2)
        {
            float square = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2);
            return square;
        }

        // implementation for integer based Chebyshev Distance
        public static int ChebyshevDistance(int dx, int dy)
        {
            // not quite sure if the math is correct here
            return 1 * (dx + dy) + (1 - 2 * 1) * (dx - dy);
        }

        // implementation for floating-point Chebyshev Distance
        public static float ChebyshevDistance(float dx, float dy)
        {
            // not quite sure if the math is correct here
            return 1 * (dx + dy) + (1 - 2 * 1) * (dx - dy);
        }
    }
}


texts: Getting JSON data from an HTTP response using conditional binding

texts:
I am new to Swift and I am trying to use the optional binding feature in as efficient way as possible but I am a bit confused on how to use it (if I can) in this scenario:

var jsonData:AnyObject? = nil

jsonData = try? NSJSONSerialization.JSONObjectWithData(data!, options: [])
if(jsonData == nil) {
    print("Could not parse data")
}

if(httpresponse.statusCode == 200 || httpresponse.statusCode == 201) {
    if (jsonData as? ReturnType) != nil {
        return jsonData as? ReturnType
    } else { print("Request Successful") }
} else { // Not HTTP 200 or 201
    if let dic = jsonData as? NSDictionary {
        if dic["Message"] != nil && (dic["Message"] as? String) != nil {
            let message = dic["Message"]! as! String
            print("Server returned status code '\(httpresponse.statusCode)': '\(message.trim())'")
        }
    } else {
        let message = NSHTTPURLResponse.localizedStringForStatusCode(httpresponse.statusCode)
        print("Server returned status code '\(httpresponse.statusCode)': \"\(message)\"")
    }
}

The key statements here are:

jsonData = try? NSJSONSerialization.JSONObjectWithData(data!, options: [])
if(jsonData == nil) {
    print("Could not parse data")
}

There are potentially several places where all I need to do is a print or a user message (basically run some conditional code) after an important assign/unwrap without any major redirections of the rest of the code.

I was wondering if there was a smarter way of doing what I want to do without having to follow up each of those assignments with its own if statement.

I was under the impression that if let and guard did that very thing by merging conditional statements like if and else with the assignment, thus compacting the code, but they also seem to add some restrictive scope limitations like scope of the constant in the if let and having to 'return' or 'continue' in the guard scope.

What do you think?


texts: Creating objects and putting them into std::list

texts:
I am writing small roguelike game where I spawn some items and put them into the std::list. Is this the right way to do it?

The Item class is as followed (I know it has public id property):

class Item {

public:
   Item();
   ~Item();

   unsigned int id;
};

Somewhere in the code I also defined:

list<Item*> listOfItems;
list<Item*>::iterator it;

Now I am using this code to create an item:

Item *p = new Item();
p->id = itemCrowbar;
listOfItems.push_back(p);

At the end of the program I use small loop to delete all items:

for (it = listOfItems.begin(); it!=listOfItems.end(); it++) {
    delete *it;
}

Is this approach for creating objects, putting them in std::list and
at the end deleting them correct, or am I missing something important here?


texts:
I made a simple Question "system":

Answer

Stores an answer (string) and a boolean value to check if the answer is correct or not.

public class Answer {

    private String answer;
    private boolean isCorrect;

    public Answer(String answer, boolean isCorrect) {
        this.answer = answer;
        this.isCorrect = isCorrect;
    }

    public String getAnswer() {
        return answer;
    }

    public boolean isCorrect() {
        return isCorrect;
    }

}

Question

I don't know if I should use "Answer[] answers" or "Answers... answers" in the Question constructor.

public class Question {

    private String question;
    private Answer[] answers;

    public Question(String question, Answer... answers) {
        this.question = question;
        this.answers = answers;
    }

    public String getQuestion() {
        return question;
    }

    public Answer[] getAnswers() {
        return answers;
    }

    public boolean isCorrect(String answer) {
        for(Answer tempAnswer : answers)
            if(tempAnswer.getAnswer().equals(answer) && tempAnswer.isCorrect())
                return true;

        return false;
    }

    public boolean isCorrectIgnoreCase(String answer) {
        for(Answer tempAnswer : answers)
            if(tempAnswer.getAnswer().equalsIgnoreCase(answer) && tempAnswer.isCorrect())
                return true;

        return false;
    }
}

SAMPLE

private static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        Question questionA = new Question("Do chickens fly?",
                                          new Answer("Yes", true),
                                          new Answer("No", false));
        System.out.println(questionA.getQuestion());

        while(true) {
            if(questionA.isCorrectIgnoreCase(scanner.nextLine()))
                break;
            else
                System.out.println("No, that is incorrect. Please try again.");
        }

        System.out.println("Correct.");
    }


texts: Better way to write generic method to convert List> to T[][]

texts:
I was working through getting myself past the creation of a generic method, that converts a List<T> or List<List<T>>, to T[] or T[][] respectively. Well, let's just consider a maximum dimension of 2 for now.

List<T> to T[] is quite straight-forward:

public static <T> T[] listToArray(List<T> list, Class<T> clazz) {

    /**** Null Checks removed for brevity ****/

    T[] arr = (T[]) Array.newInstance(clazz, list.size());

    for (int i = 0; i < list.size(); ++i) {
        arr[i] = list.get(i);
    }
    return arr;
}

Now I can call this method as:

List<String> list = new ArrayList<>(Arrays.asList("rohit", "jain"));
String[] arr = listToArray(list, String.class);

List<List<T>> to T[][] is what gives problems:

Now, here's the problem. Consider the code:

public static <T> T[][] multiListToArray(List<List<T>> listOfList, Class<T> clazz) {

    // Here I don't know what size to give for 2nd dimension
 // T[][] arr = (T[][]) Array.newInstance(clazz, listOfList.size(), ?);

    // So, I tried this. But this of course is not type safe
 // T[][] arr = (T[][]) new Object[listOfList.size()][];

    /* Only alternative I had was to iterate over the listOfList to get the
       maximum out of all the column sizes, which I can give as 2nd
       dimension later on.
    */
    int maxCol = 0;

    for (List<T> row: listOfList) {
        if (row.size() > maxCol) {
            maxCol = row.size();
        }
    }

    // Now I can pass `maxCol` as 2nd dimension
    T[][] arr = (T[][]) Array.newInstance(clazz, listOfList.size(), maxCol);

    for (int i = 0; i < listOfList.size(); ++i) {
        List<T> row = listOfList.get(i);
        arr[i] = listOfList.get(i).toArray((T[])Array.newInstance(clazz, row.size()));
    }

    return arr;
}

Now, this is what I want to avoid - double iteration of List<List<T>> to be able to create the array. Is there any possibility?


texts:
I need to get some scripts from the different social networking site and cache them.  I want the function to be asynchronous, and non-blocking.

I have settled with a script, but I am not really sure if it is not overly complicated to do the job.

I did replace a normal for loop, and this method is much faster. I do not know why, but it just is.

// Cached scritps
var cachedScriptPromises = {};

// Location of the scripts
var Scripts : {
    twitter    : '//platform.twitter.com/widgets.js',
    facebook   : 'http://static.ak.fbcdn.net/connect.php/js/FB.Share',
    googleplus : 'https://apis.google.com/js/plusone.js',
    linkedin   : 'http://platform.linkedin.com/in.js'
};

// When the button is clicked all the scripts
// are loaded. The conainers are already
// on the website. They will be filled
// as soon as the script is loaded.
jQuery('a.share-link').click(function(){
    for( var script in Scripts ){
        jQuery.cachedGetScript( Scripts[script] );
    }
});

// Function that get and caches the scripts
jQuery.cachedGetScript = function( script ) {
    if ( !cachedScriptPromises[ script ] ) {
        cachedScriptPromises[ script ] = jQuery.Deferred(function( defer ) {
            jQuery.getScript( script ).then( defer.resolve, defer.reject );
        }).promise();
    }
    return cachedScriptPromises[ script ];
};

Eventually this function can be expanded by adding some before and after actions. The thing is that the files are loaded so quickly that I have removed these features, but I am planning to do this as soon as the project becomes bigger.

Does anyone have any suggestions on making this better?  Maybe some adjustments to the code, or go a complete other way with this.


texts:
Here is a sample program I have written to convert numbers to words:

ONES = [None, 'one', 'two', 'three', 'four',
        'five', 'six', 'seven', 'eight', 'nine']

# Empty string for zero will be replaced in main function

TEENS = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen',
         'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']

TENS_PREFIXES = ['_', '_', 'twen', 'thir', 'for',
                 'fif', 'six', 'seven', 'eigh', 'nine']

# Tens places words without "-ty". ex. twenty > twen, thirty > thir

POWERS_OF_1000 = ['', 'thousand', 'million', 'billion', 'trillion',
                  'quadrillion', 'quintillion', 'sextillion',
                  'septillion', 'octillion']

def to_base_1000(number):
    # To split a number into chunks of three digits
    # ie. (fifty three thousand   two hundred one)

    digits = []
    while number:
        number, digit = divmod(number, 1000)
        digits.append(digit)

    return digits

def to_hundreds_tens_ones(number):

    assert(0 <= number < 1000)

    return number // 100, number // 10 % 10, number % 10

def two_digit_to_words(tens, ones):

    if tens == 0:
        return ONES[ones]

    elif tens == 1:
        return TEENS[ones]

    elif ones == 0:
        return '{}ty'.format(TENS_PREFIXES[tens])
        # This won't index to the underscores (positions 0 and 1)
        # because of the first two ifs

    else:
        return '{}ty {}'.format(TENS_PREFIXES[tens], ONES[ones])

def three_digit_to_words(hundreds, tens, ones):

    last_two_digits = two_digit_to_words(tens, ones)
    if hundreds == 0:
        return last_two_digits

    else:
        if last_two_digits is None:
            return '{} hundred'.format(ONES[hundreds])

        else:
            return '{} hundred {}'.format(ONES[hundreds], last_two_digits)

def chunk_to_words(chunk, position):

    multiplier = POWERS_OF_1000[position]
    # Thousand, million, etc.

    if multiplier:
        multiplier = ' ' + multiplier

    # Add space if it exists so that it's not "onemillion" "twothousand" etc.

    hundreds, tens, ones = to_hundreds_tens_ones(chunk)

    return three_digit_to_words(hundreds, tens, ones) + multiplier

def number_to_words(number):

    if number == 0:
        return 'zero'

    chunks = to_base_1000(number)

    chunk_words = []

    for position, chunk in enumerate(chunks):
        chunk_words.append(chunk_to_words(chunk, position))

    return ' '.join(chunk_words[::-1])

    # Reverse because to_base_1000 returns chunks from smallest to largest

I would like some advice on improving my programming style and my commenting.