texts: A program that expands a list of maps and chooses a random element

texts:
This is the essence of chapter 3 of "Clojure for the Brave and True".
This program is about completing the list asym-hobbit-body-parts by adding a given number of elements called "0-<name>" "1-<name>" and so on for every element in asym-hobbit-body-parts that starts with "left" and subsequently choosing a random body part to hit.
This contains code from the book which I rewrote from memory after finishing chapter 3. (And I mixed it with what I learned on the official homepage)

I am very curious what a clean version of this would look like.

(ns clojure-noob.core
  (:gen-class)
  (:require [clojure.string :as str] ))

(def asym-hobbit-body-parts [{:name "head" :size 3}
                             {:name "left-eye" :size 1}
                             {:name "left-ear" :size 1}
                             {:name "mouth" :size 1}
                             {:name "nose" :size 1}
                             {:name "neck" :size 2}
                             {:name "left-shoulder" :size 3}
                             {:name "left-upper-arm" :size 3}
                             {:name "chest" :size 10}
                             {:name "back" :size 10}
                             {:name "left-forearm" :size 3}
                             {:name "abdomen" :size 6}
                             {:name "left-kidney" :size 1}
                             {:name "left-hand" :size 2}
                             {:name "left-knee" :size 2}
                             {:name "left-thigh" :size 4}
                             {:name "left-lower-leg" :size 3}
                             {:name "left-achilles" :size 1}
                             {:name "left-foot" :size 2}])

(defn make-sym-parts [asym-set num]
  (reduce (fn [sink, {:keys [name size] :as body-part}]
           (if (str/starts-with? name "left-")
             (into sink (apply vector body-part
                         (for [i (range num)]
                           {:name (str/replace name #"^left" (str i))
                            :size size})))
             (conj sink body-part)))
           []
           asym-set))

(defn rand-part [parts]
  (let [size-sum (reduce + (map :size parts))
        thresh (rand size-sum)]
    (loop [[current & remaining] parts
           sum (:size current)]
      (if (> sum thresh)
        (:name current)
        (recur remaining (+ sum (:size (first remaining))))))))

(defn -main
  [& arg]
  (println (rand-part (make-sym-parts asym-hobbit-body-parts 3))))


texts: Map array of objects and apply condition

texts:
I'm mapping through an array of objects and applying conditions on each object by adding a new value according to the condition. I use map in ramda. Can I do this better?

events = map(el => {
  if (!['ts', 'sxi', 'ht', 'hd'].includes(el.value)) {
    el['extras'] = {type: 'cx', label: 'Es', name: 'es', options: ['cf']}
  }
  return el;
}, events);


texts:
One of many aspects of a project I am responsible for is generating an abbreviation, that is no more than n characters, for a given string. We use this in the organization for a couple things, and it only happens once for each "thing", so performance isn't hyper-critical.

An example is something like "The Main Test Company" — when asking for a 3-character abbreviation, I want to be able to generate a string like MTC. Now this would also be the same string as My Tiny Cat, but the idea is that a given company can be abbreviated and it can be done safely and effectively.

Also, if the abbreviations aren't large enough for the requested characters (say we request 4 characters from My Awesome Company) it should, for each abbreviation character, start adding characters to the total (so our example is MYAC).

I wrote the whole thing in F#, and it seems pretty readable and followable, I'm also including some test strings to verify functionality. Any comments are welcome.

let genAbbr ignoreList padding charCount (str : string) =
    if str.Length <= charCount then
        match padding with
        | Some c -> str |> Seq.append (String(c, charCount - str.Length)) |> Seq.toArray
        | None -> str.ToCharArray()
        |> Array.map Char.ToUpper
        |> String
    else
        let words =
            [|' '|]
            |> Array.append (str.ToCharArray())
            |> Array.fold (fun (acc, cs) c ->
                match c |> Char.IsUpper, c = ' ', cs with
                | true, _, [] -> (acc, [c])
                | true, _, cs -> (cs::acc, [c])
                | _, true, [] -> (acc, [])
                | _, true, cs -> (cs::acc, [])
                | _, _, cs -> (acc, c::cs)) ([], [])
            |> fst
            |> Array.ofList
            |> Array.map (Array.ofList >> Array.rev >> String)
            |> Array.rev
            |> Array.map (fun s -> s.ToCharArray())
        let ignoreWords = words |> Array.filter (fun w -> ignoreList |> Array.contains ((w |> String).ToLower()) |> not)
        let abbrCs =
            if ignoreWords |> Array.length >= charCount then ignoreWords |> Array.map Seq.head
            else if words |> Array.length >= charCount then words |> Array.map Seq.head
            else
                let firstCaps = words |> Array.map (fun s -> if s.Length > charCount then s.[0..charCount] else s) |> Array.length
                printfn "%A %A %A" ignoreWords words firstCaps
                words
                |> Array.fold (fun (acc, r) w ->
                    if w.Length > r then (w.[0..(r - 1)]::acc, 1)
                    else (w::acc, r - (w.Length - 1))) ([], charCount - firstCaps + 1)
                |> fst
                |> Array.ofList
                |> Array.rev
                |> Array.concat
                |> Array.map Char.ToUpper
        abbrCs |> Array.take charCount |> String

And lastly, some POC's:

["The Main Test Company"; "Main Test Company"; "The Main Company"; "The Company"; "Company"; "MainCompany"; "The MainCompany"; "MainTestCompany"; "SomeRX"; "SomeCompanyT"]
|> List.map (genAbbr [|"the"|] None 3)
// Should be ["MTC"; "MTC"; "TMC"; "THC"; "COM"; "MAC"; "TMC"; "MTC"; "SRX"; "SCT"]

Thanks for any commentary, and I look forward to this being brutally decimated. :)


texts:
Can you please tell me if there is a better way to do this?

people = {'123456':{'first': 'Bob', 'last':'Smith'},
          '2345343': {'first': 'Jim', 'last': 'Smith'}}

names = list()
first_names= set()
last_names = set()
for device in people:
    names.append(device)
    first_names.add(people[device]['first'])
    last_names.add(people[device]['last'])

I want to get a list of IDs, and sets of first and last Names. I know this code will work, but can I improve this?


texts:
Purpose

I came across this relatively simple question on HackerRank regarding finding missing values across two Lists. I took a fairly straight-forward approach, but is there a "better" / "slicker" way of implementing a solution?

Task

Strategy

Iterate throughList with complete data.
If Integer is in List with incomplete data, remove Integer from both Lists. Else, add Integer to a TreeSet of all missing values.

Implementation

public class MissingNumbersImpl implements MissingNumbers {
    @Override
    public Set<Integer> identifyMissingNumbers(final List<Integer> all, final List<Integer> incomplete) {
        if (all.size() <= incomplete.size()) {
            throw new IllegalArgumentException("list containing all numbers must have a size greater than list not containing all numbers");
        }

        final Set<Integer> missingNumbers = new TreeSet<>();

        final Iterator<Integer> iterator = all.iterator();
        while (iterator.hasNext()) {
            final Integer next = iterator.next();
            if (incomplete.contains(next)) {
                incomplete.remove(next);
                iterator.remove();
            } else {
                missingNumbers.add(next);
            }
        }

        return missingNumbers;
    }
}


texts: Converts data in a HashMap to a custom object

texts:
I have a HashMap and I want to convert data in it to a Response object, but I do not find it clean and optimized. Is there a better way to achieve this?

class Converter{

   public static void main(String[] args) {

      Map<String, Long> map = new HashMap<String, Long>();
      map.put("111", 80) // first
      map.put("1A9|ppp", 190) // second
      map.put("98U|6765", 900) // third
      map.put("999|aa|local", 95) // fourth

      List<Response> responses = new ArrayList<>();
      for(String key : map.keySet()){
        Response response = new Response();
        String[] str  = key.split("\\|");
        response.id = str[0] //id is always present in key i.e 111, 1A9, 98U,999
        if(str.length == 2) {
             if(str.matches("-?\\d+(\\.\\d+)?");){ // check if is numeric
                  response.code = str[1]; // 6765
             }
             else{
                  response.city = str[1]; //ppp
             }
        }
         if(str.length == 3){
                  response.client = str[1]; //aa
                  response.type = str[2];   // local
         }
        response.qty = map.get[key];
        responses.add(response);
      }
   }
}

class Response{

String id;
String city;
Long code;
String client;
String type;
Long qty;
// getters and setters

}


texts: Get random direction based off of location and previous direction

texts:
I've recently implemented a Wilson's Algorithm for maze generation. This problem however could also be extended to things such as snake, or some other simple AIs.

The problem is as follows:

  Blue Node -> Previous nodes

  Red Node -> Current node

  Black Line -> Wall

  In this case, we can analyze each of the 4 possible directions: up,
  right, down and left.

  Up - Not available, since the last move was down (reversing itself)
  Right - Not available, since there is a wall directly to the right
  Down - Available
  Left - Available

  From here we can see that should it move down, then the same
  availability will occur. If it should move left: up, left and down
  would then be available.

The way I have implemented this is as follows:

private int nextDirection(final int i, final int j, final int rowLimit, final int columnLimit, final int previous) {
    boolean up = true;
    boolean right = true;
    boolean down = true;
    boolean left = true;
    if (i == 0) {
        up = false;
    } else if (i == rowLimit) {
        down = false;
    }
    if (j == 0) {
        left = false;
    } else if (j == columnLimit) {
        right = false;
    }
    switch (previous) {
        case DIRECTION_UP:
            down = false;
            break;
        case DIRECTION_DOWN:
            up = false;
            break;
        case DIRECTION_RIGHT:
            left = false;
            break;
        case DIRECTION_LEFT:
            right = false;
    }
    final ArrayList<Integer> list = new ArrayList<>(4);
    if (left) {
        list.add(DIRECTION_LEFT);
    }
    if (right) {
        list.add(DIRECTION_RIGHT);
    }
    if (down) {
        list.add(DIRECTION_DOWN);
    }
    if (up) {
        list.add(DIRECTION_UP);
    }
    return list.get(random.nextInt(list.size()));
}

Where:

i           - row of current node
j           - column of current node
rowLimit    - row count minus one
columnLimit - column count minus one
previous    - previous direction
random      - java.util.Random instance

Now, I highly doubt this is the most efficient solution. However it is the least - well - troublesome. The others I have used are just a large amount of if statements considering every possible case.

However, neither of these solutions - at least how I see them - are efficient enough. Due to this and what Knuth once said, I went for readability. The main problem is, this has become a bottleneck in the calculation speeds.

Question:

Is there a way to better calculate the available directions? And therefore a better way to select a random direction.

Sides notes:

DIRECTION_UP    = 0x01;
DIRECTION_RIGHT = 0x02;
DIRECTION_DOWN  = 0x04;
DIRECTION_LEFT  = 0x08;

These can be changed to whatever value needed.


texts:
Is this code Pythonic?

def emit_decorator(method, signal_name):
    def decorated(self, *args, **kwargs):
        retval = method(self, *args, **kwargs)
        getattr(self, signal_name).emit()
        return retval
    return decorated

