texts:
I've been designing a game server, where a player has inventory, bank, and other features with items.

There are some definitions of what item can be in my game:

Item is either stackable or not stackable.
If item is stackable, item's amount can be up to 100 per stack.

So since each item can have an amount if it's stackable, my regular idea was having two arrays, int[] itemIds and int[] amount, where itemIds holds the IDs of the items, and amount holds the amount for item in that index.

I must keep the indexes the same, because when the client selects an item, it sends over the slot id he clicked on.

But then I thought, I could just do an Item object, with the tools in that class for that item, and have a private property isStackable and amount.

But then my mate said the following thing:

  If you want to change some value of an Item object, you'll need to
  call a new construct and then get the old value then add the new value
  and then pass it to the construct. with primitives you can do that
  instant, which gives also performance positives

But then I thought of an idea, have a class named ItemStorage which will contain two arrays, items and amount like I described above:

public class ItemStorage {

    private int[] items;
    private int[] amount;

    public void setItems(int[] a, int[] b) {
        this.items = a;
        this.amount = b;
    }

    public int[] getItems() {
        return this.items;
    }

    public int[] getAmount() {
        return this.amount;
    }

}

I have a class called Inventory, it's my domain object for handling the inventory, it extends the interface Storage<ItemStorage>.

public interface Storage<T> {
    public T getStorage();
}

Now, since it implements it, the class must have the method getStorage() which will return ItemStorage, so to modify items, you do inventory.getStorage().getItems()[0] = 50;

But I am not sure about it, I am sure that List<Item> or Item[] will be much friendly, but I am not really sure why my mate dislikes it.

What do you think about my idea, and his opinion?  Do you have another idea I can use for this?

How the items are handled in the game

The game contains over 25,000 items, each item is unique. The game uses each item as an id to represent it's uniqueness. The first item out of that item list, will have an id of 1.

Lets look at item 1445, It's a sword.

When the client wants to wear the item, he has to click on it in his inventory. This click will send a packet to the server, with the slot id he clicked in the inventory.

There's an example, similar to my inventory:

Let's base on that picture.

You see 16 slots in that picture, starting from 0 to 15. Player clicks on slot 4, and the client will pass the slot 4 to the server. The server will check through the inventory, what item is sitting on slot 4 in the array, it will see the amulet with id 555 for example (like in the picture).

Therefore I need slots to be supported in my design.


texts: PermCheck Codility with time complexity of O(N)

texts:
I have this solution for Codility's PermCheck problem.  In summary, the task is to check whether array A contains each number in \$1 \ldots N\$ exactly once.

I got 100% for it but I got a time complexity of \$O(N * log(N))\$ or \$O(N)\$. How could I make this code \$O(N)\$? Could you also give a brief description of what makes code \$O(N)\$?

Array.Sort(A);
if(A[0] == 1 && A.Length == 1) return 1;
if(A[0] != 1) return 0;

int n = 0;
for(int i = 0; i < A.Length; i++)
{
    if(i < A.Length - 1)
    {
        if(A[i+1] == A[i] + 1)
        {
            n += 1;
        }
        else
        {
            return 0;
        }
    }
}
return 1;


texts:
Here is the link to fiddle. This is my first app using Dojo. Any comments/feedback is highly appreciated.

dojoConfig = {parseOnLoad: true};

resetStopwatch();

require(["dijit/form/ToggleButton", "dijit/form/Button", "dojo/dom", "dojo/dom-attr", "dojo/domReady!"], function(ToggleButton, Button, dom, domAttr){

    var timeUpdate;

    var toggleButton = new ToggleButton({
        showLabel: true,
        checked: false,
        label: "Start",
        onChange: function() {
            if (this.get('label') == "Start") {
                this.set('label', 'Stop');

                var milliseconds = seconds = minutes = hours = 0;

                timeUpdate = updateTime(domAttr, 0, 0, 0, 0);
            }
            else if (this.get('label') == "Resume") {
                this.set('label', 'Stop');
                // fetch current time in the stopwatch
                prev_milliseconds = parseInt(domAttr.get("milliseconds", "innerHTML"));
                prev_seconds      = parseInt(domAttr.get("seconds", "innerHTML"));
                prev_minutes      = parseInt(domAttr.get("minutes", "innerHTML"));
                prev_hours        = parseInt(domAttr.get("hours", "innerHTML"));
                timeUpdate = updateTime(domAttr, prev_hours, prev_minutes, prev_seconds, prev_milliseconds);

            }
            else if (this.get('label') == "Stop"){
                this.set('label', 'Resume');
                clearInterval(timeUpdate);
            }
        }
    }, "start_stop_resume");

    var resetButton = new Button({
        label: "Reset",
        onClick: function(){
            toggleButton.set('label', "Start");
            clearInterval(timeUpdate);
            resetStopwatch();
            resumeFlag = false;
        }
    }, "reset");
});

function updateTime(domAttr, prev_hours, prev_minutes, prev_seconds, prev_milliseconds){
    var startTime = new Date();
    timeUpdate = setInterval(function(){
        var timeElapsed = new Date().getTime() - startTime.getTime();

        // calculate hours
        hours = parseInt(timeElapsed/1000/60/60) + prev_hours;
        hours = prependZero(hours);
        domAttr.set("hours", "innerHTML", hours + " : ");

        // calculate minutes
        minutes = parseInt(timeElapsed/1000/60) + prev_minutes;
        if(minutes > 60)
            minutes = minutes % 60;
        minutes = prependZero(minutes);
        domAttr.set("minutes", "innerHTML", minutes + " : ");

        // calculate seconds
        seconds = parseInt(timeElapsed/1000) + prev_seconds;
        if(seconds > 60)
            seconds = seconds % 60;
        seconds = prependZero(seconds);
        domAttr.set("seconds", "innerHTML", seconds + " :: ");

        // calculate milliseconds
        milliseconds = timeElapsed + prev_milliseconds;
        milliseconds = prependZero(milliseconds);
        if(milliseconds > 1000)
            milliseconds = milliseconds % 1000;
        if(milliseconds < 10)
            milliseconds = "00" + milliseconds.toString();
        else if(milliseconds < 100)
            milliseconds = "0" + milliseconds.toString();
        domAttr.set("milliseconds", "innerHTML", milliseconds);

    },25);  // update time in stopwatch after every 25ms

    return timeUpdate;

}

function resetStopwatch(){
    require(["dojo/dom-attr"], function(domAttr){
        domAttr.set("hours",        "innerHTML", "00 : ");
        domAttr.set("minutes",      "innerHTML", "00 : ");
        domAttr.set("seconds",      "innerHTML", "00 :: ");
        domAttr.set("milliseconds", "innerHTML", "000");
    });
}

function prependZero(time){
    if(time < 10){
        time = "0" + time.toString();
        return time;
    }
    else
        return time;
}


texts: Function that strips trailing '0's from a float

texts:
I'm writing an embedded application in C, and at one point I need to convert a float into an ASCII representation of that float, so I can send the ASCII over a serial port. The protocol the serial port is listening over doesn't like trailing
'0's, so I'm writing a function that will remove all of the unnecessary '0's at the end of the ASCII string. Here is what my expected inputs and outputs look like:

#input           #output
300.000      --> 300.
300.01400    --> 300.014
300.1200     --> 300.12
300.12345678 --> 300.12345   #Only 5 decimal places of precision

Here is the function:

int float_to_str(float f, char *output, int buffer_size)
{
    int buf_len = snprintf(output, buffer_size, "%0.5f", f);

    //Strip trailing '0's from response
    bool seen_point = false;
    int real_len = 0;
    int index = 0;
    while (index < buf_len && index < buffer_size)
    {
        if (output[index] == '.')
            seen_point = true;
        if (output[index] != '0' || !seen_point)
            real_len = index + 1;
        index++;
    }

    return real_len;
}

The return value is the length of the string stuffed into output, which will never be more than buffer_size.

Is this well written and easy to understand? Am I overlooking edge-cases? How about the choice of algorithm, is there a simpler way to do this that I'm overlooking?


texts: Sum of multiples of 3 or 5 using functional programming

texts:
I wanted to practice functional programming (fp) without using any library. So I took the 1st problem from project euler:

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.

My solution in fp looks like this:
const isDivisibleBy = i => number => i % number === 0;
const selected = criteria => (...numbers) => i => numbers.filter(criteria(i))
    .length > 0;
const getSumOf = conditionFor => (sum, _, i) => conditionFor(i) ? sum + i :
    sum;
const solution = Array(1000)
    .fill()
    .reduce(getSumOf(selected(isDivisibleBy)(3, 5)), 0);

I have questions regarding efficiency and parametization:

Is there a more efficient way to write the function selected that is still functional? Because right now the filter functions runs through all elements of numbers - even if it finds an element that is not divisible for the given condition. Also .length > 0 makes it look like a hack. Is there a more declarative way?

I assume getSumOf can't be refactored any more?


texts: Securing PHP using a gateway that consults a whitelist

texts:
My site was recently infected and running malicious scripts. Once I discovered this, I cleared everything, the hosting company re-initialized the VPS and I setup my site anew. This is how I run my PHP scripts currently. I have two objectives:

To keep my scripts from being directly accessible from the web
To never run a script that I do not approve of

First I moved the PHP files out of the public folder except for one gateway file

scripts/
   prepend.php
   a.php
   b.php
   ...
public_html/
   gateway.php
   html, css, js, image files

I use .htaccess to redirect all requests for my PHP scripts to gateway.php.  This is the file that actually executes the PHP script requested.  To reach a.php, the browser requests /php/a...

RewriteEngine On
RewriteBase /
RewriteRule ^php/(.*)   gateway.php?file=$1.php   [END,QSA,NC]

In php.ini, I set auto_prepend_file to point to scripts/prepend.php. This file is run before all PHP scripts, so I can use it to do some configuration. In part, it has a list of allowed PHP scripts.

prepend.php

//the only scripts that will be allowed to run
Const SAFE_SCRIPTS = '"path/to/gateway.php","/path/to/a.php","/path/to/b.php"';
Const SCRIPTS_PATH = __DIR__;

//ensure that the requested script is allowed. The check here is to prevent
//a maliciously uploaded PHP file from executing.
$file = $_SERVER['SCRIPT_FILENAME'];//typically /path/to/gateway.php
if(strpos(SAFE_SCRIPTS,"\"$file\"")===false) die("$file is not allowed");

After prepend.php, gateway.php runs; it's in charge of making sure the requested PHP file is on the allowed list and for forwarding the request to the right file

//get the file requested. Comes from the htaccess rule
$file = SCRIPTS_PATH.'/'.$_GET['file'];

//if file is not in the allowed list, abort. The check here is to prevent
//gateway from loading any file it wasn't designed to load
if(strpos(SAFE_SCRIPTS,"\"$file\"")===false) die("$file is not allowed");

//load the file that actually handles the http request
require $file;

Looking for feedback on what's the weakest link and/or how to improve.


texts:
I have three methods that are really similar but do slightly different things. This doesn't feel very DRY to me, but I can't think of a way to reduce the duplication. Here are the methods, I think they're fairly self explanatory:

# Present a date as a string, optionally without a year
# Example output: "December 1, 2011"
def date_string(year=true)
  if date
    str = "%B %e"
    str += ", %Y" if year
    date.strftime(str).gsub('  ',' ')
  else
    ""
  end