class Model(base.Transformer, Node):
    """
    Transformer subclass that implements the Model of the Model-View-Controller
    paradigm.
    """
    def __init__(self, *args, **kwargs):
        super(Model, self).__init__(*args, **kwargs)

    modelChanged = pyqtSignal()

    def create_view(self, parent=None):
        return View(self, parent)

for x in ('importance_changed',
          'evidence_changed',
          ):
    setattr(Model, x,
            emit_decorator(getattr(Model, x), 'modelChanged'))

Final decorator code:

from functools import update_wrapper

def method_emit_decorator(signal_name):
    def method_decorator(method):
        def decorated(self, *args, **kwargs):
            retval = method(self, *args, **kwargs)
            getattr(self, signal_name).emit()
            return retval
        return update_wrapper(decorated, method)
    return method_decorator

def class_emit_decorator(signal_name_to_method_names_dict):
    def class_decorator(cls):
        retval = cls
        for signal_name, method_names in (
            signal_name_to_method_names_dict.items()):
            for method_name in method_names:
                method = method_emit_decorator(signal_name)(
                    getattr(cls, method_name))
                setattr(retval, method_name, method)
        return retval
    return class_decorator


texts: Create annotation to validate JWT in Spring controller instead of filter

texts:
I developed a Spring RESTful service that uses a JWT for authorization.
To the validity of this JWT, i used two different implementations.

Create a filter to intercept every request and validate request, if invalid then reject it.
Create a annotation to be used in controller methods, this approach is explained below.

The JWT contains user id which is used to identify authenticated user, but if i used a filter, i have to decode this JWT again in controller method, because of this problem i used second implementation.

The question is about annotation approach.

Is this a good implementation to JWT validation ?
How can i improve this code ?

Here's the code,

Annotation

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Authorize {
    String[] value();
}

Implementation of the annotation

public class MethodAccessResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return (parameter.getMethodAnnotation(Authorize.class) != null) && (parameter.getParameterName().equals("jwt"));
    }

    @Override
    public Object resolveArgument(
        MethodParameter parameter,
        ModelAndViewContainer mavContainer,
        NativeWebRequest webRequest,
        WebDataBinderFactory binderFactory
    ) throws Exception {
        String[] allowedUsers = parameter.getMethodAnnotation(Authorize.class).value();
        JwtProperties jwt = JwtUtil.validate(webRequest.getHeader("Authorization"));
        String currentUser = jwt.getScope().get(0);

        int no = 0;
        for (String allowedUser : allowedUsers) {
            if (!allowedUser.equals(currentUser)) {
                no++;
            }
        }

        if (no == allowedUsers.length) {
            throw new UnauthorizedAccessException("Un-authorized access", 0xd1561);
        } else {
            return jwt;
        }
    }
}

Controller method - where the annotation is used

@GetMapping(
        path = "/api/event/post",
        produces = MediaType.APPLICATION_JSON_VALUE
)
@Authorize(value = {UserSupport.USER, UserSupport.ADMIN, UserSupport.END_USER})
public ResponseEntity<?> getLiveLocations(
        HttpServletRequest request,
        JwtProperties jwt
) throws
        MongoException,
        ParseException,
        JwtException,
        UnsupportedEncodingException,
        ResourceNotFoundException,
        UnauthorizedAccessException {
    //do something
}

An Exception is thrown if token is invalid or the user role contains in token is not allowed to access particular URL.

If token is validated then user details will be injected to method parameter JwtProperties jwt.


texts:
I think it could have been designed with more object orientation. I don't like how one of my methods calls another from within the method, but I wasn't sure how to return the result because it is a loop.

Also is it ok to have all methods static, or should I be instantiating the classes?

If there is any other improvements please let me know, but these were my main concerns.

App.java:

public class App {

    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();

        Fibonacci.fibonacci();

        long endTime = System.currentTimeMillis();
        long totalTime = endTime - startTime;

        System.out.println("****************************************\n");
        System.out.println("Total Running Time: " + totalTime + "ms");
    }
}

Fibonacci.class:

public class Fibonacci {

    static void fibonacci() {
        long i = 0;
        long j = 1;
        long k = 0;
        while (i < 1E17) {
            k = i + j;
            i = j;
            j = k;
            Prime.prime(k);
        }
    }
}

Primes.java:

public class Prime {

    static void prime(long number) {

        boolean isPrime = false;

        long end = (long) (Math.sqrt(number) + 1);
        for (long i = 2; i <= end; i++) {
            if (number % i == 0) {
                isPrime = false;
                break;
            } else {
                isPrime = true;
            }
        }
        if (isPrime) {
            System.out.println(number);
        }
    }
}


texts:
I did a Goldbach's Conjecture exercise and got it to work. It's pretty slow though and I was wondering how I could optimize it.

number = int(input("Enter your number >> "))
print("\nCalculating...")
if number % 2 == 0: #Only even numbers
    primes = primenums(number) #returns all prime numbers <= input number
    addend1 = primes[0]
    addend2 = primes[0]

    while addend1 + addend2 != number:
        if primes[-1] == addend2:
            addend2 = primes[primes.index(addend1) + 1]
            addend1 = primes[primes.index(addend1) + 1]
        else:
            addend2 = primes[primes.index(addend2) + 1]

Right now, up to 10,000 the algorithm is pretty fast, but at 100,000 it takes about 3 seconds to finish. Is that just how it is or could I make it faster?


texts: Converting an input audio file to a monophonic FLAC file

texts:
I have the following method which basically converts an input audio file to a monophonic FLAC file.

Now I am getting Member has cyclomatic complexity of 21 (105%) message in Visual Studio, while I've taken care of improving it as in the beginning it was longer, now there's not much I can remove from it as it pretty much fulfills my needs.

Should I just ignore this warning ?

private static void Convert(string inputFile, string outputFile, IProgress<double> progress = null)
{
    if (inputFile == null) throw new ArgumentNullException("inputFile");
    if (outputFile == null) throw new ArgumentNullException("outputFile");
    int stream = 0;
    int mixer = 0;
    try
    {
        stream = Bass.BASS_StreamCreateFile(inputFile, 0, 0,
            BASSFlag.BASS_STREAM_DECODE | BASSFlag.BASS_SAMPLE_FLOAT | BASSFlag.BASS_STREAM_PRESCAN);
        if (stream == 0) throw new BassException("Could not create stream");
        var info = Bass.BASS_ChannelGetInfo(stream);
        if (info == null) throw new BassException("Could not retrieve stream info");
        var freq = info.freq;
        mixer = BassMix.BASS_Mixer_StreamCreate(freq, 1,
            BASSFlag.BASS_MIXER_END | BASSFlag.BASS_SAMPLE_FLOAT | BASSFlag.BASS_STREAM_DECODE);
        if (mixer == 0) throw new BassException("Could not create mixer");
        bool addChannel = BassMix.BASS_Mixer_StreamAddChannel(mixer, stream, BASSFlag.BASS_MIXER_NORAMPIN);
        if (!addChannel) throw new BassException("Could not add stream to mixer");
        long getLength = Bass.BASS_ChannelGetLength(stream);
        if (getLength == -1) throw new BassException("Could not get channel length");
        var encoder = new EncoderFLAC(mixer)
        {
            Force16Bit = true,
            FLAC_Verify = true,
            OutputFile = outputFile
        };
        if (!encoder.Start(null, IntPtr.Zero, false))
            throw new InvalidOperationException("Could not start encoder");
        const int samples = 65536;
        const int bytes = (samples * sizeof(float)) | (int)BASSData.BASS_DATA_FLOAT;
        var buffer = new float[samples];
        long bytesRead = 0;
        while (Bass.BASS_ChannelIsActive(mixer) == BASSActive.BASS_ACTIVE_PLAYING)
        {
            int getData = Bass.BASS_ChannelGetData(mixer, buffer, bytes);
            bytesRead += getData;
            if (progress != null) progress.Report(1.0d / getLength * bytesRead);
        }
        encoder.Stop();
        if (getLength / sizeof(short) != bytesRead)
            throw new InvalidOperationException("Output length not equal to input length");
    }
    catch (Exception ex)
    {
        throw new InvalidOperationException("Conversion failed", ex);
    }
    finally
    {
        if (stream != 0) Bass.BASS_StreamFree(stream);
        if (mixer != 0) Bass.BASS_StreamFree(mixer);
    }
}


texts:
I want to implement basic audio functions like play, stop and pause. I have stuffed all the code inside onCreate method. Is this best practise to follow?

public class MainActivity extends Activity {
        Button start,pause,stop;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            start=(Button)findViewById(R.id.button1);
            pause=(Button)findViewById(R.id.button2);
            stop=(Button)findViewById(R.id.button3);
            //creating media player
            final MediaPlayer mp=new MediaPlayer();
            try{
                    //you can change the path, here path is external directory(e.g. sdcard) /Music/maine.mp3
            mp.setDataSource(Environment.getExternalStorageDirectory().getPath()+"/Music/maine.mp3");

            mp.prepare();
            }catch(Exception e){e.printStackTrace();}

            start.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    mp.start();
                }
            });
            pause.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    mp.pause();
                }
            });
            stop.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    mp.stop();
                }
            });
        }
    }


texts: PHP function to access a database and return json

texts:
<?php

include_once('../dbInfo.php');

function getReport($user_table) {
    $tables = array(
        "day"        => "p_day",
        "month"      => "p_month"
        ... etc. .....
    );

    $table = $tables[$user_table];

    if(!$table) {
        die(json_encode(array("error" => "bad table name")));
    }

    $con = getConnection(); // getConnection is in '../dbInfo.php'

    $query = "select * from " . $table;
    $res = mysql_query($query, $con);

    if(!$res) {
        die(json_encode(array("error" => "no results from table")));
    }

    $fields_num = mysql_num_fields($res);
    $fields = array();
    for($i=0; $i < $fields_num; $i++) {
        $field = mysql_fetch_field($res);
        $fields[$i] = $field->name;
    }

    $i = 0;
    while($row = mysql_fetch_array($res)) {
        $rows[$i] = $row;
        $i++;
    }
    $json = array("rows" => $rows, "headers" => $fields);

    $jsontext = json_encode($json);
    return $jsontext;
}

?>

What this code is doing:

access the database, selecting rows from a table, and returning them as a serialized json object
a table name is looked up in $tables -- the keys are acceptable user input, the values are actual table/view names in the database
data is selected from the table
the data is put into a big hash
the hash is serialized as a json string and returned

Specific issues I'm concerned about:

security -- is my DB connection info safe?  This file is in the root directory of public content, so dbiInfo.php, with the database connection information, is not publicly accessible (I think)
security -- am I open to SQL injection attacks?  I build a SQL query with string concatenation
security -- $user_table is untrusted input; is it safe?  It's only used as a key to look up trusted input ...
error handling -- have I dealt with all error conditions
there are lots of versions of PHP functions -- am I using the right ones?

General issues:

following conventions
quality/readability/comments

Edit:  the data is publicly available -- I'm worried about somebody getting more than read access to one of the listed tables, or any access to any other table in the DB.


texts:
I wrote cat program in x64 FASM and I would like to know if there is anything that can be improved.

This implementation of cat supports:

Reading from stdin.
Multiple arguments.

I checked few cases and program behaves exactly like original cat command.

Is there anything I could do to improve performance of this program? I compared it to original cat and my program is around 200ms slower on 512MB file.

Code:

format ELF64 executable 3
entry start

BUFSIZE equ 1048576

segment readable writeable
    fd dq 0
    buf rb BUFSIZE

segment readable executable

start:
    mov rbx, 1
    cmp [rsp], rbx
    je read
open:
    xor rsi, rsi            ;fd=open(pathname,flags)
    mov rdi, [rsp+rbx*8+8]
    mov rax, 2
    syscall
    mov [fd], rax
read:
    mov rdx, BUFSIZE        ;bytes_read=read(fd,buf,BUFSIZE)
    mov rsi, buf
    mov rdi, [fd]
    mov rax, 0
    syscall
write:
    mov rdx, rax            ;write(STDOUT_FILENO,buf,bytes_read)
    mov rsi, buf
    mov rdi, 1
    mov rax, 1
    syscall
    test rdx, rdx           ;if(bytes_read!=0) goto read
    jnz read
close:
    mov rdi, [fd]           ;close(fd)
    mov rax, 3
    syscall
    inc rbx
    cmp rbx, [rsp]          ;if(rbx<argc)
    jb open
exit:
    xor rdi, rdi
    mov rax, 60
    syscall


texts:
I'm creating an online calculator to get the average grade of different tests my students take. I wonder if you see any problems in the following code or any way to improve it:

document.getElementById('calculator').addEventListener('click', function() {
  var physicsTests = document.getElementById('physics').getElementsByTagName('input'),
    historyTests = document.getElementById('history').getElementsByTagName('input'),
    physicsTestsCount = 0,
    historyTestsCount = 0,
    physicsAverage = document.getElementById('physicsAverage'),
    historyAverage = document.getElementById('historyAverage'),
    i;
  for (i = 0; i < physicsTests.length; i++) {
    if (physicsTests[i].value) {
      physicsTestsCount++;
    }
    if (!physicsTestsCount) {
      physicsAverage.value = 'No assessment made!';
    } else {
      physicsAverage.value = (Number(physicsTests[0].value) + Number(physicsTests[1].value) + Number(physicsTests[2].value)) / physicsTestsCount;
    }
  }
  for (i = 0; i < historyTests.length; i++) {
    if (historyTests[i].value) {
      historyTestsCount++;
    }
    if (!historyTestsCount) {
      historyAverage.value = 'No assessment made!';
    } else {
      historyAverage.value = (Number(historyTests[0].value) + Number(historyTests[1].value) + Number(historyTests[2].value)) / historyTestsCount;
    }
  }
});
<form>

    Physics:
    <input type="number">
    <input type="number">
    <input type="number">
    <output id="physicsAverage"></output>

    History:
    <input type="number">
    <input type="number">
    <input type="number">
    <output id="historyAverage"></output>

  <button type="button" id="calculator">Calculate</button>
</form>


texts: Adding and subtracting Matrices based on condition

texts:
procedure E(n, m: integer; A, B: tMatrix; var C: tMatrix);
var i, j: integer;
begin
  for i:=1 to n do
    for j:=1 to m do begin
      if i<=j then C[i,j]:=A[i,j] + B[i,j] else C[i,j]:=A[i,j] - B[i,j];
    end;
end;

Input: three matrix. Output: new matrix which created by addition or subtraction of two elements of two matrix depending on conditions


texts: Global site settings middleware for Slim Framework 3

texts:
I have created this middleware code for slim. I just want to know that is this right way to store site settings globally. so, I can use where ever I want. What do you think about my class structure apart from invoke (which is slim's own feature) what do you think about foreach and setting the data. I'm trying to learn and find good practice. thanks.

this is the middleware

    namespace entity;

    use PDO;
    use Psr\Http\Message\ServerRequestInterface;
    use Psr\Http\Message\ResponseInterface;

    class SiteSettings {

      public function __construct( $app ) {
        $this->pdo =  $app->getContainer()['pdo'];
      }
      public function __invoke( $request, $response, $next ) {
        if( $this->getSettings() !== false ) {
          foreach ( $this->getSettings()  as $row )
          $response = $next($request->withAttribute($row['setting'], $row['value']), $response );
        }
        return $response;
      }
      protected function getSettings() {
        $sql = "SELECT setting, value, description FROM site_settings";
        try {
          $query = $this->pdo->prepare( $sql );
          if ( $query->execute() ) {
            return $query->fetchAll(PDO::FETCH_ASSOC);
          }
          return false;
        } catch ( PDOException $pe ) {
          return false;
        }
      }
    }

added to all routes

$app->add( new entity\SiteSettings( $app ) );

and able to use it like this

    $app->get('/en/admin', function ($request, $response, $args) {
        // Sample log message
        $this->logger->info("Tes '/' route");
        echo $request->getAttribute('site_name');

     });

and this is the table

     CREATE TABLE `site_settings` (
        `setting` VARCHAR(250) NOT NULL DEFAULT '' COLLATE 'utf8_unicode_ci',
        `value` VARCHAR(250) NULL DEFAULT NULL COLLATE 'utf8_unicode_ci',
        `description` TINYTEXT NULL COLLATE 'utf8_unicode_ci',
        PRIMARY KEY (`setting`)
     )
     COLLATE='utf8_unicode_ci'
     ENGINE=InnoDB
     ;


texts: Dynamic Allocation and Reallocation of Memory

texts:
This is a code snippet of a larger program. I tried to simplify it as much as possible.

This code identifies certain particles and stores them in a list which corresponds to a certain processor.
Besides that I count the number of particles per processor that are already in the list.
After the work is done I want to use the message-passing system MPI to send the particles in the list to other processors (not shown here).

I would like to know:

Is the process of allocation and deallocation of memory correct?
Is the code robust?
Can this be simplified?

Code:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define DIM 2

typedef struct{
    double m;
    double x[DIM];
    double v[DIM];
    int id;
} Particle;

typedef struct{
    double **list;
    int *counter;
} ParticleList;

void generateParticles(Particle *p, int N);
void buildList(Particle *p, ParticleList *plist, int numprocs, int N);

int main() {
    time_t t;
    srand((unsigned)time(&t));

    // Generate data, print data
    int N = 50;
    Particle *p = (Particle*)malloc(N*sizeof(*p));
    generateParticles(p, N);
    for(int i=0; i<N; i++){
        printf("id: %d m: %lf x: %lf %lf v: %lf %lf\n", p[i].id, p[i].m, p[i].x[0], p[i].x[1], p[i].v[0], p[i].v[1]);
    }

    // Fill lists of every processor
    int numprocs = 4;
    ParticleList plist;
    plist.list = malloc(sizeof(double*)*numprocs);
    for(int k=0; k<numprocs; k++)
        plist.list[k] = malloc(sizeof(double)*1);
    plist.counter = calloc(numprocs, sizeof(int));
    buildList(p, &plist, numprocs, N);

    for(int k=0; k<numprocs; k++){
        printf("Processor %d Particles in list %d\n", k, plist.counter[k]);
        for(int c=0; c<(DIM*plist.counter[k]); c++){
            printf("%lf ", plist.list[k][c]);
        }
        printf("\n");
    }

    // deallocate memory
    for(int k=0; k<numprocs; k++){
        free(plist.list[k]);
    }
    free(plist.list);
    free(plist.counter);
    free(p);
    return 0;
}

void buildList(Particle *p, ParticleList *plist, int numprocs, int N){
    for(int k=0; k<numprocs; k++){
        for(int i=0; i<N; i++){
            printf("k %d, i %d\n", k, i);
            if(rand()%10 < 5){
                plist->counter[k] = plist->counter[k] + 1;
                plist->list[k] = realloc(plist->list[k], (DIM*plist->counter[k])*sizeof(plist->list[k][0]));
                int d=0;
                for(int j=(plist->counter[k] - 1)*DIM; j < (plist->counter[k] * DIM); j++){
                    plist->list[k][j] = p[i].x[d];
                    d++;
                }
            }
        }
    }
}

double frand(){
    return (double)rand() / (double)RAND_MAX;
}

void generateParticles(Particle *p, int N){
    for(int i=0; i<N; i++){
        for(int d=0; d<DIM; d++){
            p[i].x[d] = frand();
            p[i].v[d] = frand();
        }
        p[i].m = frand();
        p[i].id = i;
    }
}


texts:
For part of a project, I was given this directive:

  The grep command will take an exact string and an exact filename as
  the 2 arguments and you will need to search through the filename for
  the given string and display the "line" and "line number" the string
  resides in.
  Example output would be:

# grep bob FileWithBob
12 and then bob picked up the phone and called jane
24 even though they knew that bobby was not going to show up

Testing seems to give identical results to the actual grep program for everything I've tried:

$ ./my_grep "test" grep.c
1:// test
2:// multi-line test

$ grep -n "test" grep.c
1:// test
2:// multi-line test

grep.c:

// test
// multi-line test
#define _GNU_SOURCE 1       // for getline()
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <regex.h>
#include <unistd.h>
#include <sys/types.h>

#ifndef streq
#define streq(x, y) (strcmp((x), (y)) == 0)
#endif

#define MSGBUFSIZE  512

regex_t pattern;

int compile_pattern(const char *pat)
{
    int flags = REG_NOSUB;
    char error[MSGBUFSIZE] = "";

    int ret = regcomp(&pattern, pat, flags);
    if (ret)
    {
        regerror(ret, &pattern, error, sizeof(error));
        fprintf(stderr, "pattern `%s`: %s\n", pat, error);
        return ret;
    }

    return 0;
}

// read lines of text and match against the pattern
int process(FILE *fp)
{
    char *buf = NULL;
    size_t size = 0;
    char error[MSGBUFSIZE] = "";
    int ret = 0;

    for (int i = 1; getline(&buf, &size, fp) != -1; i++)
    {
        ret = regexec(&pattern, buf, 0, NULL, 0);
        if (ret)
        {
            if (ret != REG_NOMATCH)
            {
                regerror(ret, &pattern, error, sizeof(error));
                fprintf(stderr, "%s\n", error);
                free(buf);
                return ret;
            }
        }
        else
            printf("%d:%s", i, buf);
    }

    free(buf);
    return 0;
}

void usage(char* prog_name)
{
    fprintf(stderr, "usage: %s [-i] [-E] pattern [ files ... ]\n", prog_name);
    exit(1);
}

int main(int argc, char **argv)
{
    FILE *fp = NULL;

    if (1 == argc)
        usage(argv[0]);

    int err = compile_pattern(argv[optind]);
    if (err)
        return err;
    else
        optind++;

    if (optind == argc) // no files, default to stdin
        process(stdin);
    else {
        for (int i = optind; i < argc; i++)
        {
            if (streq(argv[i], "-"))
                process(stdin);
            else if ((fp = fopen(argv[i], "r")))
            {
                process(fp);
                fclose(fp);
            }
            else
            {
                fprintf(stderr, "%s: could not open: %s\n", argv[i], strerror(errno));
                err = -1;
            }
        }
    }

    regfree(&pattern);
    return err;
}

Any suggestions?


texts: C# How to check if we've 'had' values from a method without having to re-call the method

texts:
Currently I'm saving the values, gotten from a method, to a variable and using them later on.

This is the example code of how I do it:

var events = class.GetEvents();

if(events.Length > 0)
{
     foreach(var event in events)
     {
        // do something
     }
}
else
{
     // No events
     Console.Log("No Events");
}

But actually, What I'd like to achieve is something more like this:

foreach(var event in class.GetEvents()) // <-- If none, I'd like to know.
{
      // do something
}

However, I still need to log that there weren't any results. I'd have to do a check, and re-call the method to see if there are any results.. OR i++ in my loop, and if that's a 0 => log.

Is there a simpler way to do this?


texts: Using quickCheck for "99 Haskell problems" - problem 1

texts:
I'm working on learning Haskell, and I've implemented a solution to the first of the 99 Haskell problems. Here is my code:

import Data.Int
import Test.QuickCheck

myLast :: [a] -> Either String a
myLast [] = Left "Empty lists have no last element."
myLast xs = Right ((reverse xs) !! 0)

testMyLast :: [Int] -> Bool
testMyLast xs =
    case myLast xs of
        Left err -> null xs
        Right x -> x == last xs

main = quickCheck testMyLast

Now, I realize that my implementation of myLast is not the most efficient one. I'm not particularly interested in that type of feedback. Rather, I'm more curious about whether or not I'm following reasonable Haskell code style practices (the naming of things, indentation, etc.), as well as how I'm dealing with errors.

It's my understanding that using Either (or Maybe) when an error occurs is, in general, to be preferred over error "...", since dealing with exceptions is really only cleanly done in an IO context. Is my understanding correct? If it is, why do basic library functions (like List's last, for example) use error instead?