end

# Present a time as a string, optionally with a meridian (am/pm)
# Example output: "1:30 PM"
def start_time_string(meridian=true)
  if start_time
    str = "%l:%M"
    str += " %p" if meridian
    start_time.strftime(str).lstrip
  else
    ""
  end
end

# Present a time as a string, optionally with a meridian (am/pm)
# Example Output: "2:00"
def end_time_string(meridian=true)
  if end_time
    str = "%l:%M"
    str += " %p" if meridian
    end_time.strftime(str).lstrip
  else
    ""
  end
end

Each method just presents a time as a string with certain options, and if the time object they're trying to present is nil, they return an empty string.

Any ideas how to DRY this up?


texts:
Fellow JS devs, I have come across a fairly simple question which has puzzled me. When the user submits a form I disable all inputs and submit button changes to a loading animation (fa-spinner from fontawesome). Once the form submit is complete then I restore the previous state, and enable everything back.

My question comes to making this code more concise and deliberate in a simple toggle function:

function toggleFormElements(toggle, elArr) {
  if (toggle == 'disable') {
    elArr.btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
    elArr.btn.setAttribute('disabled', 'disabled');

    // inputs
    elArr.fields.forEach((field, i) => {
      field.setAttribute('disabled', 'disabled');
    });
  } else if (toggle == 'enable') {
    elArr.btn.innerHTML = 'Submit';
    elArr.btn.removeAttribute('disabled');

    // inputs
    elArr.fields.forEach((field, i) => {
      field.removeAttribute('disabled');
    });
  }
}

Would it be possible to make this code more readable or simply shorter?


texts:
I have answered a Question in Stackoverflow link.

  a) Create a function called resize that can be used to increase the
  size of integer arrays dynamically. The function takes three
  parameters. The first parameter is the original array, the second
  parameter is the size of this array, and the third parameter is the
  size of the larger array to be created by this function. Make sure
  that you allocate memory from the heap inside this function. After
  allocating memory for the second array the function must copy the
  elements from the first array into the larger array. Finally, the
  function must return a pointer to the new array.

  b. In main, allocate an array on the heap that is just large enough to
  store the integers 5, 7, 3, and 1.

  c. Resize the array to store 10 integers by calling the resize
  function created in step a. Remove the old (smaller) array from the
  heap. Add the numbers 4, 2, and 8 to the end of the new array.

  d. Write a sort function that sorts any integer array in increasing
  order.

  e. Use the sort function to sort the array of numbers in c above.
  Display the sorted numbers.

Is there a Dangling pointer issue.

#include <array>
#include <iostream>

void swap(int *xp, int *yp)
{
    int temp = *xp;
    *xp = *yp;
    *yp = temp;
}

//Bubble Sort
bool sort(int arr[], int size)
{
    for( int i = 0; i< size -1; i++)
    {
        for( int j = 0; j < size - i -1; j++)
        {
            //descending order
            if(arr[j]<arr[j+1])
            {
                swap(&arr[j], &arr[j+1]);
            }
        }
    }
    return true;
}

void Print(int Array[], int nSize)
{
    for( int i = 0; i < nSize; i++)
    {
        std::cout<<" "<<Array[i];
    }
    std::cout<<"\n";
}

void Resize( int *&Array, const int& nSizeOld, const int& nSize )
{
    int * newArray = new int[nSize];

    //Copy Elements of the Array
    for(int i = 0; i< nSize; i++)
    {
        newArray[i] = Array[i];
    }

    delete[] Array;

    //Assign ptr of Prev to new Array
    Array =  newArray;
}

int _tmain(int argc, _TCHAR* argv[])
{
    const int kNewSize = 10, kSize = 5;
    int *pMyArray = new int[kSize];

    //Set Values
    for( int i = 0; i< kSize; ++i )
    {
        pMyArray[i] = i * 5;
    }

    Resize( pMyArray, kSize, kNewSize );

    //Set Values
    for( int i = kSize; i< kNewSize; ++i )
    {
        pMyArray[i] = i * 10;
    }

    Print(pMyArray, kNewSize);

    sort(pMyArray, kNewSize);

    Print(pMyArray, kNewSize);

    if( pMyArray!=NULL )
    {
        delete[] pMyArray;
    }

    return 0;
}


texts: "Block a website" script with vanilla JavaScript

texts:
I use this script to block access to a one or more websites with vanilla JavaScript. I find that it helps me avoid some addictive news websites that make me depressed. (Credit to Marat Tanalin for helping me with the event handling.)

The script is aimed to be an all vanilla JavaScript imperative small script for personal usage, hence it's not modular (there isn't a HTML/CSS/JS file distribution on purpose).

To use the script please change news_website_1.com to a given news website you hate.

My personal main problem with the script is that it doesn't block websites right away or almost right away such as happens with BlockSite Google Chrome extension:
For example, the script first loads a website, then about 5 seconds pass, then it gets blocked; for some reason, listening to the sooner DOMContentLoaded event sometimes works and sometimes doesn't and a reviewed version might show an improvement in that point.

How would you revise this script?

// ==UserScript==
// @name         New Userscript
// @match        *
// ==/UserScript==

window.addEventListener('load', ()=> {
  let sitesToBlock = [
      'news_website_1.com'
  ];
  let regexToMatchTLD = /\..+/;
  let href = window.location.href;
  for (let i = 0; i < sitesToBlock.length; i++) {
      if (href.includes(sitesToBlock[i])) {
          let domain = sitesToBlock[i].replace(regexToMatchTLD, '');
          document.body.innerHTML =`

                  The website ${domain} successfully blocked !

        `;
      }
  }
}, false);


texts:
The challenge is this: You have a function that is passed a board length (8x8 chess board), with the coordinates of the queen's location, along with an array of obstructions (opponents). Given the location of the queen, how many moves spaces are available for her to move, total?

This is the solution I came up with, based on the matrix spiral one I did recently, and I absolutely cringe when I look at it because the code looks so reusable but every time I look at lines to reuse, there's always something preventing it.

I like this approach because it's straightforward, but it is super wet and I'm wondering if anyone has any tips for taking the same strategy and making it cleaner.

const queensMenace = (boardLength, queen, obstructions) => {
  let counter = 0;
  const x = queen[0];
  const y = queen[1];

  function isObstacle(row, col) {
    for (let o of obstructions) {
      if (o[0] === row && o[1] === col) {
        console.log(o[0] + ',' + o[1]);
        return true;
      }
    }
  }

  function checkUp(row, col) {
    if (row >= 0) {
      console.log(row);
      if (isObstacle(row,col)) {
        return;
      } else {
        counter++;
        checkUp(row-1,col);
      }
    }
  }

  function checkDown(row, col) {
    if (row < boardLength-1) {
      if (isObstacle(row,col)) {
        return;
      } else {
        counter++;
        checkDown(row+1,col);
      }
    }
  }

  function checkLeft(row, col) {
    if (col >= 0) {
      if (isObstacle(row,col)) {
        return;
      } else {
        counter++;
        checkLeft(row,col-1);
      }
    }
  }

  function checkRight(row, col) {
    if (col < boardLength-1) {
      if (isObstacle(row,col)) {
        return;
      } else {
        counter++;
        checkRight(row,col+1);
      }
    }
  }

  function checkUpLeft(row, col) {
    if (row >= 0 && col >= 0) {
      if (isObstacle(row,col)) {
        return;
      } else {
        counter++;
        checkUpLeft(row-1,col-1);
      }
    }
  }

  function checkUpRight(row, col) {
    if (row >= 0 && col < boardLength-1) {
      if (isObstacle(row,col)) {
        return;
      } else {
        counter++;
        checkUpRight(row-1,col+1);
      }
    }
  }

  function checkDownRight(row, col) {
    if (row < boardLength-1 && col < boardLength-1) {
      if (isObstacle(row,col)) {
        return;
      } else {
        counter++;
        checkDownRight(row+1,col+1);
      }
    }
  }

  function checkDownLeft(row, col) {
    if (row < boardLength-1 && col >= 0) {
      if (isObstacle(row,col)) {
        return;
      } else {
        counter++;
        checkDownRight(row+1,col-1);
      }
    }
  }

  checkUp(x-1,y);
  checkUp(x+1,y);
  checkLeft(x,y-1);
  checkRight(x,y+1);
  checkUpLeft(x-1,y-1);
  checkUpRight(x-1,y+1);
  checkDownRight(x+1,y+1);
  checkDownLeft(x+1,y-1);

  return counter;
};

queensMenace(8, [4,5], [[2,3], [7,4]]);


texts:
This is a program that I made for encrypting text files, it uses a one time pad cipher to encrypt the files, but I do not know if there are any holes in my program that could be a vulnerability.

import os
q = 1
while q == 1:
    e = raw_input("file to encypt: ")
    #This will open a file for encryption
    o = open(e, "r")
    o1 = o.read()
    #This is the plain text to encrypt
    #'The quick brown fox jumps over the lazy dog'
    plain = o1
    #This will measure the length of the plain text
    f3 = len(plain)
    #generate random chacters as long as the text
    a1 = os.urandom(f3)
    #makes the random characters tuple format
    b = list(a1)
    b2 = list(plain)
    s = plain
    #gives the ascii value of the charters
    L = [ord(c) for c in s]
    s = a1
    a = [ord(c) for c in s]
    b = [ord(c) for c in plain]
    #adds the random digits and the plain text
    c = map(sum, zip(a,b))
    #uses Modular arithmetic if the sum is greater than 256
    x=c
    z = []
    for y in x:
        z.append(y-256 if y>=256 else y)
    z = [y-256 if y >= 256 else y for y in x]
    #converts the sum back to charter form
    cipher_text = ''.join(chr(i) for i in z)
    #makes a folder for the files
    base1 = os.path.basename(e)
    base2 = os.path.splitext(base1)[0]
    #makes a folder for the output
    p = "/Users/kyle/one_time_pad/"+base2
    print p
    if os.path.exists(p):
        print
    else:
        os.mkdir(p)

    key = a1
    #makes a file containg the key
    p = p + "/"
    f2 = p+"key.txt"
    #print f2
    if os.path.exists(f2):
        f1 = file(f2, "w")
        f1 = open(f2, "w")
        f1.write(key)
        f1.close()
    else:
        f1 = file(f2, "w")
        f1 = open(f2, "w")
        f1.write(key)
        f1.close()

    #makes a file containg the cipher text
    f3 = p+"cipher_text.txt"
    if os.path.exists(f3):
        f1 = file(f3, "w")
        f1 = open(f3, "w")
        f1.write(cipher_text)
        f1.close()
    else:
        f1 = file(f3, "w")
        f1 = open(f3, "w")
        f1.write(cipher_text)
        f1.close()

    f4 = p+"encrypt.py"
    encrypt1 = open("/Users/kyle/encrypt.py", "r")
    encrypt = encrypt1.read()
    if os.path.exists(f4):
        f1 = file(f4, "w")
        f1 = open(f4, "w")
        f1.write(encrypt)
        f1.close()
    else:
        f1 = file(f4, "w")
        f1 = open(f4, "w")
        f1.write(encrypt)
        f1.close()

    f5 = p+"decrypt.py"
    encrypt1 = open("/Users/kyle/decrypt.py", "r")
    encrypt = encrypt1.read()
    if os.path.exists(f5):
        f1 = file(f5, "w")
        f1 = open(f5, "w")
        f1.write(encrypt)
        f1.close()
    else:
        f1 = file(f5, "w")
        f1 = open(f5, "w")
        f1.write(encrypt)
        f1.close()

    print 50*"-"

This is the code that I use for decryption:

import os

q = 1
while q == 1:
    #opens the cipher text and it converts it to decimal
    cipher = raw_input("cipher text: ")
    cipher1 = open(cipher, "r")
    cipher2 = cipher1.read()
    cipher3 = [ord(c) for c in cipher2]

    #opens the key and coverts it to decimal
    key = raw_input("key: ")
    key1 = open(key, "r")
    key2 = key1.read()
    key3 = [ord(c) for c in key2]

    #subtracts the key from the cipher
    a = cipher3
    b = key3
    c = map(lambda x: (x[0]-x[1]) % 256, zip(a,b))

    #prints out the decrypted plain text
    decrypt = ''.join(map(chr,c))
    #makes a file with the decrypted output
    path1 = raw_input("out folder: ")
    name = "plain_text.txt"
    path2 = path1 + "/" + name
    if os.path.exists(path2):
        f1 = file(path2, "a")
        f1 = open(path2, "a")
        f1.write(decrypt)
        f1.close()
    else:
        f1 = file(path2, "w")
        f1 = open(path2, "w")
        f1.write(decrypt)
        f1.close()

    print 50*"-"


texts: Function to determine the effect of a lightning bolt on a game character using "abilities"

texts:
I'm writing my first game and would love some advice on how to get away from all this hardcoding I'm using...
Each Character has "abilities" (all individual functions) but I can't seem to figure out how to streamline this. Example:

def lightning_bolt(self):
    if self.is_stunned:
        print("Stunned...ability unsuccessful.")
    elif self.is_confused:
        confused_test = roll_d_x(2)
        if confused_test == 1:
            print("Confused...ability unsuccessful.")
    else:
        defender.mobility = (defender.mobility / 2)
        success = self.success_check()
        defender.mobility = (defender.mobility * 2)
        if success:
            volatile_roll = roll_d_x(10)
            if volatile_roll == 1:
                self.volatile_magic()
            else:
                defender.lose_health(((self.energy * 0.5) + 10))
                self.lose_energy(25)
                stun_test = roll_d_x(4)
                if stun_test == 1:
                    defender.is_stunned = True
        else:
            print("Ability failed.")

Note: all abilities must pass this "stunned and confused test" and a "volatile test". I will be defining a function for those. *I wanted to make "class Ability:", but I want each character to have their own individual abilities. Is there a way to nest classes or something? Any ideas to streamline aspects like "cost" and "damage dealt", etc.?


texts:
To be honest, I am pretty new to coding. I want to analyse the articles my local newspaper publishes on ther website. To do that, I have a list of URLs and from that, I want to download and save all the articles published. This is my code:

from bs4 import BeautifulSoup
import urllib.request
import pickle
import time

def savelist(allurls, dname):
    with open(dname, 'wb') as f:
        pickle.dump(allurls, f, pickle.HIGHEST_PROTOCOL)

def readlist(dname):
    with open(dname, 'rb') as f:
        return(pickle.load(f))

def turntosoup(liste):
    #turns a list of URLs to a list of soups
    soups = list()
    for url in liste:
        r = urllib.request.urlopen(url)
        soup = BeautifulSoup(r, 'html.parser')
        soups.append(soup)
    return(soups)

def einzelsuppe(url):
    r = urllib.request.urlopen(url)
    soup = BeautifulSoup(r, 'html.parser')
    return(soup)

def gettextdesk(soup):
    #extracts the Text from the Soup and returns a List
    article=(soup.find(class_='g_m_1of2'))
    try:
        hlwithhtml=article.find('h1')
        hl = hlwithhtml.string
    except:
        hl = ''

    try:
        pubdatewithhtml=article.find(class_='publication_date')
        pubdate = pubdatewithhtml.getText(' ', strip=True)
    except:
        pubdate = ''

    try:
        abstractwithhtml=article.find(class_='abstract ')
        abstract=abstractwithhtml.getText(' ', strip=True)
    except:
        abstract = ''

    try:
        contentwithhtml=article.find(class_='content')
        while contentwithhtml.script:
            contentwithhtml.script.decompose()
        content = contentwithhtml.getText(' ', strip=True)
    except:
        content = ''

    newspost = [str(hl), str(abstract), str(content), str(pubdate)]
    return(newspost)

def workonlist(urllist):
    souplist = turntosoup(urllist)
    soups = list()
    for soup in souplist:
        geparst = gettextdesk(soup)
        soups.append(geparst)
    return(soups)

start_time = time.time()

essenurls = readlist('Liste URLs Essen')

def chunker(seq, size):
    # found here: http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks
    return[seq[pos:pos + size] for pos in range(0, len(seq), size)]

def abarbeiten(essenurls):
    count = 50
    for teilurls in chunker(essenurls, 50):
        savelist(workonlist(teilurls), 'Essen %d' % count)
        count +=50

abarbeiten(essenurls)

print("--- %s seconds ---" % (time.time() - start_time))

Where should I change stuff to improve performance? It takes about 1.9 seconds per URL, and i wondered if I could make it faster.

This is the output of python3 -m cProfile -s cumtime Abrufen.py:

http://pastebin.com/2yLXGx3s (i couldn't post it here because of the character limit)

Here is a list of URLs as an example:

essenurls = ['http://www.derwesten.de/staedte/essen/schweinekopf-an-moschee-in-essen-altendorf-befestigt-id12200572.html','http://www.derwesten.de/staedte/essen/vor-drei-jahren-verschwand-pierre-pahlke-aus-essen-id12201302.html','http://www.derwesten.de/staedte/essen/essen-packt-an-geht-riesenbaerenklau-an-die-wurzel-id12201120.html']


texts:
This is the first coding class I've taken and I'm not getting much feedback from the instructor. The function of this program is to take two roman numeral inputs, convert them to arabic, add them together, then convert the sum to roman numerals. I wanted to see if any of you code ninjas could give me some feedback on the solution that I've come up with for this.

I would like to note that in the class I'm taking we haven't learned about dictionaries and we have only briefly covered lists.

This is only the functional part of the code, not including the loops to catch improper inputs.

print('Enter two roman numeral number to be added together')
print()

#converting first roman numeral to arabic

user1 = input('Enter first roman numeral: ')

print()

total1 = 0

for i in user1:
    if i == 'I':
        total1 += 1
    elif i == 'V':
        total1 += 5
    elif i == 'X':
        total1 += 10
    elif i == 'L':
        total1 += 50
    elif i == 'C':
        total1 += 100
if 'IV' in user1:
    total1 -= 2
if 'IX' in user1:
    total1 -= 2
if 'XL' in user1:
    total1 -= 20

print('The decimal value of', user1, 'is', total1)
print()
#converting second roman numeral to arabic

user2 = input('Enter second roman numeral: ')

print()

total2 = 0

for i in user2:
    if i == 'I':
        total2 += 1
    elif i == 'V':
        total2 += 5
    elif i == 'X':
        total2 += 10
    elif i == 'L':
        total2 += 50
    elif i == 'C':
        total2 += 100
if 'IV' in user2:
    total2 -= 2
if 'IX' in user2:
    total2 -= 2
if 'XL' in user2:
    total2 -= 20

print('The decimal value of', user2, 'is', total2)
print()

totalSum = total1 + total2

print('The decimal sum is:', totalSum)
print()

numeral = []

# converting from arabic to roman numeral
# splits the number into integers and appends roman numeral characters to a list

while totalSum > 1:
    for i in range(len(str(totalSum))): #this loop to identify the one, tens, hundreds place
        if i == 0:
            digit = totalSum % 10
            totalSum //= 10
            if digit == 9:
                numeral.append('IX')
            if 5 < digit < 9:
                numeral.append('I' * (digit % 5))
                digit -= digit % 5
            if digit == 5:
                numeral.append('V')
            if digit == 4:
                numeral.append('IV')
            if digit < 4:
                numeral.append('I' * digit)
        if i == 1:
            digit = totalSum % 10
            totalSum //= 10
            if digit == 9:
                numeral.append('XC')
            if 5 < digit < 9:
                numeral.append('X' * (digit % 5))
                digit -= digit % 5
            if digit == 5:
                numeral.append('L')
            if digit == 4:
                numeral.append('XL')
            if digit < 4:
                numeral.append('X' * digit)
        if i == 2:
            digit = totalSum % 10
            totalSum //= totalSum
            numeral.append('C' * digit)

numeral.reverse()

print('The roman sum is: ', ''.join(numeral))


texts:
I am trying to XOR two files each 1Mb which contains only 0 and 1. It works, but I think it is very slow for the C++ program - approximately 4 sec.

Could someone, please, suggest the fastest XOR method on large files or at least tell what you think about XORing 1MB files running time? May 0.5sec or 1sec? or even less...
What should be my goal related to time?

PS
Yes, I did not read files by chunks or mapping them.

#include <iostream>
#include <fstream>
#include <vector>
#include <cstring>
#include <algorithm>
#include <iterator>
using namespace std;

inline std::vector<int> read_vector_from_disk(std::string file_path)
{
    std::ifstream instream(file_path, std::ios::in | std::ios::binary);
    std::vector<int> data((std::istreambuf_iterator<char>(instream)), std::istreambuf_iterator<char>());
    return data;
}

int main()
{
    // Open result file.
    fstream new_file;
    new_file.open("output.txt", ios::out | ios::app);
    if (!new_file)
    {
        cout << "File creation failed";
    }

    // Here we will store the result
    std::vector<int> xored_file;

    std::vector<int> in_data = read_vector_from_disk("first_arg.txt");
    std::vector<int> out_data = read_vector_from_disk("second_arg.txt");

    //creating iterator
    vector<int>::iterator first_iter = in_data.begin();
    vector<int>::iterator second_iter = out_data.begin();

    //printing all elements
    cout << "XOR-ed elements are: ";

    for (; first_iter != in_data.end() && second_iter != out_data.end(); first_iter++, second_iter++)
    {
        int xored = *first_iter ^ *second_iter;
        xored_file.push_back(xored);
    }

    // Print result.
    vector<int>::iterator out_iter = xored_file.begin();
    for (; out_iter != xored_file.end(); out_iter++)
    {
        new_file << *out_iter;
    }

    cout << "Complete";

    return 0;
}


texts:
I want to remove a connection string that may already have been set in a different config file and then set it again.
Say my application has a Web.config file and a Web.Debug.config file then I can achieve what I want to do in the following way:
Web.config:
  <connectionStrings>
    <remove name="MyConnectionString" />
    <add name="MyConnectionString" connectionString="...";User Id=******;Password=******;" />
  </connectionStrings>

Web.Debug.config
  <connectionStrings>
    <remove xdt:Transform="Replace" name="MyConnectionString" />
    <add
      xdt:Transform="SetAttributes(connectionString)"
      xdt:Locator="Condition(@name='MyConnectionString')"
      connectionString="...";User Id=******;Password=******;"
    />
  </connectionStrings>

I am going to be removing connection strings and then adding them to ensure there are no errors that result from a connection string already having been set in some other config file. Before I change tens or hundreds of config files across all of our repositories I want to know if there is a better way - easier to read or requiring fewer/simpler changes.