texts: jQuery Plugin Review - wrapper for jQuery UI's tabs

texts:
This is a jQuery plug-in I've created that relies on jQuery UI's tabs plug-in. It adds some framework specific logic when setting up tabs:

Fixes a bug in jQuery that appears when an id/class contains a "."
Manages the tab state using a framework specific cookie API (does not use the jQuery cookie plugin)
Exposes a couple of options for transition behavior

I'd love to get some suggestions on how to improve this, as it'll be used widely in the framework.

(function ($) {
    $.fn.dnnTabs = function (options) {
        var opts = $.extend({}, $.fn.dnnTabs.defaultOptions, options),
            $wrap = this;

        $(document).ready(function () {
            // Patch for Period in IDs (jQuery bug)
            $.ui.tabs.prototype._sanitizeSelector = function (hash) {
                // we need this because an id may contain a ":" or a '.'
                return hash.replace(/:/g, "\\:").replace(/\./g, "\\\.");
            };

            var id = 'dnnTabs-' + $wrap.selector.replace('#', '').replace('.', '');
            if (opts.selected === -1) {
                var tabCookie = dnn.dom.getCookie(id);
                if (tabCookie) {
                    opts.selected = tabCookie;
                }
                if (opts.selected === -1) {
                    opts.selected = 0;
                }
            }

            $wrap.tabs({
                show: function (event, ui) {
                    dnn.dom.setCookie(id, ui.index, 1, '/', '', false);
                },
                selected: opts.selected,
                fx: {
                    opacity: opts.opacity,
                    duration: opts.duration
                }
            });
        });

        return $wrap;
    };

    $.fn.dnnTabs.defaultOptions = {
        opacity: 'toggle',
        duration: 'fast',
        selected: -1
    };

})(jQuery);


texts:
I am working on building an UndoManager in C#. The concept is to store events and property changes in a Stack<Action<T>> instance. I believe it is working, but I am also looking for peer review.

What can I improve?  Do you see any bugs?

public abstract class UndoManager<T>
{
    /// <summary>
    /// Adds an Event to Stack
    /// </summary>
    /// <param name="undoOperation"></param>
    protected abstract void Add(Action<T> undoOperation);

    /// <summary>
    /// Returns the size of the stack
    /// </summary>
    /// <returns></returns>
    public abstract int Size();
    /// <summary>
    /// Holds all the Events in a stack
    /// </summary>
    protected Stack<Action<T>> MyUndoOperations { get; set; }
    protected Stack<Action<T>> MyRedoOperations { get; set; }

    /// <summary>
    /// Preforms the undo action. Pops the last event and gets a reference to the next event
    /// and fires the event
    /// </summary>
    public abstract void Undo();
    /// <summary>
    /// Preforms the Redo action.
    /// </summary>
    public abstract void Redo();

}

public class MyClass : UndoManager<MyClass>
{
    #region Getter and Setters
    private String myValue;
    public String MyValue
    {
        get { return this.myValue; }

        set
        {

            this.Add(x => x.myValue = value);// save the operation on the stack
            this.myValue = value;

        }
    }

    private String productName;
    public String ProductName
    {
        get { return productName; }

        set
        {
            this.Add(x => x.productName = value);// save the operation on the stack
            productName = value;
        }
    }
    #endregion

    /// <summary>
    /// Returns the size of the Action Event Stack
    /// </summary>
    /// <returns>Size of this.MyOperations</returns>
    public override int Size()
    {
        return this.MyUndoOperations.Count();
    }

    public MyClass()
    {

        this.MyUndoOperations = new Stack<Action<MyClass>>();
        this.MyRedoOperations = new Stack<Action<MyClass>>();
    }
    /// <summary>
    /// Pushes the last Action event on the Stack
    /// </summary>
    /// <param name="undoOperation">Last Action Event</param>
    protected override void Add(Action<MyClass> undoOperation)
    {
        //this.MyRedoOperations.Clear();
        this.MyUndoOperations.Push(undoOperation);
    }

    /// <summary>
    /// Preforms the undo action. Pops the last event and gets a reference to the next event
    /// and fires the event
    /// </summary>
    public override void Undo()
    {

        if (this.MyUndoOperations != null && this.MyUndoOperations.Any())
        {

            Action<MyClass> topAction = this.MyUndoOperations.Pop();// remove the very last event.
            this.MyRedoOperations.Push(topAction); // add to the redo stack

            if (this.MyUndoOperations.Any())
            {
                // get a reference (peek) to the last event
                Action<MyClass> lastAction = this.MyUndoOperations.Peek();
                lastAction(this);// fire event
                //this.Add(lastAction); // add to the undo stack
            }

        }

    }

    public override void Redo()
    {
        if (this.MyRedoOperations.Any())
        {

            Action<MyClass> lastAction = this.MyRedoOperations.Pop();
            lastAction(this);// fire event
            this.Add(lastAction);
        }

    }
}


texts: Korean word segmentation using frequency heuristic

texts:
This a continuation of a previous question. I want to thank Joe Wallis for his help with increasing the readability of my code. Although the changes made by Joe Wallis did increase the speed of the code, the speed improvements aren't enough for my purposes.

I'll reiterate the problem, but please feel free to look at the previous question. The algorithm uses a corpus to analyze a list of phrases, such that each phrase is split into constituent words in a way that maximizes its frequency score.

The corpus is represented as a list of Korean words and their frequencies (pretend that each letter represents a Korean character):

A 56
AB    7342
ABC   3
BC    116
C 5
CD    10
BCD   502
ABCD  23
D 132
DD    6

The list of phrases, or "wordlist", looks like this (ignore the numbers):

AAB       1123
DCDD  83

The output of the script would be:

Original    Pois        Makeup                    Freq_Max_Delta
AAB         A AB        [AB, 7342][A, 56]         7398
DCDD        D C DD      [D, 132][DD, 6][C, 5]     143

In the previous question, there are some sample inputs which I am using. The biggest problem is the size of the data sets. The corpus and wordlist have 1M+ entries in each file. It's currently taking on average 1-2 seconds to process each word in the wordlist, which in total will take 250 hours+ to process.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys, codecs, collections, operator, itertools
from argparse import ArgumentParser

sys.stdout = codecs.getwriter("utf8")(sys.stdout)
sys.stderr = codecs.getwriter("utf8")(sys.stderr)

def read_corpa(file_name):
    print 'Reading Corpa....'
    with codecs.open(file_name, 'r', 'UTF-8') as f:
        return {l[0]: int(l[-1]) for l in (line.rstrip().split('\t') for line in f)}

def read_words(file_name):
    with codecs.open(file_name, 'r', 'UTF-8') as f:
        for word in f:
            yield word.split('\t')[0]

def contains(small, big):
    small_ = len(small)
    for i in xrange(len(big) - small_ + 1):
        if big[i:i + small_] == small:
            return (i, i + small_)
    return None

def find_best(word, corpas):
    combos = {}
    for corpa, frequency in corpas.items():
        c = contains(corpa, word)

        if c:
            combos[word[c[0]:c[1]]] = frequency

    return combos

def create_combination(combos, word):
    if not combos:
        return None

    combo_keys = combos.keys()
    word = sorted(word)
    combinations_ = [
        j
        for i in range(len(combo_keys) + 1)
        for j in itertools.combinations(combo_keys, i)
        if sorted(''.join(j)) == word
    ]

    if not combinations_:
        return None

    result = None
    for combination in combinations_:
        sub = [(v, combos[v]) for v in combination]
        total = sum(map(operator.itemgetter(1), sub))
        if not result or total > result[2]:
            result = [combination, sub, total]

    return result

def display_combination(combination, word):
    if combination is None:
        print '\t\t'.join([word, 'Nothing Found'])
        return None

    part_final = ''.join(
        '[' + v[0] + ', ' +  str(v[1]) + ']'
        for v in combination[1]
    )

    print '\t\t'.join([word,' '.join(combination[0]), part_final, str(combination[2])])

def main():
    parser = ArgumentParser(description=__doc__)
    parser.add_argument("-w", "--wordlist", help="", required=True)
    parser.add_argument("-c", "--corpa", help="", required=True)
    args = parser.parse_args()
    corpas = read_corpa(args.corpa)
    for word in read_words(args.wordlist):
        combos = find_best(word, corpas)
        results = create_combination(combos, word)
        display_combination(results, word)

if __name__ == '__main__':
   main()


texts: Recursive directory scan using boost file system

texts:
I have written the following code for searching and recursive directory.

Please review it.

Can it be optimized to avoid traversing symlink and handle "abort" signal inside for loop to continue the flow

void Dirs::scan_dir(string dir_name, DataBase &b, string owner) {
    fs::path p(dir_name);
    if (!fs::exists(p)) {
        std::cout<<"Path does not exist"<<std::endl;
        return;
    }
    if(fs::is_directory(p)) {
        fs::recursive_directory_iterator end_iter;
        std::vector<std::string> check_link;
        for(fs::recursive_directory_iterator begin(p); begin != end_iter; ++begin){
            try {
                fs::path tmp = begin->path().filename();
                string f_path = begin->path().relative_path().string();
                f_path = "/" + f_path;
                bool link_found = false;
                for(std::vector<std::string>::iterator it = check_link.begin();
                        it != check_link.end(); ++it) {
                    if (f_path.find(*it) != std::string::npos){
                        link_found = true;
                        std::cout<<"link name"<<*it<<" in path is  "<<f_path<<std::endl;
                        break;
                    }
                }
                if(link_found)
                    continue;
                if(fs::is_symlink(begin->path())) {
                    check_link.push_back(begin->path().filename());
                    continue;
                }

                if(fs::is_regular_file(begin->path())) {
                    std::vector<std::string> ls_file_output = this->getfiledetail(f_path);
                    string f_time = std::to_string(fs::last_write_time(begin->path()));
#if 1
                    b.insert_disk_analyze_query(ls_file_output[2],
                                            this->local_time(),
                                            tmp.string(),
                                            f_path,
                                            ls_file_output[3],
                                            f_time);
#endif
                }
            }
            catch(fs::filesystem_error &ex) {
                std::cout<<" File.."<<ex.what()<<std::endl;
                signal(SIGINT, signal_callback_handler);
            }
            catch(const std::exception &ex) {
                std::cout << ex.what() << std::endl;
            }
            catch(...) {
                std::cout<<"unkown error"<<std::endl;
            }
        }
    }
}