texts:
The program reads in an operation, and then numbers, and does stuff to them based on that.

Exercise number 1 at this linl

For example, ./this_file sum 1 2 3 would yield 6

I'm fairly certain I don't need all the #includes, but I had added them at some point to deal with a problem, some ideas I kept others I didn't.

I've also started reading Accelerated C++ and I realize that I should have probably tried to use things like Array<> if it's to really be C++.

/*
 * Write a program that takes as its first argument one of the words ‘sum,’ ‘product,’ ‘mean,’ or ‘sqrt’  and for further arguments a series of numbers.
 * The program applies the appropriate function to  the series.
 */

#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <iostream>
#include <string.h>

using namespace std;

// Prototypes
double sum(int argc,const char* argv[]);
double product(int argc, const char* argv[]);
double mean(int argc, const char* argv[]);

int main(int argc, const char* argv[])
{
    double return_value;
    if(argc == 3)
    {
        //This means we're in sqrt, as we don't support sqrt of > 1 number
        //Nor sum, product, etc of less than one. 'cause that's dumb

        double operand;
        operand = strtod(argv[2], NULL );
        return_value = sqrt(operand);

    }
    else
    {
        if(strcmp(argv[1],"sum") == 0)
        {
            return_value = sum(argc, argv);
        }
        if(strcmp(argv[1],"product") == 0)
        {
            return_value = product(argc, argv);
        }
        if(strcmp(argv[1],"mean") == 0)
        {
            return_value = mean(argc, argv);
        }
    }

    cout << return_value << endl;
}

double sum(int argc,const char* argv[])
{

    double return_value = 0.0;
    for(int i = 2; i < argc; i++)
    {
        double x = strtod(argv[i], NULL);
        return_value += x;
    }
    return return_value;
}

double product(int argc, const char* argv[])
{

    double return_value = 1;
    for(int i = 2; i < argc; i++)
    {
        return_value *= strtod(argv[i],NULL);
    }
    return return_value;
}

double mean(int argc,const char* argv[])
{
    double summation = sum(argc, argv);
    return summation/((double) argc-2);
}


texts: Small script to re-create a file indefinitely

texts:
I created a small ruby script at work to recreate a text file I use for a test in the Java application we are supporting.

I'm still really new to the ruby paradigm and wanted to know if that small script respect most of the spirit of it.

The content of the file doesn't need to make sense since the only requirement I have is that a file exist.

Since I'm doing my test every minute mostly, I set the sleeping time between checking the existence of the file to 30 seconds.

require 'pathname'

PATH = "C:/folder/to/file/test1.txt"
SLEEP_TIME = 30

path_to_text_file = Pathname.new(PATH)
while (true)
  unless path_to_text_file.exist? then
    File.open(PATH, "w") {|f| f.write("test") }
    puts "File #{PATH} created"
  end
  puts "Sleeping for #{SLEEP_TIME} seconds"
  sleep(SLEEP_TIME)
end

Could I do better? I'm on Windows and using JRuby, is there something I'm missing with my code being portable ?

Obvisously, I could make the path an argument of my script, but I don't need this at the moment.


texts:
Just starting out in Python, coming from a C/C++ background. Any comments on style, how its solved, unseen redundancies, is it 'Pythonic' enough or am I lacking in the general syntax structure?

#https://projecteuler.net/problem=1
'''
problem statement: If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.

Created on Jan 12, 2018

@author: Anonymous3.1415
'''

#is test number divisable by divisor
def divisable_by(divisor,test_num):
    if not test_num % divisor:
        return True
    else:
        return False
'''
FUNCTION DEF: nat_nums_divisors_1_or_2(divisor1, divisor2 , range_start, range_end)
PURPOSE: Find list of natural numbers that are divisable by either divisor1 or divisor2
@ var: (nat_nums_list) list of numbers that satisfy conditon
@ var: (nat_num_iterator) used to iterate through the natural numbers withing a given range

'''
def nat_nums_divisors_1_or_2(divisor1, divisor2 , range_start, range_end):
    nat_nums_list = []
    for nat_num_iterator in range(range_start, range_end):
        if divisable_by(divisor1, nat_num_iterator) or divisable_by(divisor2, nat_num_iterator):
            nat_nums_list.append(nat_num_iterator)
        nat_num_iterator += 1
    return nat_nums_list

nat_nums_div_3_5 = [] # Natural numbers divisable by either 3 or 5
divisor_3, divisor_5 = 3, 5
range_start, range_end = 1, 1000

nat_nums_div_3_5 = nat_nums_divisors_1_or_2(divisor_3, divisor_5, range_start, range_end)

nat_nums_div_3_5_sum = sum(nat_nums_div_3_5)
print ("The sum of Natural Numbers in range: [%d, %d]; divisable by either 3 or 5 is: %d") % (range_start, range_end, nat_nums_div_3_5_sum)


texts:
This is my first text-based game I made. It's very small because I just learned Python and wanted to start small and then code bigger programs. Please comment on this.

import random
import time
import sys

def fight_enemy(enemy_name, min_enemy_damage, max_enemy_damage, min_player_damage, max_player_damage):
    enemy_damage_dealt = random.randint(min_enemy_damage, max_enemy_damage)
    player_damage_dealt = random.randint(min_player_damage, max_player_damage)

    if enemy_damage_dealt > player_damage_dealt:
        print("Uh-oh! You died!")
        game_over()
    elif enemy_damage_dealt < player_damage_dealt:
        print("You killed the {enemy_name}".format(enemy_name=enemy_name))
        its_getting_late()
    else:
        print("You walk away unscathed, but the {enemy_name} still lives.".format(enemy_name=enemy_name))
        its_getting_late()

def fight_enemy_2(enemy_name, min_enemy_damage, max_enemy_damage, min_player_damage, max_player_damage):
    enemy_damage_dealt = random.randint(min_enemy_damage, max_enemy_damage)
    player_damage_dealt = random.randint(min_player_damage, max_player_damage)

    if enemy_damage_dealt > player_damage_dealt:
        print("Uh-oh! You died!")
        game_over()
    elif enemy_damage_dealt < player_damage_dealt:
        print("You killed the {enemy_name}".format(enemy_name=enemy_name))
        game_end()
    else:
        print("You walk away unscathed, but the {enemy_name} still lives.".format(enemy_name=enemy_name))
        game_end()

def intro():
    name = input("Enter you name: ")
    print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
    print("Welcome to the Wildlife %s" %(name))
    print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
    time.sleep(1)
    desert()

def desert():
    print("You are in the middle of a Desert in Africa")
    time.sleep(2)
    print("All you see is Sand. EVERYWHERE!!!")
    time.sleep(2)
    print("You start walking")
    time.sleep(2)
    print("You see a Snake")
    ch1 = str(input("Do you wanna attck the Snake? [y/n]: "))

    if ch1 in ['y', 'Y', 'YES', 'Yes', 'yes']:
        time.sleep(2)
        fight_enemy('Snake', 1, 7, 1, 7)
    elif ch1 in ['n', 'N', 'No', 'NO', 'no']:
        print("You slowly back away")
        time.sleep(1)
        print("You managed to get away from the Snake")
        print("But you fell in a sinkhole and died")
        game_over()

def game_end():
    print("Congratulations you won!!!")
    ch4 = str(input("Do you wanna play again? [y/n] "))

    if ch4 in ['y', 'Y', 'YES', 'Yes', 'yes']:
        intro()
    elif ch4 in ['n', 'N', 'No', 'NO', 'no']:
        print("Thank you for playing")

def its_getting_late():
    time.sleep(1)
    print("Its starting to get late")
    ch2 = str(input("Do you wanna go to sleep? [y/n]: "))

    if ch2 in ['y', 'Y', 'YES', 'Yes', 'yes']:
        print("You were shot dead last Night")
    elif ch2 in ['n', 'N', 'No', 'NO', 'no']:
        print("You stay up")
        print("You see a person")
        ch3 = str(input("Do you wanna attack the person? [y/n]: "))

        if ch3 in ['y', 'Y', 'YES', 'Yes', 'yes']:
            time.sleep(1)
            fight_enemy_2('Enemy', 4, 9, 1, 7)
        elif ch3 in ['n', 'N', 'No', 'NO', 'no']:
            print("You try to run away")
            print("But the Enemy is faster than you and stabs you")
            game_over()

def game_over():
    print("You lost")
    ch5 = str(input("Do you wanna play again? [y/n] "))

    if ch5 in ['y', 'Y', 'YES', 'Yes', 'yes']:
        intro()
    elif ch5 in ['n', 'N', 'No', 'NO', 'no']:
        print("Thank you for playing")

intro()


texts:
Problem - The classic puzzle of finding the minimum amount of time required to cross a bridge given that only two people can cross the bridge at any one time.
Since they have only one flashlight (it's dark and they need the flashlight), the two people move at the speed of the slower one.

Constraints - Upto 6 people (although it should work for a higher number of people)

Input - Number of people (up to 6 tested) & Sorted vector of time required by each person to cross the bridge.

Output - Minimum time possible

int main()
{
  vector<int> v; int n; int time;
  int items;
  int k = 2;
  cin>>items;
  for (int i = 0; i < items; i++)
  {
    cin >> n;
    v.push_back(n);
   }

  if (v.size() == 1)
  {
    cout << v[0];
    return 0;
  }
  int last = v.size() - 1;
  time = v[0] + v[1] + v[last] + v[1];

  while (last-k >= 2)
  {
    time += v[0] + v[last - k];
    k++;
  }
  time = time + v[1];

  cout << time;
  return 0;
}

Note : Code will not work for 2 people, missed a special case.


texts: Normalise list of N dimensional numpy arrays

texts:
I have a list of N dimensional NumPy arrays.

num_vecs = 10
dims = 2

vecs = np.random.normal(size=(num_vecs, dims))

I want to normalize them, so the magnitude/length of each vector is 1. I can easily do this with a for-loop.

norm = np.linalg.norm(vecs, axis=1)

for dd in range(dims):
    vecs[:, dd] /= norm

assert np.allclose(np.linalg.norm(vecs, axis=1), 1.)

But how do I get rid of the for-loop?


texts:
Is my implementation of AVL tree correct? It is my second Python program and I am not sure if do code properly.

'''
Created on 30 sty 2016

AVL tree - my second python program :)

@author: stanek
'''

class Node:

    def __init__(self, data, left = None, right = None, height = 0):
        self.data = data
        self.left = left
        self.right = right
        self.height = height

    def add_node(self, data):
        if self.data > data:
            '''Adding to left subtree'''
            if self.left is None:
                self.left = Node(data)
            else:
                self.left.add_node(data)
                if ( self.get_left_height() - self.get_right_height() == 2):
                    ''' Then we need to balance a subtree'''
                    print("Rebalancing after inserting", data)
                    if (data < self.left.data):
                        self.rotate_left()
                    else:
                        self.double_rotate_left()

        else:
            '''Adding to right subtree'''
            if self.right is None:
                self.right = Node(data)
            else:
                self.right.add_node(data)
                if ( self.get_right_height() - self.get_left_height() == 2):
                    ''' Then we need to balance a subtree'''
                    print("Rebalancing after inserting", data)
                    if (data < self.right.data):
                        self.rotate_right()
                    else:
                        self.double_rotate_right()

    def print_nodes(self):
        if self.left is not None:
            self.left.print_nodes()
        print(self);
        if self.right is not None:
            self.right.print_nodes()

    '''
    AVL methods
    '''
    def get_right_height(self):
        if self.right is None:
            return -1
        else:
            return self.right.height

    def get_left_height(self):
        if self.left is None:
            return -1
        else:
            return self.left.height

    def set_height(self):
        self.get_height = max( self.left.get_height, self.right.get_height ) + 1

    def rotate_right(self):
        print("rotating right",self.data);
        temp = self
        self = self.right
        self.right = temp
        self.right.set_height
        self.set_height

    def rotate_left(self):
        print("rotating left",self.data);
        temp = self
        self = self.left
        self.left = temp
        self.left.set_height()
        self.set_height()

    def double_rotate_right(self):
        print("double rotating right",self.data);
        temp = self.left
        self.left = temp.right
        temp.right = self
        self = temp
        self.right.set_height
        self.set_height

    def double_rotate_left(self):
        print("double rotating left",self.data);
        temp = self.right
        self.right = temp.left
        temp.left = self
        self = temp
        self.left.set_height
        self.set_height

    def __str__(self):
        return str(self.data)

class binary_tree:

    def __init__(self):
        self.root = None

    def getRoot(self):
        return self.root

    def add(self, data):
        if self.root is None:
            self.root = Node(data)
        else:
            self.root.add_node(data)

    def print_all(self):
        if self.root is None:
            print("Empty tree")
        else:
            self.root.print_nodes();

if __name__ == '__main__':
    b = binary_tree();
    b.add(1)
    b.add(2)
    b.add(4)
    b.add(6)
    b.add(3)
    b.add(5)
    b.print_all()


texts:
The problem statement is as follows

By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10,001st prime number?

My code that follows is what I used to solve this with.
public class Program
{
    static bool IsPrime(long value)
    {
        if (value==2)
            return true;

        if (value % 2 ==0)
            return false;

        long largestPossibleFactor = (long)Math.Sqrt(value);
        for (int possiblePrimeFactor = 3; possiblePrimeFactor <= largestPossibleFactor; possiblePrimeFactor +=2)
        {
            if (value % possiblePrimeFactor == 0)
                return false;
        }
        return true;
    }

    static long GetPrimeOccurence(int NthOccurence)
    {
        if (NthOccurence==1)
            return 2;

        int primePosition=2;
        long returnValue=0;
        bool numberIsPrime =false;
        for (long testForPrime=3; primePosition <= NthOccurence; testForPrime +=2)
        {
            numberIsPrime = IsPrime(testForPrime);

            if (numberIsPrime && primePosition == NthOccurence)
                returnValue = testForPrime;

            if (numberIsPrime)
                primePosition++;
        }
        return returnValue;
    }

    public static void Main(string[] args)
    {
        Console.WriteLine(GetPrimeOccurence(10001));
    }
}


texts: Printing the contents of a string array using pointers

texts:
I'm currently studying C and I'm trying to just print the contents of a string array. I'm using pNames to point to the first char pointer and iterating from there.

A more proper approach would use this pointer, get a char* each time and use printf("%s", pNames[i]) to print a whole string. However, I thought I would try to print it character-by-character inside each string, as follows:

#include <stdio.h>

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

char *names[] = {
    "John", "Mona",
    "Lisa", "Frank"
};

char **pNames = names;
char *pArr;
int i = 0;
while(i < 4) {

    pArr = pNames[i];
    while(*pArr != '\0') {
        printf("%c\n", *(pArr++));
    }
    printf("\n");
    i++;
}
return 0;
}

This code kind of works (prints each letter and then new line). How would you make it better?


texts:
I saw this problem posted as an interview question asked at Bloomberg:

  Given an integer N, print numbers from 1 to N in lexicographic order.
  Restriction. One cannot use strings or characters.

Below is my solution to this problem. Can the algorithm be improved?

#!/usr/bin/env python
import sys
import traceback

def printlexnum(i, tens, number):
    lexnum = i*tens
    for j in range(lexnum,min(number+1,lexnum+tens)):
        print j
    if number>=lexnum:
        printlexnum(i, tens*10, number)
    return

try:
    if len(sys.argv) < 2:
        number = 0
        while number < 0:
            number = int(raw_input('please enter number >0: '))
        if number == 0:
            sys.exit(1)
    else:
        number = int(sys.argv[1])
        if number <= 0:
            print "Bad argument." + number + " must be greater than zero."
            sys.exit(1)
    for i in range(1,min(10,number+1)):
        print i
        printlexnum(i,10, number)
except ValueError, e:
    traceback.print_exc()
    print sys.argv[1], " Input not an integer"
except Exception, e:
    traceback.print_exc()
    print sys.argv[1], " Exception thrown"
finally:
    a = 1 # dummy line


texts: Is there a better way to handle multiple join statements in a linq query?

texts:
I am rewriting a VB.NET app into C#. I won't subject you to the original code. I am mainly looking for a better way to handle all the join statements that are being done. I am dealing with a legacy database that I cannot currently change the structure of. (Though I am making my arguments for it)

I am wondering if there is a better / cleaner way to handle multiple join statements. I am using DB first EF 6.1 so I have more options than was originally available. Here is the original Linq query converted to C#:

(from myObject in _context.MyObjects
join myObjectType in _context.MyObjectTypes on myObject.CRTKey equals myObjectType.CRTKey
join myObjectsSchedule in _context.MyObjectSchedule on myObject.CRS_Key equals myObjectsSchedule.CRS_Key
join myObjectGroup in _context.MyObjectGroups on myObject.ReportKey equals myObjectGroup.ReportKey
where myObjectGroup.ReportGroupNameKey == groupNameKey
select myObject).Distinct();

This particular example only has three joins I have a few blocks of code that have in  excess of 6 join statements. Is there a better way to handle all the join statements?


texts: Recursively walk directories with a callback function

texts:
This code works, but I want to refine it:

# =======================
# Dir Walk
#
# This will recursively walk a directory
# ========================

function dirwalk(path::AbstractString, fn::Function)
  content = readdir(path)
  for c in content
    p = joinpath(path, c)
    if isdir(p)
      dirwalk(p, fn)
    elseif isfile(p)
      fn(p)
    end
  end
end


texts: Flutter: ToggledButtons using FlatButton

texts:
I'm new to Dart and Flutter and I would like to know what do you think about this code and if it's any way that I could improve it :).

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Checked Listview',
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);

  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
          child: ToggleButtons(
        selectedWidget: <Widget>[
          Text("select_1"),
          Text("select_2"),
          Text("select_3")
        ],
        unselectedWidget: <Widget>[
          Text("unselect_1"),
          Text("unselect_2"),
          Text("unselect_3")
        ],
        onPressed: (elem, isSelected) {
          if (isSelected) {
            print(elem);
          }
        },
        shouldBeJustOneSelected: true,
      )),
    );
  }
}

class ToggleButtons extends StatefulWidget {
  final List<Widget> selectedWidget;
  final List<Widget> unselectedWidget;
  final bool shouldBeJustOneSelected;
  final Function(Widget widget, bool isSelected) onPressed;

  ToggleButtons(
      {Key key,
      this.selectedWidget,
      this.unselectedWidget,
      this.shouldBeJustOneSelected,
      this.onPressed})
      : super(key: key);

  _ToggleButtonsState createState() => _ToggleButtonsState();
}

class _ToggleButtonsState extends State<ToggleButtons> {
  List<Widget> _originalButtons = List<Widget>();
  List<Widget> _choosedButtons = List<Widget>();

  @override
  void initState() {
    super.initState();
    _choosedButtons = widget.unselectedWidget;
  }

  buildList() {
    if (_originalButtons.isNotEmpty) {
      _originalButtons.clear();
    }
    for (int i = 0; i < _choosedButtons.length; i++) {
      _originalButtons.add(FlatButton(
        child: _choosedButtons[i],
        onPressed: () {
          print(i);
          rebuildList(i);
        },
      ));
    }
    return _originalButtons;
  }

  List<Widget> deepCopyList(List<Widget> list) {
    var newList = List<Widget>();
    for (int i = 0; i < list.length; i++) {
      newList.add(list[i]);
    }
    return newList;
  }

  List<Widget> deepCopyListElement(List<Widget> list, Widget elem, int ind) {
    var newList = List<Widget>();
    for (int i = 0; i < list.length; i++) {
      if (i == ind) {
        newList.add(elem);
      } else {
        newList.add(list[i]);
      }
    }
    return newList;
  }