texts: HackerRank "Manasa and Stones" in Python

texts:
Problem Statement:

Manasa is out on a hike with friends. She finds a trail of stones with numbers on them. She starts following the trail and notices that two consecutive stones have a difference of either a or b. Legend has it that there is a treasure trove at the end of the trail and if Manasa can guess the value of the last stone, the treasure would be hers. Given that the number on the first stone was 0, find all the possible values for the number on the last stone.
Note : The numbers on the stones are in increasing order

Input Format:
The first line contains an integer T i.e. the number of Test cases. T testcases follow.
Each testcase has 3 lines. The first line contains n ( the number of stones ) The second line contains a. The third line contains b.
Output Format:
Space separated list of numbers which are the possible values of the last stone in increasing order.
Constraints:
1 ≤ T ≤ 10
1 ≤ n, a, b ≤ 103
Algorithm:
I order a and b such that a > b. The maximal value of the last stone is then found from the sequence:
1, a, 2 * a, 3 * a, ..., (n-2) * a, (n-1) * a

Which is arithmetic sequence with difference a. A smaller value will be produced by replacing the last difference of 'a' with 'b', which results in (n-2) * a + 1 * b. Doing this repeatedly yields the list of possible stone values:
(n-1) * a + 0 * b, (n-2) * a + 1 * b, ..., 1 * a + (n-2) * b, 0 * a + (n-1) * b

Since a, b can be equal, I wrap this list into a set to produce my code below.
Code:
T = int(input())

for _ in range(T):
    n = int(input())
    a = int(input())
    b = int(input())
    a, b = sorted((a, b))
    values = sorted(set([(n - i - 1) * a + i * b for i in range(n)]))
    print(*values)

I would like any suggestions to help improve this code.


texts:
I think my code works pretty well, although I'm biased: http://jsfiddle.net/AHKb4/2/
Basic Overview: I'm working on building a math skill game, where the objective is to drag and drop div's to a container. Each div will have a value, likely set with classes. Each container must equal theSumNum to pass the level. Just giving this info so you can possibly understand better what I'm trying to achieve.

Most importantly I think I've got my main function pickNumbers() ready to go. But I'd really appreciate any opinions and advice that you have for that function.

I've made two classes so far, three and five. I'm planning though to have classes from two through ten. I'm thinking each class will have an amount of arrays equal to that class number. Likewise there will be x number of container divs for x number of arrays.
So I think I could obviously improve how I do my classes by creating a for loop to generate the classes when needed, and use like myArray1 instead of myArrayOne.  I'm just looking for a True or False answer for this question.

Lastly, please take a look at the function pickFive(). So again I'm assuming I could just use a for loop for that as well? Just looking for a True or False here too, but if there's anything to look out for or be careful of in doing it that way, please let me know.

$(document).ready(function() {
var three = {
    myArrayOne: [],
    myArrayTwo: [],
    myArrayThree: [],
    myArraysCombined: []
}
var five = {
    myArrayOne: [],
    myArrayTwo: [],
    myArrayThree: [],
    myArrayFour: [],
    myArrayFive: [],
    myArraysCombined: []
}
// theArray is the array to push to  ~ ex(three.myArrayTwo)
// theNum is the amount of numbers that will be in the array  ~ ex(3)
// theSumNum is what the sum of all the numbers in the array will equal  ~ ex(20)
// theMaxNum is the largest number that can appear in the array, except the last number may be larger since its not random  ~ ex(10)
// theMinNum is the smallest number that can appear in the array  ~ ex(1)
// aRandNum is a temporary var for each number in the array, except for the last number in the array
// thePreSumNum is the sum of all the numbers in the array except for the last number
// theLastNum is the last number that will be pushed to the array, this number is not random
function pickNumbers(theArray, theNum, theSumNum, theMaxNum, theMinNum) {
    for (var x=0; x < theNum;) {
        var aRandNum = Math.floor(Math.random()*theMaxNum + theMinNum);
        if (theArray.indexOf(aRandNum) === -1) {
            if (theArray.length < (theNum - 1)) {
                theArray.push(aRandNum);
                x += 1;
            }
            if (theArray.length === (theNum -1)) {
                var thePreSumNum = 0;
                for (var e = 0; e < theArray.length; e += 1) { thePreSumNum += theArray[e]; }
                var theLastNum = theSumNum - thePreSumNum;
                    if (theArray.indexOf(theLastNum) > -1 || theLastNum < 1) {
                        theArray.length = 0;
                        x = theNum;
                        pickNumbers(theArray, theNum, theSumNum, theMaxNum, theMinNum);
                    }
                    else {
                        theArray.push(theLastNum);
                        x += 1;
                    }
            }
        }
    }
}

function pickThree() {
    pickNumbers(three.myArrayOne, 3, 20, 10, 1);
    pickNumbers(three.myArrayTwo, 3, 20, 10, 1);
    pickNumbers(three.myArrayThree, 3, 20, 10, 1);
    three.myArraysCombined = three.myArrayOne.concat(three.myArrayTwo, three.myArrayThree);
}

function pickFive() {
    pickNumbers(five.myArrayOne, 5, 40, 20, 1);
    pickNumbers(five.myArrayTwo, 5, 40, 20, 1);
    pickNumbers(five.myArrayThree, 5, 40, 20, 1);
    pickNumbers(five.myArrayFour, 5, 40, 20, 1);
    pickNumbers(five.myArrayFive, 5, 40, 20, 1);
    five.myArraysCombined = five.myArrayOne.concat(five.myArrayTwo, five.myArrayThree, five.myArrayFour, five.myArrayFive);
}

pickThree();
pickFive();

});


texts:
I was writing a function that takes an argument and returns a truth value.

My initial idea was just return !!value, but this will fail for '0', {} or []. I know that '0' should be true but in my application we are considering it false.

So, my function should return false for:

Falsey values: false, 0, undefined, null, ''
Blank values: {}, []
Special requirement: '0'

So considering it, I updated code to following to handle

var isTrue = function(value) {
  switch (typeof(value)) {
    case "string":
      return !(value === '0' || value === 'false');
    case "number":
    case "boolean":
      return !!value;
    case "object":
      return Object.keys(value).length > 0
  }
}

console.log(false,isTrue(false))
console.log(true,isTrue(true))
console.log(0,isTrue(0))
console.log(1,isTrue(1))
console.log('0',isTrue('0'))
console.log('1',isTrue('1'))
console.log('test',isTrue('test'))
console.log('Object',isTrue({}))
console.log('Array',isTrue([]))

Now this works fine. It does not include handling for functions but that is out of scope of current question. My question is, is there a better way to handle the same?


texts:
I have been using this site for a couple of years for great answers and a ton of help. I wrote this program for my class project due 1/23. I am just wondering what you would recommend me changing or improving. I think I have some repetitive code, but I have not learned about defs in Java yet.

package project2;

import java.util.Scanner;

/**
 * @author Sartaj Singh
*/
public class Project2 {

    public static void main(String[] args) {

        int choice = 0;
        double weight;
        double earth = 9.81;
        double moon = 1.622;
        double mercury = 3.7;
        double venus = 8.87;
        double jupiter = 24.79;

        System.out.println("Welcome to Planetary Weight Calculator: ");
        Scanner input = new Scanner(System.in);
        System.out.print("Enter your weight in pounds (lb): ");
        weight = input.nextDouble();
        while (weight <= 0) {
            System.out.println("Invalid Input - Plase enter a value higher than 0 ");
            System.out.print("Enter your weight in pounds (lb): ");
            weight = input.nextDouble();
        }
        System.out.println("/////MENU/////");
        System.out.println("1 - Moon");
        System.out.println("2 - Mercury");
        System.out.println("3 - Venus");
        System.out.println("4 - Jupiter");
        System.out.print("Pick a number 1-4: ");
        choice = input.nextInt();
        while (choice <= 0 || choice >= 5) {
            System.out.println("/////MENU/////");
            System.out.println("1 - Moon");
            System.out.println("2 - Mercury");
            System.out.println("3 - Venus");
            System.out.println("4 - Jupiter");
            System.out.print("Pick a number 1-4: ");
            choice = input.nextInt();
        }
        switch (choice) {
            case 1:
                System.out.println("You selected Moon, your weight on Moon is: ");
                System.out.println(weight * (moon / earth) + " Lbs");
                break;
            case 2:
                System.out.println("You selected Mercury, your weight on Mercury is: ");
                System.out.println(weight * (mercury / earth) + " Lbs");
                break;
            case 3:
                System.out.println("You selected Venus, your weight on Venus is: ");
                System.out.println(weight * (venus / earth) + " Lbs");
                break;
            case 4:
                System.out.println("You selected Jupiter, your weight on Jupiter is: ");
                System.out.println(weight * (jupiter / earth) + " Lbs");
                break;
        }

        System.out.println("Thank you for using the Planetary Weight Calculator");
        System.out.println("Hope you will use it again! ");

    }

}


texts:
Currently I try to create some unit tests for a project, which provides access to some webservice methods.

It's interface is rather simple. I have a class "WebService" which offers methods like "CreatePDF".
Here's a little example:

The Model:
The model contains a number of properties, which each represent a URL parameter of the webservice. The models provide a method "GetParameterDictionary", which delivers a dictionary with key == url parameter name and value == url parameter value.

public class CreatePDFParameters
{
        public List<string> Names { get; set; }
        public List<string> Colors { get; set; }

        public Dictionary<string, string> GetParameterDictionary()
        {
            [...] //returns Key == url parameter name and Value == ";" separated list of values
        }
}

So here's a example for the Interface method:

public byte[] CreatePDF(CreatePDFParameters parameters)
{
    return MakeByteRequest(GetQuery(WebServiceMethods.CreatePDF, parameters.GetParameterDictionary()));
}

/// <summary>
///     Creates a query out of a dictionary. The dictionary must have the paramname as key and the value as value!
/// </summary>
private string GetQuery(string methodName, Dictionary<string, string> parameters)
{
    string parameterString = parameters.Where(parameter => !String.IsNullOrEmpty(parameter.Value))
    .Aggregate(String.Empty, (current, parameter) => String.Format(String.IsNullOrEmpty(current) ? "{0}?{1}={2}" : "{0}&{1}={2}", current, parameter.Key, parameter.Value));
    return methodName + parameterString;
}