  void rebuildList(int ind) {
    setState(() {
      Widget newElement = _choosedButtons[ind] == widget.unselectedWidget[ind]
          ? widget.selectedWidget[ind]
          : widget.unselectedWidget[ind];
      bool isSelected =
          _choosedButtons[ind] == widget.unselectedWidget[ind] ? true : false;

      if (widget.shouldBeJustOneSelected) {
        _choosedButtons = deepCopyList(widget.unselectedWidget);
      }
      _choosedButtons = deepCopyListElement(_choosedButtons, newElement, ind);

      widget.onPressed(newElement, isSelected);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: buildList(),
    );
  }
}

Just let me know if you think I can improve it in any way, thanks :D


texts:
I wrote two template functions to take an integer type and output a float in the given range. One function takes signed integers and the other takes unsigned integers.

The functions are used to normalize audio PCM data into a range that an encoder is expecting, such as [0.0f, 1.0f]. The source audio data can come in many forms (signed, unsigned, 1 byte, 2 bytes, etc) so I thought template functions would be ideal for this.

The caller has the responsibility of calling the function with an appropriately sized type containing the sample to normalize (e.g. int16_t). The functions use a lookup-table to determine the max/min values the type can contain based on the size of the integer type.

util.cc

#include <stdint.h>

const uintmax_t MAX_VALUE_PER_BYTES_UNSIGNED[] = {
    0,
    uintmax_t(UINT8_MAX),
    uintmax_t(UINT16_MAX),
    uintmax_t(UINT16_MAX) + uintmax_t(UINT8_MAX),
    uintmax_t(UINT32_MAX),
    uintmax_t(UINT32_MAX) + uintmax_t(UINT8_MAX),
    uintmax_t(UINT32_MAX) + uintmax_t(UINT16_MAX),
    uintmax_t(UINT32_MAX) + uintmax_t(UINT16_MAX) + uintmax_t(UINT8_MAX),
    uintmax_t(UINT64_MAX)
};

const intmax_t MAX_VALUE_PER_BYTES_SIGNED[] = {
    0,
    intmax_t(INT8_MAX),
    intmax_t(INT16_MAX),
    intmax_t(INT16_MAX) + intmax_t(INT8_MAX),
    intmax_t(INT32_MAX),
    intmax_t(INT32_MAX) + intmax_t(INT8_MAX),
    intmax_t(INT32_MAX) + intmax_t(INT16_MAX),
    intmax_t(INT32_MAX) + intmax_t(INT16_MAX) + intmax_t(INT8_MAX),
    intmax_t(INT64_MAX)
};

const intmax_t MIN_VALUE_PER_BYTES_SIGNED[] = {
    0,
    intmax_t(INT8_MIN),
    intmax_t(INT16_MIN),
    intmax_t(INT16_MIN) + intmax_t(INT8_MIN),
    intmax_t(INT32_MIN),
    intmax_t(INT32_MIN) + intmax_t(INT8_MIN),
    intmax_t(INT32_MIN) + intmax_t(INT16_MIN),
    intmax_t(INT32_MIN) + intmax_t(INT16_MIN) + intmax_t(INT8_MIN),
    intmax_t(INT64_MIN)
};

util.h

#include <stdint.h>
#include <limits>
#include <cmath>

extern const uintmax_t MAX_VALUE_PER_BYTES_UNSIGNED[];
extern const intmax_t MAX_VALUE_PER_BYTES_SIGNED[];
extern const intmax_t MIN_VALUE_PER_BYTES_SIGNED[];

template <typename T>
float normalizeToRangeFloatSigned(T num, float rangeMin, float rangeMax) {
    float f = 0.0f;

    if (!std::numeric_limits<T>::is_integer) {
        return f;
    }

    const float rangeDiff = rangeMax - rangeMin;
    if (!rangeDiff || rangeDiff < 0.0f) {
        return f;
    }

    uintmax_t uintRangeMax = MAX_VALUE_PER_BYTES_UNSIGNED[sizeof(T)];

    const intmax_t tRangeMin = MIN_VALUE_PER_BYTES_SIGNED[sizeof(T)];
    const intmax_t tRangeMax = MAX_VALUE_PER_BYTES_SIGNED[sizeof(T)];
    const intmax_t tRangeMinAbs = std::abs(tRangeMin);
    float percent = 0.0f;

    if (num < 0) {
        if (num == tRangeMin) {
            percent = 0.0f;
        } else {
            percent = (tRangeMinAbs - T{-1} * num) / float(uintRangeMax);
        }
    } else if (!num) {
        percent = 0.5f;
    } else {
        if (num == tRangeMax) {
            percent = 1.0f;
        } else {
            percent = (num + tRangeMinAbs) / float(uintRangeMax);
        }
    }

    f = (percent) * rangeDiff + rangeMin;

    return f;
}

template <typename T>
float normalizeToRangeFloatUnsigned(T num, float rangeMin, float rangeMax) {
    float f = 0.0f;

    if (!std::numeric_limits<T>::is_integer) {
        return f;
    }

    const float rangeDiff = rangeMax - rangeMin;
    if (!rangeDiff || rangeDiff < 0.0f) {
        return f;
    }

    uintmax_t uintRangeMax = MAX_VALUE_PER_BYTES_UNSIGNED[sizeof(T)];
    f = (num / float(uintRangeMax)) * rangeDiff + rangeMin;

    return f;
}

I don't have much experience with templates so any feedback is welcome. Also, any improvements to the functions time-efficiency.


texts: Script to get available IP automatically

texts:
Recently I made a script to get available IP automatically. I was woundering if anyone can give me tips on how to make this code look better, preferably in a class and OOP. I'm gonna show the code to my boss, but i want it to look clean and nice before i do so, and hopefully learn a thing or two about writing better code.

Code:

import requests
from orionsdk import SwisClient
import getpass

# Brukerinfromasjon
npm_server = 'mw-solarwinds.yy.dd'
username = 'jnk'
password = getpass.getpass()

server_navn = input('Skriv inn DNS navn: ')
dns_ip = '10.96.17.4'  # 10.96.17.5 = Felles
dns_sone = 'yy.dd'

verify = False

if not verify:
    from requests.packages.urllib3.exceptions import InsecureRequestWarning

    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

swis = SwisClient(npm_server, username, password)  # Kjører mot IPAM med brukerinformasjon

subnets = {
    'ka-windows': ['10.112.12.0', '24'],
    'ka-linux': ['10.112.10.0', '24'],
    'ka-exa-mgmt': ['10.112.26.0', '28']
}

print("Tilgjengelige subnets: ")

for i in subnets:
    print(i)

print("--------------")

found = False

while not found:
    inp = input("Skriv in Subnet: ")
    if inp in subnets:
        '''
        Finner ledig IP adresse i subnet
        '''

        sub_ip = subnets[inp][0]
        sub_cdir = subnets[inp][1]
        ipaddr = swis.invoke('IPAM.SubnetManagement', 'GetFirstAvailableIp', sub_ip, sub_cdir)
        '''
        Sette DNS > IP
        '''
        dns = swis.invoke('IPAM.IPAddressManagement', 'AddDnsARecord', server_navn, ipaddr, dns_ip, dns_sone)
        print("IP: {} > DNS: {}".format(ipaddr, server_navn))
        found = True
    else:
        print("Det er ikke et subnet, velg en fra listen.")


texts: SMB Script which collect remote files, mount locations, unmount locations, and show directory file tree

texts:
I've written a script that is able to accomplish the following:

mount/unmount a remote SMB location using the subprocess module
List the file contents of a specified directory
copy a single file out from a remote directory to a specified destination folder.
List subdirectories within a mounted SMB location.

I've done my best to make as much of my functionality reusable within functions, but there's a part of me that worries functions like selectSingleFile() is getting a little convoluted.

Here is my code:

import os
import shutil
import subprocess
from os import walk
from shutil import copy2
from glob import glob

def mount(remote_dir, local_dir):
    """Mounts a remote directory and chooses a local file in which to mount the directory against"""
    retcode = subprocess.call(["/sbin/mount", "-t", "smbfs", remote_dir, local_dir])

def unmount(local_dir):
    """Unmounts the local SMB directory"""
    retcode = subprocess.call(["/sbin/umount", local_dir])

def getFileContents(directory):
    """Creates a list of files within a directory"""
    f = []
    for (dirpath, dirnames, filenames) in walk(directory):
        f.extend(filenames)
        break
    return f

def printChoices(local_dir):
    """Used to print a list of numbered list of files in a directory"""
    num = 1
    a = getFileContents(local_dir)
    for item in a:
        print(str(num) + ".", item)
        num +=1

def listDirectory(directory):
    return glob(directory)

def selectSingleFile(local_dir, destination):
    '''Used to get the contents of a directory and select a single file to copy to a destination
    --requires printChoices() and getFileContents()
    '''
    a = getFileContents(local_dir)
    printChoices(local_dir)
    b = int(input("please select your choice: "))
    copy2(local_dir+(a[b-1]), destination)

''' The following was an example usage of the functions above. It allowed for mounting of a remote
file location, within the work network, and a listing/transfer of a single file within the directory.
'''
local_dir = '/Users/ParanoidPenguin/smb/' #Specifies the local directory to mount
destination = '/Users/ParanoidPenguin/Desktop/JPEGs'#For copy2, destination where file will be stored
smb_location = '//Guest@192.168.1.167/Documents' #smb location to be mounted

mount(smb_location, local_dir)

selectSingleFile(local_dir, destination)

input("Press any key to unmount: ")
unmount(local_dir)


texts: Basic input system for a few form fields

texts:
I am attempting to port a linear function that I designed in a spreadsheet into HTML and Javascript.  It's based on linear least squares where I have to take a Matrix and multiply it by its transformation. At any rate. I am attempting to lay out a basic input system in Javascript/HTML where I can enter in variable data.  I have to take in quite a few more inputs, so I am looking for a more maintainable code pattern with less duplication.

In the name of make it work, then make it better. I came up with the following code.

Very new to javascript and the scope is hurting my brain! I am thinking that a dictionary (or similar) where I can pass that to a function then iterate over the values to update my HTML view. But again I am really new to Javascript.

The code also in JS BIN.

window.onload = function() {

    var EnameField = document.getElementById('EnameField');
    var ENameValue = undefined;
    var MnameField = document.getElementById('MnameField');
    var MNameValue = undefined;
    var CnameField = document.getElementById('CnameField');
    var CNameValue = undefined;
    var FnameField = document.getElementById('FnameField');
    var FNameValue = undefined;

    updateNameDisplay();

    setInterval(updateNameDisplay, 100);

    function updateNameDisplay() {
        var thisEValue = EnameField.value || " ";
        if (ENameValue != thisEValue) {
            document.getElementById('EnameDisplay').innerHTML = ENameValue = thisEValue;
        }

        var thisMValue = MnameField.value || " ";
        if (MNameValue != thisMValue) {
            document.getElementById('MnameDisplay').innerHTML = MNameValue = thisMValue;
        }

        var thisCValue = CnameField.value || " ";
        if (CNameValue != thisCValue) {
            document.getElementById('CnameDisplay').innerHTML = CNameValue = thisCValue;
        }

        var thisFValue = FnameField.value || " ";
        if (FNameValue != thisFValue) {
            document.getElementById('FnameDisplay').innerHTML = FNameValue = thisFValue;
        }

    }

};
<!DOCTYPE html>

      <meta charset=utf-8 />
      <title>Test Page</title>

      <form>
         How many E's <input type='text' id='EnameField'>

         How many M's <input type='text' id='MnameField'>

         How many C's <input type='text' id='CnameField'>

         How many F's <input type='text' id='FnameField'>

      </form>

      E's: ??

      M's:??

      C's: ??

      F's: ??


texts:
Please let me know how I can make it better, especially with avoiding repetition without the need to replace the user guesses.

import java.util.Scanner;
public class Lottery {

    static int guess[] = new int[3],actual[]= new int[3];

    private static void aquireGuess()
    {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Time to play the lottery please choose three numbers ranging from zero to nine.");
        System.out.print("Please enter first number:");
        guess[0] = keyboard.nextInt();
        System.out.print("Please enter second number:");
        guess[1] = keyboard.nextInt();
        System.out.print("Please enter third number:");
        guess[2] = keyboard.nextInt();
        keyboard.close();
    }

    private static void generateLottery()
    {
        actual[0] = (int)(Math.random()*10);
        actual[1] = (int)(Math.random()*10);
        actual[2]= (int)(Math.random()*10);
    }

    private static void compare()
    {
        if(guess[0]==actual[0]&&guess[1]==actual[1]&&guess[2]==actual[2])
        {
            System.out.println("Congradulations three matches in exact order!!! You win $1,000,000.");
            return;
        }
        int count = 0;
        for(int i=0;i<=2;i++)
        {
            for(int x=0;x<=2;x++)
            {
                if (actual[i]==guess[x])
                {
                    count++;
                    guess[x]=-1;
                    break;
                }
            }
        }
        switch(count)
                {
        case 0:System.out.println("Sorry better luck next time."); break;
        case 1:System.out.println("Good job. One match. You win $10."); break;
        case 2:System.out.println("Awsome you made two matches. You win $100."); break;
        case 3:System.out.println("Woohoo you matched all three. You win $1,000.");break;
                }
    }