As you can see, you only need to call the CreatePDF method with a parameters object. The method itself calls a methods, which creates the query and calls a method, which makes the actual request (It calls directly the ByteRequest method, there are methods like StringRequest (delivers a string as return value) too).

I would like to write a UnitTest for the GetQuery method. But I don't want to make it public or internal in the actual state. I could make the method public If I would remove the "CreatePDF" method and let the user make direkt calls to MakeByteRequest / GetQuery and so on - which would require the users to have some knowledge about the webservice itself (knowledge about return types, web method names and so on).

Would you prefer a more simple "interface" over unit tests in this case?


texts:
Is there any way to improve this simple addition to the textbox control: appending a new line?

class CustomTextBox : TextBox
{
    public void AppendLine(string textData)
    {
        if (this.Text.EndsWith(Environment.NewLine) || this.Text == "")
        {
            this.AppendText(textData);
        }
        else
        {
            this.AppendText(Environment.NewLine + textData);
        }
    }
}


texts: Node.js/Express middleware to relay requests to various APIs

texts:
I am creating a nodejs middleware server that will handle api transactions from a frontend and relay them to various api's (internal and external). The primary goal is to hide api keys from the frontend. It can also consolidate requests that may require 2 or more endpoints, and modify data structures, thus simplifying our frontend code.

I am hoping for feedback on overall design/structure which will allow us to create a project that will be flexible as we add more apis while keeping it DRY

URLs, keys, etc. are stored in a .env file

index.js

require('dotenv').load();
const express = require('express'),
  app = express(),
  request = require("./request").request,
  bodyParser = require('body-parser');

app.use(bodyParser.json());

//returns all locations
app.get("/locations", (req, res) => {
  let URL = '...';
  request({
    method: 'get',
    url: URL,
    api: 'apiName'
  }).then((resp) => {
    res.json(resp);
  })
});

//send password reset link
app.post("/resetemail", (req, res) => {
  let URL = '...';
  let DATA = req.body;

  request({
    method: 'post',
    url: URL,
    api: 'apiName',
    data: DATA
  }).then((resp) => {
    res.json(resp);
  })
});

app.listen(3000);

request.js

module.exports.request = function (options) {

  const client = require('./' + options.api).instance;
  const handleError = require('./' + options.api).handleError;
  const onSuccess = function (response) {
    console.log('Request Successful!', response);
    return response.data;
  }

  return client(options)
    .then(onSuccess)
    .catch(handleError);
}

apiName.js

const axios = require('axios');
const axiosInstance = axios.create({
  headers: { "token": process.env.API_TOKEN },
  baseURL: process.env.API_BASE_URL,
  timeout: 2000
});

const handleError = function (error) {
  console.error('Request Failed:', error.config);

  if (error.response) {
    console.error('Status:', error.response.status);
    console.error('Data:', error.response.data);
    console.error('Headers:', error.response.headers);

  } else {
    console.error('Error Message:', error.message);
  }

  return Promise.reject(error.response || error.message);
}

module.exports = {
  instance: axiosInstance,
  handleError: handleError
}


texts:
I created an Observable class that allows me to subscribe to a wrapped value. The implementation looks like this:

class Observable<ValueType> {
    typealias DidChangeHandler = (oldValue: ValueType?, newValue: ValueType) -> ()

    // MARK: Properties

    var value : ValueType {
        didSet {
            for (owner, handlers) in self._observers {
                for handler in handlers {
                    handler(oldValue: oldValue, newValue: value)
                }
            }
        }
    }

    // MARK: Initializers

    init(_ value: ValueType) {
        self.value = value
    }

    // MARK: Methods

    func addObserverForOwner(owner: AnyObject, triggerImmediately: Bool, handler: DidChangeHandler) {
        if let index = self._indexOfOwner(owner) {
            // since the owner exists, add the handler to the existing array
            self._observers[index].handlers.append(handler)
        }
        else {
            // since the owner does not already exist, add a new tuple with the
            // owner and an array with the handler
            self._observers.append(owner: owner, handlers: [handler])
        }

        if (triggerImmediately) {
            handler(oldValue: nil, newValue: self.value)
        }
    }

    func removeObserversForOwner(owner: AnyObject) {
        if let index = self._indexOfOwner(owner) {
            self._observers.removeAtIndex(index)
        }
    }

    // MARK: Private Properties

    private var _observers: [(owner: AnyObject, handlers: [DidChangeHandler])] = []

    // MARK: Private Methods

    private func _indexOfOwner(owner: AnyObject) -> Int? {
        var index: Int = 0
        for (possibleOwner, handlers) in self._observers {
            if possibleOwner === owner {
                return index
            }
            index++
        }
        return nil
    }
}

This allows me to create a variable and observer it as follows:

var observableString = Observable<String>("String")

observableString.addObserverForOwner(self, triggerImmediately: false) {
    (oldValue, newValue) in
    // ...
}

I think this is most useful to use for properties on classes.

However, there are a few things that I don't like:

Requires manually unobserving even if the owner is dealloced
triggerImmediately seems kind of verbose
oldValue has to be an optional because in the triggerImmediately case there is no old value

Mostly I am looking for any ideas on ways to improve the usability of this interface, but I am open to any ways to improve the code.

Update 08/02/2014

I actually figured out a way to not require manually unobserving if the owner is deallocated. It isn't perfect, but it does work. Basically I created a WeakWrapper class that makes a weak reference to a wrapped value. This allows Observable to keep an array of weak references instead of strong references to observers. The reference will be set to nil when the observer is dealloced so I can clean them up the next time the observable is triggered. The negative part of it is that the handlers are not removed until the next time the observable is triggered.

To see the new code, including changes suggested by @nhgrif below, you can visit my github repository.


texts:
So I have a file(story.dat) with a randomly generated story like:
"Sleeping in his car was never the plan but sometimes things don't work out as planned. This..."
It will print out each word and the corresponding word to it like so:
0."It: was,
1."Pepsi-Cola.": He,
2."This: is,
3./: 50.,
4.50: /,
5.50.: I,
6.A: long,
7.All: that,
8.He: didn't,knew,had,
9.I: think,had,
10.I'd: love,
11.I'm: certain,
12.It: was,
13.Or: at,
14.She: knew,
15.Sleeping: in, ...

And then it prints the story like so:

have a cup of everything. The inside was ten, and a little strange,
but he was either exhausted of days ago. It was supposed to hear from
you today and fondling over it. He knew what made the last option is
to make a year ago. It was supposed to make this case, was in months.
The third is the sun. He knew...

Here's the code:
// #include files
namespace Randomiser
{
    std::mt19937 generator{ static_cast<std::mt19937::result_type>(std::time(nullptr)) };
}
int getRandomNumber(int min, int max)
{
    std::uniform_int_distribution<int> rand{ min, max };
    return rand(Randomiser::generator);
}

void markovIt(const std::map<std::string, std::vector<std::string>>& m)
{
    std::string temp{};
    std::vector<std::string> possibilities{};
    std::string next{};

    int i{ 0 };
    int randomNumber{ getRandomNumber(0, m.size()) };
    for (const auto& n : m)
    {
        if (i == randomNumber)
        {
            temp = n.first;
        }
        ++i;
    }

    auto found{ m.find(temp) };
    i = 0;
    while(found != m.end())
    {
        if (i == 255)
            break;

        possibilities = found->second;
        next = possibilities.at(getRandomNumber(0, possibilities.size() - 1));

        std::cout << temp << " ";
        temp = next;

        found = m.find(temp);
        ++i;
    }
}

int main()
{
    std::ifstream wordStream{ "story.dat" };
    std::string fWord;
    std::string sWord;
    std::vector<std::string> temp;
    std::map<std::string, std::vector<std::string>> gram{};
    int i{ 0 };
    while(wordStream)
    {
        wordStream >> fWord;
        if (i != 0)
            gram[sWord].push_back(fWord);
        wordStream >> sWord;
        gram[fWord].push_back(sWord);
        if (i == 0)
            i++;
    }

    i =  0;
    for (const auto& n : gram)
    {
        std::cout << i << "." << n.first << ": ";
        for (const auto& key : n.second)
            std::cout << key << ",";
        std::cout << '\n';
        ++i;
    }

    markovIt(gram);
    std::cout << '\n';

    return 0;
}

The implementation feels awful and I believe it could be optimised alot further. I'm just not sure where to take it.


texts:
I have made an operator (surrounded by others operators) for training a model in sagemaker in airflow and I have doubts how would it be more readable or more pythonic. First I did this:

transform_data = BashOperator(
        task_id = 'transform_data',
        bash_command = 'blabla')

container = get_image_uri(boto3.Session().region_name,
                      'xgboost', repo_version='0.90-1')
estimator = sagemaker.estimator.Estimator(
        container,
        role = 'AmazonSageMaker-ExecutionRole-201903XXX',
        train_instance_count = 1,
        train_instance_type = 'ml.m4.2xlarge',
        output_path = f"s3://production/models/{domain}-{product}-{today}",
        train_use_spot_instances = True,
        hyperparameters = {'num_round':'400',
                           'objective':'binary:logistic',
                           'eval_metric':'error@0.1',
                           'gamma':'5',
                           'scale_pos_weight':'10'}
        )

s3_input_train = sagemaker.s3_input(s3_data='s3://production/data/{domain}-{product}-{today}/train_data.csv',
                                    content_type='text/csv')
s3_input_validation = sagemaker.s3_input(s3_data='s3://production/data/{domain}-{product}-{today}/validation_data.csv',
                                    content_type='text/csv')

job_name_timestamp = datetime.today().strftime('%Y-%m-%d-%H-%M-%S')

train_config = training_config(estimator=estimator,
                               inputs = {'train':s3_input_train,
                                         'validation':s3_input_validation},
                                         job_name = f'{domain}-{product}-{job_name_timestamp}')

model_training = SageMakerTrainingOperator(
            task_id = 'model_training',
            config = train_config,
            wait_for_completion = True)

model_deployment = OperatorX(blabla)

But then, I have gathered all the information about the training operator, motivated by not stopping the succession of operators in the code. So I have coded:

transform_data = BashOperator(
        task_id = 'transform_data',
        bash_command = 'blabla')

model_training = SageMakerTrainingOperator(
        task_id = 'model_training',
        config = training_config(
                estimator=sagemaker.estimator.Estimator
                (
                    container=get_image_uri(boto3.Session().region_name,
                                  'xgboost', repo_version='0.90-1'),
                    role = 'AmazonSageMaker-ExecutionRole-20190XXXX',
                    train_instance_count = 1,
                    train_instance_type = 'ml.m4.2xlarge',
                    output_path = f"s3://production/models/{domain}-{product}-{today}",
                    train_use_spot_instances = True,
                    hyperparameters = {'num_round':'400',
                                       'objective':'binary:logistic',
                                       'eval_metric':'error@0.1',
                                       'gamma':'5',
                                       'scale_pos_weight':'10'}
                ),
               inputs =
               {
                   'train':sagemaker.s3_input(s3_data='s3://production/data/{domain}-{product}-{today}/train_data.csv',
                                              content_type='text/csv'),
                   'validation':sagemaker.s3_input(s3_data='s3://production/data/{domain}-{product}-{today}/validation_data.csv',
                                                   content_type='text/csv')
               },
               job_name = f"{domain}-{product}-{datetime.today().strftime('%Y-%m-%d-%H-%M-%S')}"),
        wait_for_completion = True)

model_deployment = OperatorX(blabla)

What do you think? Which is the best way? Doesn't it matter at all and both can be considered as good (or bad) code? thanks for your answers


texts:
This is my implantation of counting sort, but I see myself using way too many for loops. Is this necessary?

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

namespace ConsoleApplication1
{
    class Program
    {
        public static int[] a = { 0,0,0,5,4,8,9,9,7,3, 3, 2, 1 };
        public static void Sorting()
        {
            int j = 0, i = 0, smallestvalue = 0, largestvalue = 0, n = a.Length, lengthof_B = 0, temp = 0, anothersmallestvalue;
            smallestvalue = largestvalue = a[0];
            for (i = 0; i < n; i++)
            {
                if (smallestvalue > a[i])
                {
                    smallestvalue = a[i];
                }
                else if (largestvalue < a[i])
                {
                    largestvalue = a[i];
                }
            }
            int x = anothersmallestvalue = smallestvalue;

            lengthof_B = largestvalue - smallestvalue + 1;
            int[] b = new int[lengthof_B];
            for (i = 0; i < lengthof_B && smallestvalue <= largestvalue; i++)
            {
                for (j = 0; j < n; j++)
                {
                    if (smallestvalue == a[j])
                    {
                        b[i] = b[i] + 1;
                    }
                }
                b[i] = temp + b[i];
                temp = b[i];
                smallestvalue++;
            }
            int[] c = new int[a.Length];
            for (i = n - 1; i >= 0; i--)
            {
                anothersmallestvalue = x;
                for (j = 0; j <= lengthof_B ; j++)        //{3,3,2,1}
                {
                    if (a[i] == anothersmallestvalue)
                    {
                        temp = b[j];
                        c[temp-1] = anothersmallestvalue;
                        b[j] = b[j] - 1;
                    }
                    anothersmallestvalue++;
                }
            }
            for (i = 0; i < c.Length; i++)
            {
                Console.WriteLine("c[i] : " + c[i]);
            }
        }
    }
    class Demo
    {
        static void Main(string[] args)
        {
            Program.Sorting();
            Console.ReadLine();
        }
    }
}


texts: The problem “Fun game” from a competition

texts:
I recently began to learn Python and encountered this problem.
The condition:
You and your friends are playing the next game. Friends write  natural numbers in a row on the board. Your task is to find as many consecutive numbers as possible that are divisible by the same number greater than 1. Since it is difficult to find the answer manually, you decided to write a program that will do the job for you.
Input:
The first line of the input contains the number  (1 ≤  ≤ 100000). The second line is separated by a space  integers 1... (1 ≤  ≤ 1000, 1 ≤  ≤ ). These are the numbers that your friends wrote. They are given in the same order as they are placed on the board.
Output:
Your program should output a single integer — the largest number of consecutive numbers in a given sequence that would be divisible by the same natural number greater than 1.
Here is my code:
Python

from math import gcd

def func(n,a):

    mx = 0
    for i, cur_g in enumerate(a):
        if n - i < mx:
            break
        p = 0
        for j in range(i, n):
            cur_g = gcd(cur_g, a[j])
            if cur_g == 1:
                break
            p += 1
            if mx < p:
                mx = p

    return mx

print(func(int(input()), [int(i) for i in input().split()]))

The problem is that I can't pass the time check: the program runs for longer than 0.5 seconds. And I can't think of any way to speed up the program. It may even be necessary to solve the problem itself in a different way. Please help me. Thanks in advance!


texts: Looping through nested arrays with creating new array from nested items

texts:
I have written this function but I am not so proud on it. I could use some help refactoring it.

Would recursion improve my code?

Data sample.

{
  "Name":"test2",
  "DepartmentUnitId":"test",
  "ParentDepartmentUnitId":"test",
  "NestedDepartments":[
    {
      "Name":"test2",
      "DepartmentUnitId":"test",
      "ParentDepartmentUnitId":"test",
      "NestedDepartments":[]
    },
    {
      "Name":"test2",
      "DepartmentUnitId":"test",
      "ParentDepartmentUnitId":"test",
      "NestedDepartments":[]
    }
  ]
}

JS:

function indentDepartments(departments, model) {
    var indentedDepartments = [];

    _.each(departments, function (department) {
        indentedDepartments.push(buildDepartment(department, 0));
        _.each(department.NestedDepartments, function (lv1Department) {
            indentedDepartments.push(buildDepartment(lv1Department, 1));
            _.each(lv1Department.NestedDepartments, function (lv2Department) {
                indentedDepartments.push(buildDepartment(lv2Department, 2));
            });
        });
    });

    function buildDepartment(data, level) {
        department = _.pick(data, 'DepartmentUnitId', 'ParentDepartmentUnitId');
        name = _.times(level, function () { return '-'; }).join('') + data.Name;

        _.extend(department, { Name: name });
        return department;
    }
    model.parentDepartments(indentedDepartments);
}

Edit:
Nested array can go 2 levels deep, but I wouldn't mind making this function more scalable.


texts:
I have been in conversation with a fellow web developer on whose servers I am doing some client work. Part of the current project is to add an email sending system from a web based form to my clients email via PHPMailer.

I have used PHPMailer repeatedly with no issues whatsoever, however, this developer has said to me that they do not want PHPMailer on the server due to having found previous instances on their server of PHPMailer being 'hacked'.

Please note that with all form to email systems I use I do believe I fully escape and clean the input strings as far as possible.

I'm asking here:

Is hacking PHPMailer version 5.2.8 specifically even possible?
How is this possible?
What can be done to secure PHPMailer in these instances?

Is there a halfway clear way that the above script could be hacked or otherwise hijacked by a hacker or similar?

Please note: all $member array values are from a database and have already been pre-cleaned.

require "PHPMailerAutoload.php"; ///version 5.2.8

        $message = "The following enquiry about " . $member['bizname'] . " was sent to " . $member['contname'] . " :
    Enquirer's Name: " . $name . ",
    Enquirer's Address:
         " . $addr1 . "
         " . $addr2 . "
         " . $addr3 . "
         " . $postcode . "
    Telephone Number: " . $tel . ",
    Email address: " . $email . ",
    Dates they are interested in: " . $dates . ",
    Comments: " . $comments . ".

    NOTE: This is an automatic notification email for your records.
    Please do not reply to this email.
        ";

         $mail           = new PHPMailer();
        $mail->Host     = "localhost";
        $mail->WordWrap = 78;
        $mail->Mailer   = "smtp";
        $mail->From     = "server@website.co.uk";
        $mail->FromName = "Website Server";

///this is the client email and would not change.
        $mail->AddAddress("static@email-address.co.uk");
        $mail->Subject = $member['bizname'] . " Website Enquiry";
        $mail->Body    = $message;
        if (!$mail->Send()) {
            $dispmsg = "Mailer 1 error: " . $mail->ErrorInfo;
        } else {
            $dispmsg = "Your email has been sent to " . $member['bizname'] . " who will be in touch with you shortly.";
        }
    ////////////end email 1


texts:
My attempt at a fixed framerate using SDL2 without using VSync. Just using SDL_Delay left the fps a bit slower or faster due to the fact SDL_Delay only works with milliseconds. So the solution I came up with is after using SDL_Delay the remainder of the "extra" time is elapsed through a loop. The solution seems a little bit cluttered to me and my experience with programming in general is very limited so any pointers would be much appreciated.

float frame_cap{ 60 };
float ms_per_frame{ 1000.0f / frame_cap };
float fps{ 0 };
uint64_t start_counter;
uint64_t end_counter;

bool quit{ false };
while( quit != true )
{
    start_counter = SDL_GetPerformanceCounter();

    //HANDLE INPUT
    //UPDATE
    //RENDER

    end_counter = SDL_GetPerformanceCounter();
    //multiplying by 1000.0f to convert to ms
    float elapsed_ms = ((end_counter - start_counter) / (float)SDL_GetPerformanceFrequency()) * 1000.0f;
    if( elapsed_ms < ms_per_frame )
    {
        float ms_left = ms_per_frame - elapsed_ms;
        SDL_Delay( floor(ms_left) );

        //loop for the amount of time that could not be delayed with SDL_Delay
        float missed_ms = ms_left - floor(ms_left);
        start_counter = SDL_GetPerformanceCounter();
        float delayed_ms { 0 };
        while(delayed_ms < missed_ms)
        {
            end_counter = SDL_GetPerformanceCounter();
            delayed_ms = ((end_counter - start_counter) / (float)SDL_GetPerformanceFrequency()) * 1000.0f;
        }
        //adding time delayed to elapsed time of frame for fps calculation
        elapsed_ms += floor(ms_left) + delayed_ms;
        /*floor(ms_left) is time delayed using SDL_Delay
        this has a chance to be inaccurate if SDL_Delay
        delays more then floor(ms_left) due to OS scheduling*/
    }
    //dividing by 1000.0f to convert to seconds
    fps = 1.0f / (elapsed_ms / 1000.0f);
}


texts: Formatting floating point number as mixed fractional in Ruby

texts:
I have to format numbers that are either whole numbers or mixed fractional numbers with quarters (1/4, 1/2, 3/4) or thirds (1/3, 2/3).

The numbers are given as floats, for example 1.3333333 or 1.5 and are therefore inaccurate (but always close to a quarter or a third).

The formatting method is supposed to return Unicode fractions, for example:

1.0    #=> 1
1.3333 #=> 1⅓
1.5    #=> 1½
1.6667 #=> 1⅔

My current approach is to format the number via sprintf and to apply a second formatting based on the result:

def format_fraction(number)
  fix, frac = sprintf('%0.2f', number).split('.')
  case frac
  when '00' then "#{fix}"
  when '25' then "#{fix}¼"
  when '33' then "#{fix}⅓"
  when '50' then "#{fix}½"
  when '67' then "#{fix}⅔"
  when '75' then "#{fix}¾"
  end
end

Is there a better / less string-based / more numeric way to solve this?


texts:
I want to design Chinese mapping number routing. How can I improve this code in the method mapRouting?

I want to use reflect auto get method name by providing a value without if else, but I have no idea how to do it.

public class FwMappingChi {

    public static Map<String, String> mapRouting(String mapName){
        if(mapName == "ACTION") {
            return ACTION;
        }
        else if(mapName == "ENVIRONMENT") {
            return ENVIRONMENT;
        }
        else if(mapName == "RULE_TYPE") {
            return RULE_TYPE;
        }
        return null;
    }

    @SuppressWarnings("serial")
    private static final Map<String, String> ACTION = new HashMap<String, String>(){
        {
            put("0", "新增");
            put("1", "刪除");
        }
    };

    @SuppressWarnings("serial")
    private static final Map<String, String> ENVIRONMENT = new HashMap<String, String>(){
        {
            put("0", "正式環境");
            put("1", "長期UAT");
            put("2", "測試需求");
        }
    };

    @SuppressWarnings("serial")
    private static final Map<String, String> RULE_TYPE = new HashMap<String, String>(){
        {
            put("0", "系統間連接");
            put("1", "系統間連接");
            put("2", "人員維護用");
            put("3", "提供服務用");
            put("4", "User對外連接");
        }
    };
}