    public static void main(String args[])
    {
        aquireGuess();
        generateLottery();
        System.out.println("Your guess were "+guess[0]+" "+guess[1]+" "+guess[2]);
        System.out.println("The lottery numbers were "+actual[0]+" "+actual[1]+" "+actual[2]);
        compare();
    }
}


texts:
I am writing a domino draw game in C# and would like to know if there is a simpler/better way to know the player that has been dealt the highest double bone (where x equals y) and what bone it is:

public class Player
{
    public string Name { get; set; }
    public List<Bone> Bones;
    public Player(string name)
    {
        Name = name;
    }
}

public class Bone
{
    public int x { get; set; }
    public int y { get; set; }
}

Code in question (players is a list of player):

//select player with highest double and select the double
var pdb = players.SelectMany(pl => pl.Bones.Where(b => b.x == b.y)
    .Select(b => new { player = pl, doublebones = b }))
    .OrderByDescending(db => db.doublebones.x)
    .First();
Player playerWithHighestDouble = pdb.player;
Bone highestBone = pdb.doublebones;


texts: Regex for finding After Effects files in scene code format

texts:
I haven't used regex a lot and I needed to set up a script that can gather a list of file paths that should adhere to a strict formatting convention, so I thought that sounded like a good opportunity to use them.

To explain a bit, there's a set of sequence folders inside a root folder, and in those sequences is a set of scene folders. In those is a set of constant named folders, the relevant one being "AEP Files". Then in there is a set of after effects files, of which I want to get the highest numbered version which is denoted but _v##.aep at the end of the file. A sample path might look like this:

P:\ProjectName\Scenes\e10_q04\e10_q04_s12\AEP Files\proj_e10_q04_s12_v04.aep

I'm particularly interested to know

If I'm using regex correctly,
Whether I should use something other than if re.match(...)?
Whether I could make it more efficient (particularly the list comprehensions); and
Given the complexity, how is the current readability?

I had ideas on more efficiency but they involved collapsing list comprehensions down and I thought that would make an unreadable mess, so I opted not to. Any other feedback you want to give is also welcome!

import os
import re

root = r'P:\ProjectName\Scenes'
IGNORE = re.IGNORECASE

folders = [os.path.join(root, f) for f in os.listdir(root)
            if re.match(r'e\d*q\d*', f, IGNORE)]
folders.sort()

scene_folders = [os.path.join(folder, f) for folder in folders
                for f in os.listdir(folder)
                if re.match(r'e\d*_q\d*_s\d*', f, IGNORE)]
scene_folders.sort()

scenes = []
missing_scenes = []
for folder in scene_folders:
    matches = [re.match(r'proj_q\d*_s\d*_v(\d*)\.aep', f, IGNORE)
                for f in os.listdir(os.path.join(folder, "AEP Files"))
                if re.match(r'proj_q\d*_s\d*_v(\d*)\.aep', f, IGNORE)]
    matches = [(match.group(), match.groups()[0]) for match in matches]
    if matches:
        scenes.append(os.path.join(folder, sorted(matches)[-1][0]))
    else:
        missing_scenes.append(folder)


texts:
Below is the code for the problem at Codechef. I have made use of the String method .equals in my solution which is working fine for all the test inputs. However, I am getting a Time Limit Exceeded when I submit to the Judge. I need your ideas on optimizing the code.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main
{

    public static void main(String args[]) throws IOException
    {

        BufferedReader in =new BufferedReader(new InputStreamReader(System.in));

        int not=Integer.parseInt(in.readLine());

        for(int i=0;i<not;i++)
        {

            String s=in.readLine();
            int count=0;

            String inp[]=in.readLine().trim().split(" ");

            int m=Integer.parseInt(inp[0]);
            int p=Integer.parseInt(inp[1]);

            //System.out.println(m+" "+p);

            String temp=s;

            for(int b=0;b<(Integer.MAX_VALUE/2);b++)
            {

                //System.out.println(temp);
                String s1=rotate(m,temp);
                //System.out.println(s1);
                count++;
                if(s1.equals(s))
                    break;

                String  s2=rotate(p,s1);
                //System.out.println(s2);
                count++;
                if(s2.equals(s))
                    break;

                temp=s2;

            }

            if(count>0)
                System.out.println(count);
            else
                System.out.println(-1);

        }

    }   private static String rotate(int m, String s) {

        char sa[]=s.toCharArray();

        int l=sa.length;

        StringBuilder sb=new StringBuilder();

        for(int j=m-1;j>=0;j--)
        {

            sb.append(sa[l-1-j]);

        }

        for(int k=0;k<(l-m);k++)
            sb.append(sa[k]);

        return sb.toString();
    }

}


texts: Separating values in string and returning them as comma separated string

texts:
I am iterating through a set of values that are in the following string format:

69;#Statements;#44;#Clarifications;#45;#Suggestions;

(fields with multiple values returned from SharePoint.)

I've created a function that both adds these values to a list and returns them as a comma separated string:

Category = formatLookup( Category_Raw, categoryRow )

The function works, but is probably far from efficient. Any suggestions on how to optimize this function, used for thousands of elements?

function formatLookup( input ) {
    var result = ''
    if (typeof input != "undefined" && input != "" ) {
        if (input.indexOf(";#") >= 0) { //detect if there is more than one value in column
            if (input.match(/;#/g).length > 1) {
                var array = input.split(';#');
                for (i = 0; i < array.length; i++) {
                    if (array[i].match(/^\d+/)) { //do nothing
                    } else {
                        var output = array[i].replace(/^\d+/, '')
                        if (output != '') {
                            result += output
                            result += ', '
                        }
                    }
                }
            } else {
                result = output = input.split(';#')[1]
            }
        } else {
            result = input
        }
        if (result.slice(-2) == ', ') result = result.substr(0, result.length - 2) //if the last item has a comma, remove this
    }
    return result
}


texts:
Here is a practice question I am solving:

  Write a function to find the first non-repeated character in a string.
  For instance, the first non-repeated character in 'total' is 'o' and
  the first non-repeated character in 'teeter' is 'r'.

How can I improve the efficiency of this algorithm?

function repeater(string){
    var charCount = {};
    for(var i = 0; i < string.length; i++){
        if(charCount[string[i]]){
            charCount[string[i]] = 'More Than One';
        } else {
            charCount[string[i]] = 'One Time';
        }
    }
    for(var j = 0; j < string.length; j++){
        if(charCount[string[j]] === 'One Time'){
          return string.charAt(j);
        }
    }

    return 'Everything is repeated';
}

http://repl.it/QUf/1

I also solved this using a nested loop:

var nonRepeater = function(str) {
  var index = [];
  var count;
  str.split('').forEach(function(letter, i) {
    count = 0;
    str.split('').forEach(function(latter) {
      if (letter === latter) {
        count += 1;
      }
    });
    index.push(count);
  });
//   console.log(index.indexOf(1));
  return str[index.indexOf(1)];
};

http://repl.it/QVI/2

I am trying to find a way to increase the efficiency of this algorithm.  I am toying with ways to use a RegEx.

Does anyone know how to write this more efficiently in JavaScript?  I have found a few guides in C but I do not know the language well.


texts:
This is an AI class that takes an array of the board as an argument, and plays the best move after evaluating the board and gets a win rate. I haven't used any java package to do this. How can I make a genetic tree and calculate all possibilities for a given situation

public class AI
{
    int turn,ID;
    AI(int pID)
    {
        ID=pID;
        turn=0;
    }

    int getWinRate(int t[])
    {
        int comb[][] = {{1,2,3},{4,5,6},{7,8,9},{1,4,7},{2,5,8},{3,6,9},{1,5,9},{3,5,7}} ;
        int AIwin,oppWin,empty,j,d;
        int WinRate = 0;
        for(int i=0;i<8;i++)  //Count AI win combinations
        {
            AIwin=oppWin=empty=0;
            for(j=0;j<3;j++)
            {
                d= comb[i][j]-1;
                 if(t[d]==2)
                 AIwin++;
                 if(t[d]==1)
                 oppWin++;
                 if(t[d]==0)
                 empty++;
            }
            //Changing win rate according to win conditions
            if(AIwin==3)
            WinRate+=100;
            if(AIwin==2 && empty==1)
            WinRate+=3;
            if(oppWin==2 && empty==1)
            WinRate-=10;
        }
        return WinRate;
    }
    void play(int t1[])
    {
        int t[]=t1.clone();
        int i,j,c=0;
        for(i=0;i<9;i++){
            if(t[i]==0)
            c++;
        }
        int[] moves=new int[c];
        c=0;
        for(i=0;i<9;i++)
        {
            if(t[i]==0)
           { moves[c++]=i;}
        }
        int rate,boardcopy[]=t.clone();boardcopy[moves[0]]=2;
        int bestMove=moves[0],maxRate=getWinRate(boardcopy);
        for(i=0;i<moves.length;i++)
        {
            boardcopy=t.clone();
            boardcopy[moves[i]]=2;
            rate=getWinRate(boardcopy);
            if(rate>maxRate)
            {
                maxRate=rate;
                bestMove=moves[i];
            }
        }
        System.out.println("The Mighty AI plays : "+(bestMove+1));
        turn++;
        t1[bestMove]=2;
    }
}


texts: Checking that a filename does not end with "Com.js"

texts:
I'm fairly new to JavaScript  and I wonder if there is a way to write this function shorter and better?

   function checkFile(file){
        var cbEnab= true;
        if (file !== undefined && file !== null) {
            cbEnab = (!jQuery.endsWith(file, "Com.js"));
        }
        return cbEnab;
    }


texts:
All I want do to is simply get the result of how long (in seconds) the PHP takes to process the SQL query. Am I on a right track? Is my code correct to get the result I want?

<?php
$con = mysql_connect("localhost","root","");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("test3", $con);

    $start = microtime(TRUE);
    $result = mysql_query("SELECT * FROM `test`
    ORDER BY `test`.`test2` DESC
    LIMIT 0,100");

echo "

ID
test1
test2
test3
test4

";

while($row = mysql_fetch_array($result))
  {
  echo "
";
  echo "" . $row['ID'] . "	";
  echo "" . $row['test1'] . "	";
  echo "" . $row['test2'] . "	";
  echo "" . $row['test3'] . "	";
  echo "" . $row['test4'] . "	";
  echo "
";
  }
echo "
";

$end = microtime(TRUE);

$sqlTime = $end - $start;

mysql_close($con);
echo $sqlTime
?>


texts: N rotations of an array, either left or right, and then printing the result

texts:
Disclaimer, I'm new to OOP, but have experience in haskell and javascript.

Essentially, the challenge was to create a program which would shift an array a given amount of times to the left and then print the result.

I've tried to make this more extendable by allowing the option to shift to the right.

My code is

#include <iostream>
#include <vector>

using namespace std;

vector<int> rotate(vector<int> myVector, int direction, int count);
vector<int> rotate(vector<int> myVector, int direction);
void print(vector<int> rotatedVector);

void print(vector<int> rotatedVector){
    for(int i = 0; i < rotatedVector.size(); i++){
        cout << rotatedVector[i] << endl;
    }
}

vector<int> rotate(vector<int> myVector, int direction, int count){

    while(count > 0){
        myVector = rotate( myVector,  direction); // should I create a new variable, or just overwrite myVector each time?
        --count;
    }

    return myVector;
}

vector<int> rotate(vector<int> myVector, int direction){

    const int length = myVector.size();

    vector<int> rotatedVector(length);

    for(int i = 0; i < myVector.size(); i++){
        rotatedVector.at(i) = myVector.at((length+i-direction)%length);
    }

    return rotatedVector;
}

int main(){

    // Array to rotate
    int arr[5] = {1,2,3,4,5};

    // Times to rotate
    const int count = 2;

    // Creating a vector object out of array
    // Should I have worked with the array given?
    int n = sizeof(arr) / sizeof(arr[0]);
    vector<int> myVector(arr, arr + n);

    enum direction  {left = -1, right = 1}; // should this be global?

    myVector = rotate(myVector, left, count);

    print(myVector);

    // Could potentially turn vector back into array?

    return 0 ;
}

My design questions are...

Is this extendable enough, how could it be made more so?
Should the enums be made global?
Should I have used multiple
functions instead of using enums to make the rotation functions
generic? (e.g a right rotation function, and a left one)
Should I have kept with the array, instead of creating a vector from it?
Was overloading the function necessary?

The most important thing I would like to clarify from this review, is the concept of "state" in these types of programming puzzles (done in C++/OOP)

The line which overwrites the vector is...

myVector = rotate( myVector,  direction);

Is it better form to perhaps implement something like...

myVector.rotate(direction);

and thus action on the same object each time? (and if so why)

When would I use one over the other?

In my head, I feel as though it would be best to make the vector immutable and keep creating a new one each time, but am unsure and slightly confused about which one to use.


texts: Find two integers with the largest sum within a budget (breaking ties by smallest difference)

texts:
The algorithm finds a number pair that is as close to budget as possible, and if there are more pairs with same value, the pair with the least difference shall be given out. My algorithm works correctly, but is far too slow. Do you have ideas to improve it?

limit = highest value within budget atm,
i = smaller number of pair,
j = bigger number of pair

long limit = 0;
long i = 0, j = 0;
Arrays.sort(preis);

for (int a = 0; a < preis.length; a++) {
    for (int b = a + 1; b < preis.length; b++) {
        if (preis[a] + preis[b] > limit && preis[a] + preis[b] <= budget) {
            limit = preis[a] + preis[b];
            i = preis[a];
            j = preis[b];
        } else if (preis[a] + preis[b] == limit) {
            if (preis[a] > i) {
                i = preis[a];
                j = preis[b];
            }
        }
    }
}

I'm using Java 8.


texts: Multiple search filter like the one in freshdesk

texts:
I have requirement to apply multiple filters on database. I will have multiple conditions in the front end where the user can select the conditions he wants to filter with and then see the output. This is similar to the filter that Freshdesk has or for instance similar to many ecommerece sites.

This is my CoffeeScript file:

read = ->
$("#payment_status_filter :checkbox").click ->
    collect_data()
$("#status_filter :checkbox").click ->
    collect_data()

collect_data = ->
    status_array = []
    if $("#status_filter :checkbox").is(":checked")
        console.log("####*******status filter##########@@@@@@")
        $("#status_filter :checked").each ->
            status_array.push $(this).val()
        console.log(status_array)
    payment_status_array = []
    if $("#payment_status_filter :checkbox").is(":checked")
        $("#payment_status_filter :checked").each ->
            console.log("*****PAYMENT STATUS**********")
            payment_status_array.push $(this).val()
            console.log(payment_status_array)
    ajax_call(payment_status_array,status_array)

ajax_call= (payment_status,status) ->
    $.ajax(
        type: "GET"
        url: "/admin/filter_request"
        format: 'js'
        dataType: "script"
        data:
            payment_status: payment_status
            status: status
    ).done (data) ->
        console.log data
        $(".request_table_span").html data
        return

$(document).ready read
$(document).on "page:load", read

What I am doing above is that when the user clicks a checkbox for a payment_status conditions say "Paid" or "Unpaid" then it will fire a ajax request to a controller which will respond with a result. I have written such that when the requisite condition is clicked all the conditions in the whole page will be collected and sent along because more than one filter can be applied at the same time.

The following is my controller code:

def filter_request
    Rails.logger.info params
    @requests = Request.all
    @requests = @requests.where(payment_status: params[:payment_status]) if params[:payment_status]
    @requests = @requests.where(status: params[:status]) if params[:status]
    respond_to do |format|
       format.js
    end
end

The above approach seems not very good when the requirement has many filters, especially the controller part. How do I go about this? Any better approaches?


texts:
I am a beginner in python. This is the Nested Lists problem from HaackerRank.

  Given the names and grades for each student in a Physics class of N
  students, store them in a nested list and print the name(s) of any
  student(s) having the second lowest grade.

  Note: If there are multiple students with the same grade, order their
  names alphabetically and print each name on a new line.

I want to improve my code with better functions available in python and I want to decrease lines of code.

if __name__ == '__main__':
    scorecard = []
    for _ in range(int(input())):
        name = input()
        score = float(input())
        scorecard.append([name, score])
    scorecard.sort(key = lambda x:x[1])
    names = []
    lowest_score = scorecard[0][1]
    second_lowest = 0
    for i in range(len(scorecard)):
        if scorecard[i][1] > lowest_score and second_lowest == 0:
            second_lowest = scorecard[i][1]

        if second_lowest != 0 and scorecard[i][1] == second_lowest:
            names.append(scorecard[i][0])

    names.sort()

    for name in names:
    print(name)


texts: Flattening a nested record to its leaves

texts:
Note, I discovered a bug after I posted this. The current implementation drops any fields that have an associative value, which is not the intended behavior.

I'm writing a Tamagotchi clone, and need to be able to save the game's state to the disk. I want to save the entire state since it contains data other than the pet data like settings. Since de/serializing nested records is a pain, I decided to "flatten the nested records to their leaves". By that I mean if I have a record representing the game settings:

(defrecord Sim-Settings [health-per-tick pain-per-tick hunger-per-tick])
(defrecord Question-Settings [pain-per-wrong food-per-right])

(defrecord Settings [sim-settings question-settings])

(def test-settings
  (->Settings
    (->Sim-Settings 1 1 1)
    (->Question-Settings 1 1)))

I want to flatten that to:

(flatten-to-leaves test-settings)

{:health-per-tick 1,
 :pain-per-tick 1,
 :hunger-per-tick 1,
 :pain-per-wrong 1,
 :food-per-right 1}

All of the intermediate keys (:sim-settings and question-settings) are removed.

After struggling for a couple hours, I finally managed to get something working, but it's not perfect. All the solutions to similar problems I could find used tree-seq, which I had never used before. It's a cool function, but I'm afraid I might be forcing its usage here.

(defn flatten-to-leaves [record]
  (into {}

    (filter
      ; ... and filter out the non-leaves.
      #(and (map-entry? %)
            (not (associative? (second %))))

      ; Turn the record into a list of nodes of the map...
      (tree-seq associative? (partial apply list) record))))

Parts of it are nice. I like how tree-seq basically just turned this into a filtering problem.

My main problem is with the filtering function though. It is, I hate to admit, a product of fiddling. It works in every test case I've thrown at it, but something about it seems off. I have a feeling it can be reduced to something simpler.

I appreciate any critique regarding this code.

If I flatten the entire state:

(defrecord Pet [satiation max-satiation health max-health])
(defrecord Question-Generator [operator-ranges])
(defrecord Sim-Settings [health-per-tick pain-per-tick hunger-per-tick])
(defrecord Question-Settings [pain-per-wrong food-per-right])
(defrecord Settings [sim-settings question-settings])

(defrecord Game-State [pet q-gen last-update settings])

I get something like:

{:max-satiation 100,
 :hunger-per-tick 0.00347,
 :pain-per-tick 0.00347,
 :satiation 100,
 :pain-per-wrong 2,
 :max-health 100,
 :health-per-tick 0.0075,
 :last-update "20170905T204200.285Z",
 :food-per-right 5,
 :health 100}


texts: Forking with PHP (4 different approaches)

texts:
I thought about three (now four) different ways how to execute forks with PHP.
What is the faster, maybe better solution and why?

PHP script included

foreach($tasks as $task) {
    $pid = pcntl_fork();

    if($pid == -1) {
            exit("Error forking...\n");
    } else if($pid == 0) {

            include 'worker.php';
            exit();

    }
}

while(pcntl_waitpid(0, $status) != -1);`

PHP script executed through exec()

foreach($tasks as $task) {
    $pid = pcntl_fork();

    if($pid == -1) {
            exit("Error forking...\n");
    } else if($pid == 0) {

            exec('php worker.php '.$task);
            exit();

    }
}

while(pcntl_waitpid(0, $status) != -1);

PHP script executed as background command

foreach($tasks as $task) {

    $workers[] = exec('php worker.php '.$task.' &  echo $!');

}

do {
    foreach($workers as $idx => $pid) {
            if(!posix_getpgid($pid)) {
                    unset($workers[$idx]);
            }
    }
} while(!empty($workers));

(additional) 4. Using Gearman

worker.php can open database connections, files, etc ...

Any good explanation would be much appreciated.


texts:
This code below is for one of my scripts that I am trying to automate. I am dealing with the rows and all the data that is in those rows. What I am trying to do is make this look neater and maybe adding some different variables to make it look decent.

Foreach ($row in $csv) {
If ($row.Type0 -eq 'Domain') {
  $row."Unique Account Name" = "$($row.Domain0) - $($row.Account0)"
If ($row."Unique Account Name" -in @('ACCOUNTS - DODSCAN'.'ACCOUNTS - Domain Admins','ACCOUNTS - LADM_WS_Admins','ACCOUNTS - Tech Enterprise'))
        {$row."Excluded" = "True"}
    Else {$row."Excluded" = "False"}
 }
Else {
    $row."Unique Account Name" = "$($row.Netbios_name0) - $($row.Account0)"
    If ($row."Account0" -in @('esrxadm1n_esi','#Update','medco_tech','medco_admin'))
         {$row."Excluded" = "True"}
  Else {$row."Excluded" = "False"}
}


texts:
I am working on a fluent interface for exception handling.
Here's how it looks :

On<NullReferenceException>()
                    .First.LogTo("errors")
                    .Then.TranslateTo("null object");

            On<FileNotFoundException>()
                    .First.Translate(excpetion => excpetion.Message)
                    .Then.LogTo("errors");

            On<InvalidOperationException>()
                    .If(excpetion => excpetion.Message.Contains("This is a test"))
                    .First.DoSomethingElse(exception => Console.WriteLine(exception.Message));

            On<ArgumentException>().Ignore();

Do you think it's as fluent as it should be ? can I make it better ? any suggestions ?


texts:
I'm trying to create a generic class for decorator pattern.

I successfully did it with the example code by metaprogramming:

#include <iostream>

struct Action1 { };
struct Action2 { };

class Classe
{
public:
  // Default template.
  template<class U, class ...Args>
  auto go(Args ...args)
  {
    //static_assert(false);
  }
};

// Action 1.
template<>
auto Classe::go<Action1>()
{
  std::cout << "coucouGo1" << std::endl;
}

// Action 2.
template<>
auto Classe::go<Action2>(int i)
{
  std::cout << "coucouGo2 : " << i << std::endl;
  return i;
}

template <class T>
class Decorator
{
public:
  template<class U, class... Args>
  auto go(Args ...args)
  {
    std::cout << "coucouDecorator" << std::endl;
    return classe.template go<U>(args...);
  }
private:
  T classe;
};

class DecoreClasse : public Decorator<Classe>
{
};

int main()
{
  DecoreClasse c;
  c.go<Action1>();
  c.go<Action2>(2);
}

There is different functions "Action" and the pattern template decorator add a "coucouDecorator" before all call.

But the thing I don't like is the "auto" return type.

How can I replace auto to int or char in template specialization. I know I can do

struct Action1 { typedef retval int };
struct Action2 { typedef retval char };

template<>
Action1::retval Classe::go<Action1>()

and add a class template to the decorator

  template<class U, class T, class... Args>
  T go(Args ...args)
  {

but I prefer not to add return type in the struct.

Do you have a better idea ? Sometimes I'm not very understandable in English so do not hesitate to ask question.