example:

List<Map<String, Object>> exportDatas = fwApplyListDetailMapper.getExportQuery(idsArr);
List<List<String>> pdfValues = new ArrayList<>();
for (int i = 0; i < exportDatas.size(); i++) {
    List<String> record = new ArrayList<>();
    Map<String, Object> map = exportDatas.get(i);
    for (String index : headerIndex) {
        Object value = map.get(index);

        if(FwMappingChi.mapRouting(index) != null) {
            record.add(FwMappingChi.mapRouting(index).get(String.valueOf(value)));
        }

    }
    pdfValues.add(record);
    record = null;
}


texts: Is there a PHP security exploit with $_POST in my code?

texts:
I posted this question here.

And an answer stated that I should not do:

$table_name = 'survey_'.$_POST['surveyid'];

because

  It is easy for a hacker to exploit your site if you include $_GET or $_POST data directly in any SQL string.

Here is the code.  Do you see any security exploits?

if(ctype_digit($_POST['surveyid']) && $_POST['surveyid']>0){

    $table_name = 'survey_'.$_POST['surveyid'];

    $query = 'CREATE TABLE '.$table_name.' (
            `responseid` INT NOT NULL AUTO_INCREMENT,
            `textarea1` TEXT NULL,
            `textarea2` TEXT NULL,
            `textarea3` VARCHAR(255) NULL,
            `drop_down1` VARCHAR(255) NULL,
            `drop_down2` VARCHAR(255) NULL,
            `bool1` BIT NULL,
            `bool2` BIT NULL,
        PRIMARY KEY (`responseid`))';
}

I don't see a vulnerability.... why is $_POST['surveyid'] vulnerable? It is being sanitized by ctype_digit...


texts:
I'm a beginner and am self taught and was hoping I could get help from others more educated than me to show me what bad practices I might be forming before I go on further.

P.S. This program is just for me to learn, I'm not actually storing passwords with it.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys

def openPassFile():
    try:
        passwordFile = open('hashwork.txt', 'a')
        return passwordFile
    except IOError as e:
        print("I/O Error({0}): {1}".format(e.errno, e.strerror))
        quit

def closePassFile(passwordFile):
    try:
        passwordFile.close()
    except IOError as e:
        print("I/O Error({0}): {1}".format(e.errno, e.strerror))
        quit

def randomValue(length):
    import random
    salt_chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
    return ''.join(random.choice(salt_chars) for x in range(length))

def askforUsername():
    while True:
        print("Please enter the username you would like to use:")
        username = raw_input()
        return username

def askforPassword():
    import getpass, hashlib
    while True:
        print("What password would you like to create?")
        salt = randomValue(16)
        hashedPassword1 = hashlib.sha256(salt+getpass.getpass()).hexdigest()
        print("\nPlease enter password again.")
        hashedPassword2 = hashlib.sha256(salt+getpass.getpass()).hexdigest()
        if hashedPassword1 == hashedPassword2:
            return hashedPassword2, salt
            break
        else:
            print("Your passwords do not match. Please retry")

def storeInfo(username, hashedPass, salt):
    passwordFile = openPassFile()
    passwordFile.write(username + " | " + hashedPass + " | " + salt + "\n")
    closePassFile(passwordFile)

username = askforUsername()
hashedPass, salt = askforPassword()
storeInfo(username, hashedPass, salt)
sys.exit()


texts:
I wrote an analog watch simulation in C# and Monogame as exercise.

The application consists of a background texture. On top of that I have the hour-, minute- and second hand.

The program gets its time from DateTime.Now.

The second hand rotates by multiplying the seconds with 1/60 of a total lap in radians.

It's the same with the minute hand and hour hand.

Source code:

class Clock
{
    int hour;
    int minutes;
    int seconds;

    // Textures
    public Texture2D CaseBack;
    public Texture2D HourHand;
    public Texture2D MinuteHand;
    public Texture2D SecondHand;

    Vector2 center = new Vector2(63, 63); // Center of watch

    // Gets called 60 times/second
    public void Update(GameTime gameTime)
    {
        hour = DateTime.Now.Hour;
        minutes = DateTime.Now.Minute;
        seconds = DateTime.Now.Second;
    }

    // Gets called 60 times/second
    public void Draw(SpriteBatch spriteBatch)
    {
        // Background/Case back
        spriteBatch.Draw(CaseBack, Vector2.Zero, Color.White);

        // Second hand
        spriteBatch.Draw(SecondHand, center, null, null, new Vector2(3, 50),
            ((float)seconds*(float)Math.PI*2 / 60),
            // This is the rotation. Works by multiplying Seconds with a 1/60 of a "circle's angle".
            null, Color.White, SpriteEffects.None, 0);

        // Minute hand - basically the same, but with minutes
        spriteBatch.Draw(MinuteHand, center, null, null, new Vector2(3, 40),
            ((float)minutes * (float)Math.PI * 2 / 60),
            null, Color.White, SpriteEffects.None, 0);

        // Hour hand - same here
        spriteBatch.Draw(HourHand, center, null,null, new Vector2(4, 30),
            ((float)hour * (float)Math.PI * 2 / 12),
            null, Color.White, SpriteEffects.None, 0);
    }


texts:
Generic Headers

#include <vector>
#include <string>
#include <iostream>
#include <fstream>

typedef std::string const           BFProgram;

BF Interpreter

class BFInterpretor
{
    static const std::size_t MemorySize = 10000;

    std::vector<char>           memory;
    std::vector<std::size_t>    openLoops;
    BFProgram&                  program;
    std::istream&               input;
    std::ostream&               output;
    std::size_t                 dataPointer;
    std::size_t                 progPointer;

    std::size_t scanToEndOfLoop()
    {
        std::size_t nestedLoops = 1;
        std::size_t scanPos     = progPointer;
        for(;nestedLoops != 0;++scanPos)
        {
            switch(program[scanPos])
            {
                case '[':   ++nestedLoops;  break;
                case ']':   --nestedLoops;  break;
                default:                    break;
            }
        }
        return scanPos;
    }

    public:
        BFInterpretor(BFProgram& program, std::istream& input = std::cin, std::ostream& output = std::cout)
            : memory(MemorySize)
            , program(program)
            , input(input)
            , output(output)
            , dataPointer(0)
            , progPointer(0)
        {}

        static bool bfComment(char c)
        {
            switch(c)
            {
                case '>': case '<': case '.': case ',': case '+': case '-': case '[': case ']':
                    return false;
                default:
                    break;
             }
             return true;
        }
        void run()
        {
            while(progPointer < program.size())
            {
                ++progPointer;
                switch(program[progPointer - 1])
                {
                    case '>':   dataPointer = (dataPointer + 1) % MemorySize;break;
                    case '<':   dataPointer = (dataPointer - 1) % MemorySize;break;
                    case '+':   ++(memory[dataPointer]);                     break;
                    case '-':   --(memory[dataPointer]);                     break;
                    case '.':   output.put(memory[dataPointer]);             break;
                    case ',':   memory[dataPointer] = input.get();           break;
                    case '[':   if (memory[dataPointer]) {
                                    openLoops.push_back(progPointer);
                                }
                                else {
                                    progPointer = scanToEndOfLoop();
                                }
                                break;
                    case ']':   if (memory[dataPointer]) {
                                    progPointer = openLoops.back();
                                }
                                else {
                                    openLoops.pop_back();
                                }
                                break;
                    default:    break; /* Ignore all comments */
                }
            }
        }
};

Program Loader

BFProgram loadProgram(std::istream& program)
{
    std::string  programText;

    std::string line;
    while(std::getline(program, line))
    {
        line.erase(std::remove_if(std::begin(line), std::end(line), [](char c){return BFInterpretor::bfComment(c);}), std::end(line));
        programText.append(line);
    }
    return programText;
}
BFProgram loadProgram(std::string const& file)
{
    if (file == "-") {
        return loadProgram(std::cin);
    }
    std::ifstream   program(file);
    return loadProgram(program);
}

Main

int main(int argc, char* argv[])
{
    std::vector<std::string>    args(argv+1 , argv+argc);
    if (args.empty()) {
        args.push_back("-");
    }

    for(std::string const& file: args) {
        std::string     program = loadProgram(file);
        BFInterpretor   interpretor(program);
        interpretor.run();
    }
}


texts: Better importation of variables from .txt file


texts:
Consider this code segment:

if (empty($_GET)) {
    $page_number = 1;
} else {
    $page_number = $_GET["page_number"];
}

I wonder if there is a better, more succinct way to express that idea. I thought about using a ternary operator, but the improvement over the original is not substantial:

$page_number = empty($_GET) ? 1 : $_GET["page_number"];


texts: Finding the distance between two points in C++

texts:
I made a program in C++ where it calculates the distance between two coordinates. Is there anything to improve? Add? Make it more user-friendly?

Code:

 #include <iostream>
 #include <cmath>

using namespace std;

int ch;
double x;
double y;
double a;
double b;
double answer;

double distanceBetweenTwoPoints(double x, double y, double a, double b);

int main(){

        cout << "Enter the points for the coordinates";
        cout << endl;
        cout << "Point x for first coordinates: ";
        cin >> x;
        cout << endl;
        cout << endl;
        cout << "Point y for first coordinate: ";
        cin >> y;
        cout << endl;
        cout << endl;
        cout << "Point x for the second coordinate: ";
        cin >> a;
        cout << endl;
        cout << endl;
        cout << "Point y for the second coordinate: ";
        cin >> b;
        cout << endl;
        cout << endl;
        answer = distanceBetweenTwoPoints(x, y, a, b);
        cout << "The answer is " << answer;
}

double distanceBetweenTwoPoints(double x, double y, double a, double b){
return sqrt(pow(x - a, 2) + pow(y - b, 2));
}


texts:
I am still relatively new to Python but I have been actively doing sample examples to try and get used to problem solving aspect of programming.

With that said, I stumbled upon a question that asks you to write a code to convert DNA strand to its complementary form.

What I have written works, but I don't believe that my approach is efficient enough. Could you please review my code and guide me as to how I might improve on it? I feel like there will be a faster way than writing multiple if, elif statements.

import sys

def check_input(user_input):
    if len(user_input) == 0:
        sys.exit("No strand provided.")
    return user_input

def complementary(strand):
    complementary_strand = ''
    for dna in strand:
        if dna == 'A':
            complementary_strand += 'T'
        elif dna == 'a':
            complementary_strand += 't'
        elif dna == 'T':
            complementary_strand += 'A'
        elif dna == 't':
            complementary_strand += 'a'
        elif dna == 'G':
            complementary_strand += 'C'
        elif dna == 'g':
            complementary_strand += 'c'
        elif dna == 'C':
            complementary_strand += 'G'
        elif dna == 'c':
            complementary_strand += 'g'
        else:
            complementary_strand += 'x'
    return complementary_strand

if __name__ == "__main__":
    user_input = input("Enter strand: ")
    print()
    strand = check_input(user_input)
    complementary_strand = complementary(strand)
    print("Complementary strand is {}".format(complementary_strand))