texts:
Could you please review my script?

#!/bin/ksh
T=/bb/bdap/bin/cms/tools
U=$T/upgrader
mv $T/conbase_updates $U/conbase_updates.br.drqs$1
cd $U
grep "^BR" config.alpha > config.br
./ConbaseUpgrader config.br conbase_updates.br.drqs$1


texts: Determining if the movement of a robot is possible in a row

texts:
A robot can move in one step from cell X to cell Y if and only if the distance between the centers of the cells X and Y measured in meters is equal to the sum of integers contained in X and Y. It then returns the index of the cell which the above condition does not meet which is the index only [0, 1, 4] and its value is [3, 1, 0].

How can I improve my code and reduce the time complexity?

def row_walk(matrix):

    result = []
    x = []
    y = []
    for i, r1 in enumerate(matrix):
        y.append(i)
        for j, r2 in enumerate(matrix):
            if r1+r2 == abs(i-j) and not j <= i:
                x.append((i, j))
    result.append((list({el for tup in x for el in tup})))

    z = []
    for t1 in y:
        if t1 not in result[0]:
            z.append(t1)
    return z

if __name__=="__main__":
    matrix = [3, 1, 3, 2, 0, 0]
    print(row_walk(matrix))


texts: Freeing allocated memory: am I missing something?

texts:
If this question should be on stackoverflow instead, please point it out. I'll put it up there.

 struct {
      FILE * fd;
      hdr_t file_header;
      body_t file_body;
 } fileinfo;

The above is an approximate recreation of a structure that I have in my code. There is a separate function we use for thread cleanup. A pointer to the above structure is a parameter to this function.

 void cleanup(void * args)
 {
      struct fileinfo *file_ptr = (struct fileinfo *) args;

      if(file_ptr->fd > 0)
      {
           fclose(file_ptr->fd);
      }
      free(file_ptr);
  }

Does the free() - as called above - actually free all the memory allocated to file_ptr? Should there not be a free for the hdr_t and body_t as well?


texts: Euler Project #3 Largest prime factor timeout

texts:
I have been recently trying my hands on Euler's Project through HackerRank and got stuck with project #3 where you have to find the Largest Prime Factor.

Question: The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of a given number N?

I have written two different codes which both work for the first four problems in HackerRank but timeout on the last two. Please let me know how I can optimize my code further so that the timeout doesn't occur.

Code #1

for a in range(int(input())):
    n = int(input())
    b = n//2
    i=1
    if b%2==1:
        i+=1
    max=1
    while b > 2:
        if n%b==0:
            isprime = True
            for c in range(2,int(b**0.5)+1):
                if b%c==0:
                    isprime = False
                    break;
            if isprime:
                max = b
                break;
        b-=i
    if max==1:
        max=n
    print(max)

This one tries to find the first largest numbers which can divide a particular number and then tries to find whether it is a prime.

Code #2

for a in range(int(input())):
    n = int(input())
    num = n
    b = 2
    max=1
    while n > 1 and b < (num//2)+1:
        if n%b==0:
            n//=b
            max=b
        b+=1
    if max==1:
        max=n
    print(max)

This basically tries to find the last largest factor by multiple division.


texts:
I generally encounter a lot of if/else. I would like to get some suggestions on my code:

if( $blnLogged && isset( $_POST['postReview'] ) )
{
    if( $_SESSION['REVIEW']['SUBMITTED'] != '' )
    {
        $arrSharedData['blnRetSave'] = $_SESSION['REVIEW']['SUBMITTED'];
        $blnShowForm = false;
        $blnReviewPosted = true;
    }else{
        if( $arrData['captcha'] != $_SESSION['REVIEW']['CODE'] )
        {
            $strErrMsg = 'Invalid Captcha Code...';
        }else{
            if( empty( $arrData['review_title'] ) || empty( $arrData[ 'review_description' ] ) || empty( $arrData[ 'overall_review' ] ) || empty( $arrData[ 'cleanliness' ] ) || empty( $arrData[ 'facilities' ] ) || empty( $arrData[ 'location' ] ) || empty( $arrData[ 'quality_of_service' ] ) || empty( $arrData[ 'room' ] ) || empty( $arrData[ 'value_of_money' ]) )
            {
                $strErrMsg = 'Required field missing...';
            }else{

                //do we need any processing...
                $arrData['business_id'] = $bID;
                $arrData['client_id']   = $_SESSION['site_user'];
                $arrData['website_id']  = WEBSITE_ID;
                $arrData['review_date'] = date('Y-m-d');

                //If field Transformation required do it...

                $objTripReview = SM_Loader::loadClass('Class_Reviews');
                $blnRetSave = $objTripReview->saveReview( $arrData );
                $_SESSION['REVIEW']['SUBMITTED'] = $blnRetSave;
                $arrSharedData['blnRetSave'] = $_SESSION['REVIEW']['SUBMITTED'];
                $blnShowForm = false;
                $blnReviewPosted = true;
            }
        }
    }
}

if( $blnShowForm === true )
{
    $_SESSION['REVIEW']['CODE'] = rand(9999,99999);
    $_SESSION['Review']['SUBMITTED'] = '';
}


texts:
I tried to check if my vector struct is normalized, and I ended up with this code:

public bool IsNormalized
{
    get
    {
        double len = Length; // Math.Sqrt ((X * X) + (Y * Y) + (Z * Z)); -- X, Y, Z are in double format

        const double min = 1 - 1e-14;
        const double max = 1 + 1e-14;

        return (len >= min && len <= max);
    }
}

Is this solution OK? I read double has 15 digits precision, but 1+1E-15 give 1, so I changed to E14.

Is this all good? I need best accuracy.


texts: Traversing a JSON-like data structure in Go

texts:
In my code I need a function to traverse an arbitrary JSON-like data structure with a path definition. E.g., given the structure

{"root": {"inner": [{"name": "obj1"}, {"name": "obj2"}]}}

and the path ("root", "inner", "0", "name"} I would obtain "obj1". I just started learning Go and to be honest I found it quite hard to write it given the constraints imposed by Go's type system. Now it compiles and it seems to be working. To use it in my code, I needed additional helper functions with specific return types. All in all it seems to be a ugly hack with a lot of repetition. I'd like to see if this is the best one can do in Go.

Note: especially terrible is the distinction between map[string]string and map[string]interface{}. I though that interface{} would represent every type, but apparently not in this case. If I remove that part from the switch statement, the program does not work because map[string]string is not handled by the map[string]interface{} branch.

package main

import (
    "fmt"
    "strconv"
)

func main() {
    test := map[string]interface{}{
        "root": map[string]interface{}{
            "inner": []interface{}{
                map[string]string{"name": "obj1"},
                map[string]string{"name": "obj2"},
            },
        },
    }
    fmt.Println(TraverseToStr(test, []string{"root", "inner", "0", "name"}))
}

func TraverseToUint64(data interface{}, path []string) uint64 {
    val, err := Traverse(data, path)
    if err != nil {
        return 0
    } else {
        return val.(uint64)
    }
}

func TraverseToStr(data interface{}, path []string) string {
    val, err := Traverse(data, path)
    if err != nil {
        return ""
    } else {
        return val.(string)
    }
}

func TraverseToMap(data interface{}, path []string) map[string]interface{} {
    val, err := Traverse(data, path)
    if err != nil {
        return make(map[string]interface{})
    } else {
        return val.(map[string]interface{})
    }
}

func TraverseToArray(data interface{}, path []string) []interface{} {
    val, err := Traverse(data, path)
    if err != nil {
        return make([]interface{}, 0)
    } else {
        return val.([]interface{})
    }
}

func Traverse(data interface{}, path []string) (interface{}, error) {
    var ok bool
    current := data
    for _, p := range path {
        switch current.(type) {
        case map[string]string:
            if current, ok = current.(map[string]string)[p]; !ok {
                return nil, fmt.Errorf("key not found in map: %s", p)
            }
        case map[string]interface{}:
            if current, ok = current.(map[string]interface{})[p]; !ok {
                return nil, fmt.Errorf("key not found in map: %s", p)
            }
        case []interface{}:
            if i, err := strconv.ParseInt(p, 10, 64); err == nil {
                array := current.([]interface{})
                if int(i) < len(array) {
                    current = array[i]
                } else {
                    return nil, fmt.Errorf("index %d out of bounds for %v", i, array)
                }
            } else {
                return nil, fmt.Errorf("integer required, got: %s", p)
            }
        default:
            return nil, fmt.Errorf("cannot traverse %T\n", current)
        }
    }
    return current, nil
}
```


texts:
I wrote a program that approximates Pi by using polygons. I used the formulars in the picture beyond.
In my code they are called innerPoly (\$c_{2n}\$) and outerPoly (\$C_{2n}\$).

And since you can calculate the circumference of a 2n-polygon with knowing the circumference of a n-polygon you will get the circumferences \$C_8\$, \$C_{16}\$, \$C_{32}\$ etc., knowing \$C_4\$.

$$
\begin{array}{l}
c_{2n} =& 2 \sqrt{2n^2-n\sqrt{(2n)^2-c_n^2}} \qquad&\textrm{for the inner polygon, with}\ c_4=4\sqrt{2} \\
C_{2n} =& \frac{4 n C_n}{2n + \sqrt{(2n)^2 + C_n^2}} &\textrm{for the outer polygon, with}\ C_4=8
\end{array}
$$

My thoughts are:

Would it make it anyhow better when I have a function called void PiApproximation() that writes my values to stdout already? I mean technically you can always put your full code into the main()-function, but when you have to use the same code-parts over and over again you should make a own function of it and call it, when u need it.
So I guess in  this case it will make no difference if I use an own function or calculate the circumferences and print it in the main-function.
What else can I improve?

pi_approx.c

#include <stdio.h>
#include <math.h>

#define INNER_FOUR 4*sqrt(2); //circumference c_4 of the inner tetragon(square)
#define OUTER_FOUR 8 //circumference C_4 of the outer tetragon

int power(int n, int p);

int main(void)
{
  int n = 4;
  double innerPoly = INNER_FOUR;
  double outerPoly = OUTER_FOUR;

  printf("PI-APPROXIMATION USING POLYGONS\n");
  printf("===============================\n\n");
  printf("    n    I      c_n/2      I       C_n/2     I\n");
  printf("---------I-----------------I-----------------I\n");

  for (int i=3; n<=8192; n=power(i,2), i++)
  {
    printf("   %4d  I   %1.8lf    I    %1.8lf   I\n", n, innerPoly / 2, outerPoly / 2);

    innerPoly = 2 * sqrt(2 * n*n - n*sqrt(4 * n*n - innerPoly*innerPoly)); //formular c_2n
    outerPoly = (4 * n * outerPoly) / (2 * n + sqrt(4 * n*n + outerPoly*outerPoly)); //formular C_2n
  }

  return 0;
}

int power(int n, int p)
{

  int pBuffer = 1;

  for (int i=1; i <= n; i++)
  {
    pBuffer *= p;
  }

  return pBuffer;
}


texts:
This is my code to generate all possible Armstrong numbers between the two given numbers. The logic uses string instead of integer to separate the digits to optimize the code.

import java.util.Scanner;

public class ArmstrongNumberGenerator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int firstNumber;
        int lastNumber;
        int sum = 0;
        try {
            System.out.println("\nYou will have to enter initial and final number between which all the armstrong numbers you want to generate\n");
            System.out.println("\nEnter the initial number\n");
            firstNumber = scanner.nextInt();
            System.out.println("\nEnter the final number\n");
            lastNumber = scanner.nextInt();
            if (firstNumber == lastNumber) {
                System.out.println("both initian and final numbers are same , no range to generate armstrong numbers");
            } else {
                if (firstNumber > lastNumber) {
                    System.out.println("initial number is greater than final number so i will alter them and make a range from " + lastNumber + " to " + firstNumber);
                    int temp = firstNumber;
                    firstNumber = lastNumber;
                    lastNumber = temp;
                }
                do {
                    String s = Integer.toString(firstNumber);
                    char[] c = s.toCharArray();
                    for (int i = 0; i < s.length(); i++) {
                        sum = ( int ) (sum + Math.pow((c[i] - 48), c.length));
                    }

                    if (sum == firstNumber) {
                        System.out.println("Number " + firstNumber + " is Armstrong");
                    }
                    ++firstNumber;

                    sum = 0;
                } while (firstNumber < lastNumber);

            }
        } catch (Exception e) {
            System.out.println("invalid data");
        }

    }
}


texts: Hash function in C for sets and associative arrays

texts:
I wrote a non-cryptographic hash function in C, which I am hoping might be suitable for use in an implementation of hash sets or hash maps.

uint_fast32_t hash_u32(uint_fast32_t x) {
    uint_fast32_t h = x;
    h = h ^ (h>>16);
    h = h * 0xae6a495b;
    h = h ^ (h<<16);
    h = h * 0xae6a495b;
    return h;
}

I've tested this integrated into a set implementation before, which can be seen here, and it seems to be working fine, but I'm interested in knowing whether this is a good approach to integer hashing, or general hashing assuming all problem domains can be reduced to map the value to an integer and then hash that.


texts: NinjectWebCommon implementation/translation - C# to F#

texts:
I've translated this code from c# and would like it to be more idiomatic f#:

namespace Foo.App_Start

open System
open System.Web

open Microsoft.Web.Infrastructure.DynamicModuleHelper

open Ninject
open Ninject.Web.Common

type NinjectResolver(kernel:IKernel) =
    let _kernel = kernel
    interface System.Web.Http.Dependencies.IDependencyResolver with
        member this.BeginScope():Http.Dependencies.IDependencyScope = upcast this
        member this.GetService(t) =
            _kernel.TryGet(t)
        member this.GetServices(t)=
            _kernel.GetAll(t)
        member this.Dispose() = ()

//was static
[<AbstractClass; Sealed>]
type NinjectWebCommon () =
    static let bootstrapper = new Bootstrapper()

        /// <summary>
        /// Load your modules or register your services here!
        /// </summary>
        /// <param name="kernel">The kernel.</param>
    //private static void RegisterServices(IKernel kernel)
    static let RegisterServices(kernel:IKernel) =
        System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver <- new NinjectResolver(kernel)
        do()
        /// <summary>
        /// Creates the kernel that will manage your application.
        /// </summary>
        /// <returns>The created kernel.</returns>
        //private static IKernel CreateKernel()
    static let KernelCreation(kernel:IKernel) =
        System.Diagnostics.Debug.WriteLine "kernel Creation!"
        RegisterServices(kernel)
        let bs = fun () -> new Bootstrapper()
        let kernelFun= System.Func<IKernel> (fun () -> bs().Kernel)
        kernel.Bind<System.Func<IKernel>>().ToMethod(fun ac -> kernelFun) |> ignore
        kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>() |> ignore
        let fetchedKernel:IKernel =System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof<IKernel>) :?> IKernel
        fetchedKernel

    static let CreateKernel():IKernel =
        System.Diagnostics.Debug.WriteLine "standard kernel creating!"
        let kernel= new StandardKernel()
//
        try         //RegisterServices(kernel) |> ignore;
            KernelCreation(kernel)
        with
            | ex ->
                System.Diagnostics.Debug.WriteLine "kernel disposing!"
                kernel.Dispose()
                raise ex

    /// <summary>
    /// Starts the application
    /// </summary>
    static member Start() =
        DynamicModuleUtility.RegisterModule typedefof<OnePerRequestHttpModule> |> ignore
        DynamicModuleUtility.RegisterModule typedefof<NinjectHttpModule> |> ignore
        bootstrapper.Initialize(System.Func<_>(CreateKernel))
        System.Diagnostics.Debug.WriteLine "app Start()"
//
//
    /// <summary>
    /// Stops the application.
    /// </summary>
    static member Stop() =
        System.Diagnostics.Debug.WriteLine "app stop"
        bootstrapper.ShutDown()

module DummyModuleToAttachAssemblyAttribute =
    [<assembly: WebActivatorEx.PreApplicationStartMethod(typeof<NinjectWebCommon>, "Start")>]
    ////[assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(FLochart.App_Start.NinjectWebCommon), "Stop")]
    [<assembly: WebActivatorEx.ApplicationShutdownMethod(typeof<NinjectWebCommon>, "Stop")>]
    do()


texts:
Here I have a class where I'm checking if model_id exists in the table models_web_tbl.

Everything works like a charm but I just want to know if I'm on the right path.

class test extends dbh{

public function modelExist($model_id) {

$sql = "SELECT * FROM models_web_tbl WHERE model_id = ?";

    $stmt = $this->connect()->prepare($sql);
    $stmt->execute([$model_id]);
    $match = $stmt->fetch(PDO::FETCH_OBJ);

        if ($match > 0){

            echo "found";

        }else {

            $model_web_twitter = "twitter";

            $sql = "INSERT INTO models_web_tbl (model_web_twitter, model_id) VALUES (?, ?)";
            $stmt = $this->connect()->prepare($sql);
            $stmt->execute([$model_web_twitter, $model_id]);

            }

}
}
$model_id = 66;
$exist = new test ();
$exist = $exist->modelExist($model_id);


texts: Can I simplify my Restaurant MenuCard program?

texts:
Here is my task: Create classes for a menu plan. With the help of the classes it should be possible to create a menu card for a restaurant in a hotel.
There should be a 'MenuCard' class for this purpose. This should include a date for the card and one or more course menus. Use an appropriate data type in Python for the date. It should be possible to add the courses to a menu card one after the other with a method add_course. There should be a class 'Course' for the course menu. This has a name (e.g. starter or first course). Furthermore, each course has one or more dishes, which can be added with the 'add_dish' method. For this purpose, the 'Dish' class is to be assembled, which is the name of the food administration and whether it is vegetarian. Use the str function in all classes to display the menu card on the screen.
Additional task: Create a class for a three-course menu ThreeCourseMenuCard, which the existing class sequences. With this class you have to make sure that there are no more than (or exactly) three courses.
Create your own personal map by controlling instances from the classes.
I already programmed this, but its to complicated for some users i know. Can someone give me any ideas on how to simplify this program. Thank you in advance.
Here is my code:
#! /usr/bin/python3
import datetime, locale

class Dish():
    def __init__(self, name, veggy):
        self.__name = name
        self.__veggy = veggy
    def __str__(self):
        if self.__veggy == bool(1):
            return "{} (vegetarisch)".format(self.__name)
        else:
            return "{}".format(self.__name)

class Course():
    def __init__(self, name):
        self.__name = name
    def add_dish(self):
        for i in range(len(self.__name[1])):
            print(Dish(self.__name[1][i][0], self.__name[1][i][1]))
            if i < len(self.__name[1])-1:
                print("oder")
    def __str__(self):
        return "\n\n{}\n".format(self.__name[0][0])

class MenuCard():
    def __init__(self, date):
        self.__date = date.strftime('%A, %d.%m.%Y')
    def add_course(self, new_course):
        print(Course(new_course))
        Course(new_course).add_dish()
    def __str__(self):
        return "\n\nMenukarte fuer {}".format(self.__date)

vorspeise =     [["Vorspeise"],[
                ["Carpaggio vom Rind auf knackigem Blattsalat", 0],
                ["Honigmelone mit hausgemachtem Speck vom Hängebauchschwein", 0]
                ]]

suppe =         [["Suppe"],[
                ["Kräftige Rindssuppe mit Eiertörtchen", 1]
                ]]

erster_gang =   [["1. Gang"],[
                ["Salat vom Buffet", 0]
                ]]

zweiter_gang =  [["2. Gang"],[
                ["Wiener Schnitzel mit Kartoffelsalat", 0],
                ["Wildsaibling an Herbstgemüse auf Safranrisotto", 0],
                ["Saftiges Hirschgulasch mit Kastanienrotkraut und Semmelknödel", 0],
                ["Spinatlasagne mit frischen Tomaten", 1]
                ]]

nachspeise =    [["Nachspeise"],[
                ["Vanilleparfait auf Himbeerspiegel", 1],
                ["Luftige Topfenknödel mit roter Grütze", 0]
                ]]

locale.setlocale(locale.LC_ALL, 'de_DE.utf8')
menu = MenuCard(datetime.datetime(2020, 11, 9))
print(menu)

gaenge = [vorspeise, suppe, erster_gang, zweiter_gang, nachspeise]

for gang in gaenge:
    menu.add_course(gang)
```


texts:
1.11 Arranging the derivative of a function
  The derivative of any function f (x) at x0 can be estimated according to the following formula:

  Write a program that prints three columns of numbers: x, f (x) and the derivative f '(x) for some simple functions, e.g. sin (x) or arctan(x).

public static class Derrivative
{
    public static double Compute(Func<double, double> f, double x0, double h)
    {
        return (f(x0+h) - f(x0-h)) / (2*h);
    }
}

class Program
{
    static void Main(string[] args)
    {
        const int N = 10;

        Console.WriteLine("Derivative of sin(x)");

        Func<double, double> function = Math.Sin;

        for (int i = 0; i < N; i++)
        {
            Console.WriteLine($"{i}\t{function(i)}\t{Derrivative.Compute(function, i, 0.5)}");
        }

        Console.WriteLine();

        Console.WriteLine("Derivative of arctan(x)");

        function = Math.Atan;

        for (int i = 0; i < N; i++)
        {
            Console.WriteLine($"{i}\t{function(i)}\t{Derrivative.Compute(function, i, 0.5)}");
        }

        Console.ReadLine();
    }
}

Kindly, review this source code.


texts:
I'm re-designing the login functionality for our application, and the first thing I came across is something a previous developer wrote a while back. There's a simple Login class that just contains 2 strings, username and password, and an enum LoginStatus:

public enum LoginStatus
{
    LoggedIn,
    LoggedOut
}

I'm thinking it would be better to just use a bool here, but maybe there's something more here that I'm not understanding?

In my opinion, it is slower and more confusing to read:

if (login.LoginStatus == LoginStatus.LoggedIn)
{
    ...
}

It would seem a lot better to just write:

if (login.loggedIn) { ... }

or

if (!login.loggedIn) { ... }

I already tested it in my branch and changed everything accordingly. Everything still works normally, so the new Login class looks like this:

public class Login
{
    public string username { get; set; }
    public string password { get; set; }
    public bool loggedIn { get; set; }
}

Is there any specific reason one would want to use enum over bool in this instance? Performance, readability, ease of future expansions, or any other overhead my young mind may not be seeing?


texts:
I have working code here which takes two lists and turns them into a dictionary with the first list being the keys and the second being the values. If the keys exceed the values the value "None" will be assigned to that key.

def createDict(keys, values):
    i = 0
    dictionary = {}

    # go through all the values in the first list
    for key in keys:
        # if our keys index is equal or exceeds our value list's length
        # then extend the list with a None value
        if i >= len(values):
            values.extend([None])
        dictionary[key] = values[i]
        i = i + 1
    return dictionary

I was hoping for to get some feedback.


texts:
I'm a new programmer and I'm periodically going into the Intro To Algorithms CLRS textbook and trying to translate pseudocode into Ruby for skill practice. This is my implementation/translation of insertion sort.
I'm looking for feedback on readability as well as efficiency.
Pseudocode is found on page 17 of Intro To Algorithms Second Edition just in case you happen to have it lying around, more interested in the feedback just on the code itself.
class InsertionSort
    attr_accessor :arr
    def initialize(arr)
      @arr = arr
    end

    def sort
      key = 1
      to_the_left = key - 1

      while key < self.arr.length
        if arr[key] < arr[to_the_left]

          mover_key = key
          left_ele_moving_right = to_the_left

          until arr[mover_key] > arr[left_ele_moving_right] || left_ele_moving_right < 0

            arr[left_ele_moving_right], arr[mover_key] =
            arr[mover_key], arr[left_ele_moving_right]

              mover_key -= 1
              left_ele_moving_right -= 1
          end
        end

        key += 1
        to_the_left += 1
      end

      self.arr
    end
end

```


texts: Is this the right way to implement a hashmap?

texts:
Is this the right way? Any comments on the hash functions? If asked a question like this in an interview, do I need to follow all OOP concepts(because I am using Java)? Like encapsulating the variables by writing getter and setter functions?

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class HashMapY<K,V> {
    private static int capacity = 100;
    private Map[] arr;
    private int size;

    public HashMapY () {
        arr = (Map[]) Array.newInstance(Map.class, capacity);
        size = 0;
    }

    public V get(Object key) {
        assert key!=null;
        int i = -1;
        if (key instanceof String || key instanceof Character){
            i = hash(key.toString(), capacity) % capacity;
        }
        if (key instanceof Integer)
            i = hash(Integer.parseInt(key.toString()))%capacity;
        while (!key.equals(arr[i].k) && i < capacity)
            i = (i+1)%capacity;
        return arr[i]==null ? null : arr[i].v;
    }

    public int hash(String value, int maxValue) {
        long hash = doHash(value);
        return (int) Math.abs(hash % maxValue);
    }

    private int hash(int k) {
        k *= 357913941;
        k ^= k << 24;
        k += ~357913941;
        k ^= k >> 31;
        k ^= k << 31;
        return k;
    }

    private long doHash(String str) {
        long hash = 5381;

        for (int i = 0; i < str.length(); i++) {
            hash = ((hash << 5) + hash) + str.charAt(i);
        }

        return hash;
    }
    public boolean isEmpty() {
        return size==0;
    }

    public void put(K key, V value) {
        assert key != null;
        int i=-1;
        if (key instanceof String || key instanceof Character){
            i = hash(key.toString(), capacity) % capacity;
        }
        if (key instanceof Integer)
            i = hash(Integer.parseInt(key.toString()))%capacity;
        while (arr[i]!=null) {
            i = (i+1);
        }
        if(arr[i] == null) {
            size++;
        }
        arr[i] = new Map(key, value);
    }

    public V remove(Object key) {
        List<Map> pairs = new ArrayList<Map>();
        assert key!=null;
        int i = -1;
        if (key instanceof String || key instanceof Character)
            i = hash(key.toString(), capacity) % capacity;
        if (key instanceof Integer)
            i = hash(Integer.parseInt(key.toString()))%capacity;
        while (!arr[i].k.equals(key) && capacity > i){
            i = i + 1;
        }
        if (capacity >= i){
            Object temp = arr[i].v;
            while (arr[i]!= null && arr[i].k.equals(key)){

                pairs.add(arr[i]);
                arr[i] = null;
                size--;
            }
            for (Map m : pairs){
                this.put(m.k, m.v);
            }
            return (V) temp;
        }
        return null;
    }

    public int size() {
        return size;
    }

    class Map {
        K k;
        V v;

        public Map(K key, V val){
            k = key;
            v = val;
        }
    }

    public boolean containsKey(K key) {
        assert key!=null;
        int i = -1;
        if (key instanceof String || key instanceof Character)
            i = hash(key.toString(), capacity) % capacity;
        if (key instanceof Integer)
            i = hash(Integer.parseInt(key.toString()))%capacity;
        if (arr[i] == null) return false;
        while (i<capacity && !arr[i].k.equals(key)){
            i = i+1;
        }
        return i<capacity;
    }

    public Set<K> keySet() {
        Set<K> set = new HashSet<K>();
        for (Map m : arr){
            if (m != null){
                set.add(m.k);
            }
        }
        return set;
    }

}


texts:
This program attempts to shows the basic concepts of inheritance and polymorphism.  In what ways could the code be modified to better demonstrate those concepts? The interface, abstract class and the class are all in separate files.

Greeting Interface

interface Greeting {
    void sayHello(String greeting, String name);
}

Abstract Hello Class

abstract class Hello {
    String name;
    String greeting;
    public abstract void setName(String name);
    public abstract void setGreeting(String greeting);
    public abstract String getName();
    public abstract String getGreeting();
}

Class that says "Hello"

public class Test extends Hello implements Greeting {
    private String name;
    private String greeting;

    public void setName(String name) {
    this.name = name;
    }
    public void setGreeting(String greeting) {
    this.greeting = greeting;
    }
    public String getName() {
    return name;
    }
    public String getGreeting() {
    return greeting;
    }
    public void sayHello(String g, String n) {
    System.out.print(g + " " + n);
    }
    public static void main(String[] args) {
    Test t = new Test();
    t.setGreeting("Hello");
    t.setName("World!");
    String h = t.getGreeting();
    String w = t.getName();
    t.sayHello(h,w);

    }
}


texts:
I have an inner class for filtering:
private class RegSpecification implements Specification<Reg> {

    private final transient RegFilterDTO filter;
    private transient Predicate predicate;
    private transient CriteriaBuilder cb;

    public RegSpecification(RegFilterDTO filter) {
        this.filter = filter;
    }

    @Override
    public Predicate toPredicate(Root<Reg> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
        // this.cb = cb;
        this.predicate = cb.conjunction();

        Join<Reg, Acct> userJoin = root.join(acct, JoinType.INNER);

        predicate = eqEnumVal(predicate, cb, root.get(regType), RegType.class, filter.getRegType());
        predicate = eq(predicate, cb, userJoin.get(Acct_.id), filter.getAcctId());
        predicate = like(predicate, cb, root.get(regNumber), filter.getRegNumber());

        return predicate;
    }
}

And I made a helper class, to be used by other class as well who implements filtering by Specification (methods are public since some services are in other packages):
public class PredicateBuilder {

    public static Predicate like(Predicate predicate, CriteriaBuilder cb, Path<String> path, String value) {
        if (StringUtils.isNotEmpty(value)) {
            return cb.and(predicate, cb.like(cb.lower(path), "%" + value.toLowerCase() + "%"));
        }
        return predicate;
    }

    public static <T> Predicate eq(Predicate predicate, CriteriaBuilder cb, Path<T> path, T value) {
        if (value != null) {
            return cb.and(predicate, cb.equal(path, value));
        }
        return predicate;
    }

    public static <T extends Enum<T>> Predicate eqEnumVal(Predicate predicate, CriteriaBuilder cb,
                                                          Path<T> path, Class<T> enumType, String name) {
        if (StringUtils.isNotEmpty(name)) {
            return eq(predicate, cb, path, Enum.valueOf(enumType, name));
        }
        return predicate;
    }

}

Question is
Can I use private local variables in my RegSpecification so I won't have to use predicate = ... every time I call the helper class and some generic method to pass the predicate and cb to the helper class (so I won't have to pass the predicate and cb in my helper class methods)?
Where I could just do something like:
PredicateBuilder.with(predicate, cb)
   ...
   like(userJoin.get(Acct_.id), filter.getAcctId());
   eq(userJoin.get(Acct_.id), filter.getAcctId());
   like(root.get(regNumber), filter.getRegNumber());
   ...
.build();

in my toPredicate method.
Or any suggestions to make the code cleaner?
(Should I also annotate the helper class with @Component?)


texts: Dijkstra in C++ to find shortest path for every vertex of a directed graph

texts:
I am trying to implement the Dijkstra algorithm in C++ that finds the shortest path for a graph from a text file. The text file contains a matrix that represents a directed graph.

What I am trying to do in this code is use every vertex as the source. I finished the code but I am still very skeptical if my code is right or not.

int minDistance(int dist[], bool sptSet[], int V)
{
// Initialize min value
int min = INT_MAX, min_index;

for (int v = 0; v < V; v++)
    if (sptSet[v] == false && dist[v] <= min)
        min = dist[v], min_index = v;

return min_index;}
double  dijkstra(int vertex, int **graph, int src)
{
auto start_time = chrono::high_resolution_clock::now();
int* dist = new int[vertex];     // The output array.  dist[i] will hold the shortest
// distance from src to i

bool* sptSet = new bool[vertex]; // sptSet[i] will true if vertex i is included in shortest
// path tree or shortest distance from src to i is finalized

src = k;
// Initialize all distances as INFINITE and stpSet[] as false
for (int i = 0; i < vertex; i++)
    {
    dist[i] = INT_MAX, sptSet[i] = false;
    }

// Distance of source vertex from itself is always 0
dist[src] = 0;

// Find shortest path for all vertices
    for (int count = 0; count < vertex - 1; count++)
    {
    // Pick the minimum distance vertex from the set of vertices not
    // yet processed. u is always equal to src in first iteration.
    int u = minDistance(dist, sptSet, vertex);

    // Mark the picked vertex as processed
    sptSet[u] = true;

    // Update dist value of the adjacent vertices of the picked vertex.
    for (int v = 0; v < vertex; v++)

        // Update dist[v] only if is not in sptSet, there is an edge from
        // u to v, and total weight of path from src to  v through u is
        // smaller than current value of dist[v]
        if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX && dist[u] + graph[u][v] < dist[v])
        {
        dist[v] = dist[u] + graph[u][v];
        }
    }
k++;
delete[] dist;
delete[] sptSet;
}

auto end_time = chrono::high_resolution_clock::now();
double elapsed = chrono::duration_cast<chrono::milliseconds>(end_time - start_time).count();

return elapsed;
}


texts:
I have written a small library for saving data on local storage. I am still a learner and I am not sure whether my code is OK for a production level application.

function AppStorage (aName) {
    "use strict";

    var prefix  = aName;

    var saveItem = function (key, value) {

        if (!key || !value) {

            console.error("Missing parameters \"key\" and \"value\"");

            return false;
        }

        if (window.localStorage && window['localStorage']) {

            try {

                localStorage.setItem(prefix + '_' + key, JSON.stringify(value));

            } catch (e) {

                return false;

            }

        } else  {

            return false;

        }

    }

    var getItem = function (key) {

        if (!key) {

            console.error("Missing parameter \"key\"");

            return false;
        }

        if (window.localStorage && window['localStorage']) {
            try {

                localStorage.getItem(prefix + '_' + key);

            } catch (e) {

                return false;

            }

        } else  {

            return false;

        }

    }

    var removeItem = function (key) {

        if (!key) {

            console.error("Missing parameter \"key\"");

            return false;
        }

        if (window.localStorage && window['localStorage']) {

            try {
                return localStorage.removeItem(prefix + '_' + key)
            } catch (e) {
                return false;
            }

        } else  {

            console.log("Browser doen not support HTML5 Web Storage");

        }

    }

    return {
        set: function (key, value) {
            return saveItem(key, value);
        },
        get: function () {
            return getItem(key, item);
        },
        remove: function () {

        }
    }

}

var as = new AppStorage ('MyApp');


texts: IPC The sleeping barber problem in C feedback

texts:
I would love to get some feedback on this Sleeping barber implementation in C.
the entire project can be found here: https://github.com/T0iS/sleeping-barber
    How to run.

1. make
2. start the server on a selected port ( ./server XXXX)
3. start the client on localhost and connect to the previously specified port (./holic_cl localhost XXXX)

I would love to hear some advice on the code quality in general, what to do, what not to do and/or how could I improve the code stability and quality or readability as well.
Editing the question and specifying the code parts, did not know about that rule, thanks for letting me know.
The most important parts are these.
The readline function that reads a line from a FD
int readline(fdStruct& fd, char* buf){

    int ret, mv;
    char temp[256];
    bzero(temp, sizeof(temp));
    char* t = NULL;

    while(1){
        bzero(temp, sizeof(temp));
        bzero(buf,sizeof(buf));

        ret = read(fd.fd, &temp, 256 - sizeof(strlen(fd.BUF)));
        if (ret > 0 ){
            temp[ret] = '\0';
        }

        strcat(fd.BUF, temp);
        t = strchr(fd.BUF,'\n');

        if (t != NULL){
            mv = t-fd.BUF+1;
            strncpy(buf,fd.BUF, mv);
            strcpy(fd.BUF,fd.BUF+mv);
            return strlen(buf);
        }
        if (ret <= 0) {

            if (strlen(fd.BUF) == 0){
                return ret;
            }
            strcpy(buf, fd.BUF);
            strcpy(fd.BUF,fd.BUF+strlen(buf));
            return strlen(buf);
        }
    }
}

The other one the actual barber code (and also the customer one, not including that one since it would be too long)
void* holic(void* arg){

    if(global_data->child_count>0){
        close(comPipe[1]);
    }
    log_msg(LOG_INFO, "Getting to work..");

    msg m;
    char l[256];
    int val_check = -1;
    int cut_time = 0;

    global_data->customer_count = 0;

    while(1){

        sem_getvalue(sem_customers, &val_check);
        if (val_check==0){
            log_msg(LOG_INFO,"Sleeping..");
        }

        sem_wait(sem_customers);

        log_msg(LOG_INFO, "Woke up, start cutting..");
        global_data->customer_count -= 1;

        sem_post(sem_barber);

        bzero(l,sizeof(l));
        bzero(m.text, sizeof(m.text));
        log_msg(LOG_INFO, "barber before read %d", fd_pipe.fd);

        int tmp = read(comPipe[0], l, sizeof(l));
        l[tmp] = '\0';
        //wait_for_message(fd_pipe,l,&m,'A', AI_Zakazka);

        sscanf(l, "Cut me for %d seconds", &cut_time);
        global_data->chairs[global_data->last_chair] = 0;
        log_msg(LOG_INFO, "Cutting hair, customer on chair %d, duration %d sec.",global_data->last_chair, cut_time);

        sleep(cut_time);
        sem_post(sem_cutting);

        bzero(l,sizeof(l));
        bzero(m.text, sizeof(m.text));

        wait_for_message(fd_pipe,l,&m,'A', AI_Nashledanou);
        log_msg(LOG_INFO, "Goodbye.");

    }
    if (global_data->child_count>0){
        close(comPipe[0]);
    }
}

Thanks for every input!


texts: Can I improve this progressive enhancement?

texts:
I'm attempting to make a nice-looking UI where a user views current items in a list and can add/edit/delete.

For each item, i've included an edit and delete link, but I'm trying to do so in such a way as to gracefully degrade/progressively enhance:

My Course Name

    ✎ Edit
    ✕ Remove

The idea is that for accessibility users/css-haters/lynx-users/really-really old browsers, the link displays as "✎ Edit" - clear and obvious as to the meaning:

Then, with CSS, I tweak it so only the ✎ and ✕ is visible, in a sort of iconic format:

My Question: is this a good approach to graceful degradation and progressive enhancement, and/or could it be improved?

P.S: I have a tiny feeling this might not be 100% appropriate for Code Review - so apologies if its not; we can always migrate/close, right?

Also, CSS:

.tools {
        float:right;
        clear:both;
        height:1em;
        overflow:hidden;
        margin:0;
        width:auto;
        border:none;
    }
    .tool {
        float:left;
        width:1em;
        height:1em;
        overflow:hidden;
        color:black;
        text-decoration:none;
    }


texts: Wrapper functions for terminal capabilities

texts:
I've prepared a small C interface so the rest of my program can access relevant system functions.  I am not a C programmer, though - just C++ and D, mainly.  I want to make sure that everything here is "C-ish" before committing the rest of my code to this interface.

This is just a plain old C file, compiled with a C compiler (as opposed to C++).

    /*
     * This file provides functions to interface with
     * low-level terminal properties such as size and
     * input modes.  Functions meant to be accessible
     * to external "user" code begin with "Terminal."
     */

#include <sys/ioctl.h> // For interfacing with the terminal device.
#include <termios.h> // Ditto.
#include <unistd.h> // For the STDIN_FILENO file descriptor macro.

// This is just used internally, and should not be called directly from D code.
struct winsize Size()
{
    struct winsize Size;
    ioctl(STDIN_FILENO, TIOCGWINSZ, &Size);
    return Size;
}

unsigned short int TerminalColumnCount()
{
    return Size().ws_col;
}

unsigned short int TerminalRowCount()
{
    return Size().ws_row;
}

// Used to reset the terminal properties to their original state.
// Again, this is only for internal use.
struct termios BackupProperties;

// Removes terminal input buffering so programs can see typed characters before Enter is pressed.
void TerminalMakeRaw() // I wish I could come up with a better name for this.
{
    tcgetattr(STDIN_FILENO, &BackupProperties);
    struct termios NewProperties;
    cfmakeraw(&NewProperties);
    tcsetattr(STDIN_FILENO, TCSANOW, &NewProperties);
}

void TerminalReset()
{
    tcsetattr(STDIN_FILENO, TCSANOW, &BackupProperties);
}


texts: Convert tree to circular doubly linked list

texts:
I want you to pick my code apart and give me some feedback on how I could make it better or simpler.  This code converts a binary tree to a doubly linked list (in order).

public class BinaryTreeToLinkedList {

    private TreeNode root;

    private static class TreeNode {
        TreeNode left;
        TreeNode right;
        int item;
        public TreeNode(TreeNode left, TreeNode right, int item) {
            this.left = left;
            this.right = right;
            this.item = item;
        }
    }

    private TreeNode appendDLL (TreeNode left, TreeNode right) {
        if (left == null) return right;
        if (right == null) return left;

        // get last element of left linkedlist
        TreeNode leftLast = left.left;
        TreeNode rightLast = right.left;

        leftLast.right = right;
        right.left = leftLast;

        // now we form the list into circular again.
        rightLast.right = left;
        left.left = rightLast;

        return left;
    }

    private TreeNode postOrder(TreeNode node) {
        if (node == null) {
            return null;
        }

        TreeNode leftList = postOrder(node.left);
        TreeNode rightList = postOrder(node.right);

        // convert the current node into doubly LL
        node.left = node;
        node.right = node;

        // hook current node.
        leftList = appendDLL (leftList, node);

        // hook right side linkedlist
        leftList = appendDLL (leftList, rightList);

        return leftList;
    }

  public void convertToLinkedList() {
            root = postOrder(root);
        }
    }


texts: Dynamically adding QLineEdits and then copy text from them to vector in right order

texts:
Here is how it looks at the beginning:

And after I can add random counts of line edits:

Or delete them:

The main purpose is the possibility to add or delete QlineEdits which stores user names and each QlineEdit adds a username to the vector in the right order (index) like this:

users =>
 [0] = "a";
 [1] = "b";
 [2] = "c";
 [3] = "d";
 [4] = "e";
 [5] = "f";
 [6] = "g";

Here is the code :
mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLineEdit>
#include <QPushButton>
#include <QList>
#include <vector>
class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private slots:
    void addbutton_Clicked();
    void deletebutton_Clicked();
    void lineedit_textChanged(QString text);

private:
    QVBoxLayout *middlelayout;
    QList<QLineEdit*> qlist;
    std::vector<QString> users;
};

#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent)
{
    QWidget window = new QWidget(this);
    QVBoxLayout *mainlayout = new QVBoxLayout;
    middlelayout = new QVBoxLayout;
    QHBoxLayout *buttonlayout = new QHBoxLayout;
    QPushButton *addbutton = new QPushButton;
    QPushButton *deletebutton = new QPushButton;

    addbutton->setText("ADD");
    deletebutton->setText("Delete");

    buttonlayout->addWidget(addbutton);
    buttonlayout->addWidget(deletebutton);
    buttonlayout->setAlignment(Qt::AlignTop);
    mainlayout->addLayout(buttonlayout);
    mainlayout->addLayout(middlelayout);
    window->setLayout(mainlayout);
    setCentralWidget(window);

    connect(addbutton, SIGNAL(clicked()), SLOT(addbutton_Clicked()));
    connect(deletebutton, SIGNAL(clicked()), SLOT(deletebutton_Clicked()));
}

MainWindow::~MainWindow()
{
}

void MainWindow::addbutton_Clicked()
{
    QLineEdit *lineedit = new QLineEdit;
    qlist.push_back(lineedit);
    middlelayout->addWidget(lineedit);
    lineedit->setObjectName("lineedit"+QString::number(qlist.count()));

    users.resize(qlist.count());
    connect(lineedit, SIGNAL(textChanged(QString)), SLOT(lineedit_textChanged(QString)));
}

void MainWindow::deletebutton_Clicked()
{
    QWidget *child;
    if(!middlelayout->isEmpty())
        if((child = middlelayout->takeAt(qlist.count()-1)->widget()) != 0) {
            delete child;
            qlist.removeLast();
    }
}

void MainWindow::lineedit_textChanged(QString text)
{
    unsigned int index = 0;
    QObject *obj = QObject::sender();
    QString senderobjName = obj->objectName();
    int isTextchanged = senderobjName.indexOf("lineedit") != -1;

    if(isTextchanged)
    {
        QStringList list = senderobjName.split("lineedit");
        index = list[1].toInt();
        users[index]=text;
    }
}

The code works fine but it seems that I'm doing it wrong and there is a better way.


texts: CodeEval Challenge: Remove specified characters from a string

texts:
Question

  Write a program which removes specific characters from a string.
  The first argument is a path to a file. The file contains the source
  strings and the characters that need to be scrubbed. Each source
  string and characters you need to scrub are delimited by comma.

  Input sample:

  how are you, abc
  hello world, def

  Output sample:

  how re you
  hllo worl

I have used regex to eliminate the characters.

public class Main{

    public static void main(String[] args) throws IOException {
        File file = new File(args[0]);
        BufferedReader br = new BufferedReader(new FileReader(file));
            String s;
            while ((s = br.readLine()) != null) {
                s = s.trim();
                String arr[]=s.split(",\\s");
                String pat="([^"+arr[1]+"])";
                Pattern p=Pattern.compile(pat);
                Matcher m=p.matcher(arr[0]);
                while(m.find())
                {
                    System.out.print(m.group(0));
                }
                System.out.println();
            }
            br.close();
        }

    }

The above code passes all the test cases.
Is this the most optimized code or can it be improved further?


texts: Performing operations on a processed int vector

texts:
This question came from C++ Primer 5th edition:

  Q: Read a set of integers into a vector. Print the sum of each pair of
  adjacent elements. Change your program so that it prints the sum of
  the first and last elements, followed by the sum of the second and
  second-tolast, and so on.

I was just wondering if there is any way to improve my solution.

Part 1:

int main(){

    vector<int> intVector;
    int number;
    while (cin >> number){
        intVector.push_back(number);
    }
    for (int i = 0; i < intVector.size(); i++){
        int k;
        k = intVector[i] + intVector[i + 1];
        cout << k << endl;
    }
    return 0;
}

Part 2:

int main(){

    vector<int> intVector;
    int number;
    while (cin >> number) {
        intVector.push_back(number);
    }
    int sizeOfIntVector = intVector.size();
    for(int i = 0; i < sizeOfIntVector / 2; i++){
        int k;
        k = intVector[i] + intVector[sizeOfIntVector - 1 - i];
        cout << k << endl;
    }

    return 0;
}


texts:
I am trying to show the following results to the user

  All:8000 enabled:8000 disabled:0

What can I do to improve this code?

$Val = explode(",", urldecode($_POST['Val']));
$table = mysqliChkData($Val[0]);

$addSQL = '';
if (!empty($Val[2])) {
  // parrent.guid
  $addSQL.= " and up_cls='".mysqliChkData($Val[2])."'";
}

$getSQL = "Select guid From `".$table."` Where 1=1".$addSQL." GROUP BY guid";
$listData = $sql->Select($getSQL);
$arr['allNum'] = $listData['num'];

$getSQL = "Select guid From `".$table."` Where `chk`='Y'".$addSQL." GROUP BY guid";
$listData = $sql->Select($getSQL);
$arr['openNum'] = $listData['num'];
$arr['closeNum'] = $arr['allNum'] - $arr['openNum'];

echo json_encode($arr);
exit;

Same records but different languages will have same guid.

Child tables have up_cls column.

Few tables don't have chk column because no need to disable.

CREATE TABLE tablee (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `lang` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `chk` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `date` datetime DEFAULT NULL,
  `guid` varchar(64) COLLATE utf8mb4_unicode_ci NOT NULL,
  `modify_date` timestamp NOT NULL DEFAULT '1970-12-31 16:00:00' ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`,`guid`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=28 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ROW_FORMAT=COMPACT;

method Select

function Select($sql) {
  global $mysqli;
  $reData = array();
  $reData['data'] = array();

  $rs = mysqli_query($mysqli, $sql);
  if ($rs) {
    $thisNum = $rs->num_rows;
  }
  else {
    $thisNum = 0;
  }
  $reData['num'] = $thisNum;
  if ($thisNum != 0) {
    while ($row = $rs->fetch_assoc()) {
      $reData['data'][] = $row;
    }

  }
  return $reData;
}

===============

  Why are you mentioning child tables in this question?

$addSQL.= " and up_cls='".mysqliChkData($Val[2])."'";

  Are you comfortable with scrapping your Select function ...because it is insecure.
  Why are you mixing procedural with object-oriented mysqli syntax?

It passed acunetix last year, I don't know it's insecure. Could you give me some advice about this.

  Is there a reason that you cannot query once, then use php to filter the result set based on chk?
  How about a conditional count within the SELECT clause?

It is because some tables don't have chk . If the query has chk it will broken.


texts:
I have XML below which is stored as a String in xmlData variable and I need to pass this String to my URL in client_data variable and then execute the URL:

<?xml version="1.0"?>
<ClientData
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.google.com model.xsd"
 xmlns="http://www.google.com">
    <client id="100">
        <clock>
                <for>
                    <etc>val(tery) = 1</etc>
                    <while><![CDATA[val(tery)  < 20]]></while>
                </for>
        </clock>
    </model>
</ClientData>

Below is the URL I am hitting on the browser by URL encoding client_data value manually to get the response back and it works fine through browser -

http://localhost:8080/test_tmp?max_time=30&users=1000&client_data=<?xml version="1.0"?>
<ClientData
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.google.com model.xsd"
 xmlns="http://www.google.com">
    <client id="100">
        <clock>
                <for>
                    <etc>val(tery) = 1</etc>
                    <while><![CDATA[val(tery)  < 20]]></while>
                </for>
        </clock>
    </model>
</ClientData>

Now I have started using Apache HttpClient to execute the URL and I have got below code which is working fine -

Using Apache HttpClient

This code works fine and I am able to get the response back. I am getting JSON response back as a string which is expected.

public static void main(String[] args) {
    for(int i= 1; i<=100; i++) {
        // this will return xml as a string
        String xmlData = getXMLData(i);
        String url = generateURL(xmlData);

        // do I need to create this everytime for each call?
        HttpClient httpclient = HttpClientBuilder.create().build();
        HttpGet request = new HttpGet(url);
        StringBuilder response = new StringBuilder();

        try {
            HttpResponse httpResponse = httpclient.execute(request);
            StatusLine statusLine = httpResponse.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            String phrase = statusLine.toString();

            if (statusCode == HttpStatus.OK.value()) {
                BufferedReader rd = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));

                String line = "";
                while ((line = rd.readLine()) != null) {
                    response.append(line);
                }
            }
        } catch (ClientProtocolException e) {
            System.out.println(e.getMessage());
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }

        // prints response
        System.out.println(response.toString());

        // and then I am serializing json "response" here to my POJO if it not null
    }
}

private static String generateURL(final String clientData) {
    StringBuilder url = new StringBuilder();
    url.append("http://localhost:8080/test_tmp?max_time=30&users=1000&client_data=");
    url.append(URLEncoder.encode(clientData, "UTF-8"));

    return url.toString();
}

I am opting for code review to see whether there is any better way to execute the URL efficiently using Apache HttpClient or if there is any way to simplify the above code.


texts:
Is this good or not?  Input arguments for OsFile_Open must be in UTF8 format.

#include <stdio.h>

#ifdef WIN32
    #include <Windows.h>
#endif

// Types declaration, originally they are located in header file
//
typedef int                 Bool_T;
typedef signed long long    Int64_T;

#define true    1
#define false   0

#define IN
#define OUT

Bool_T OsFile_Open( IN const char * name, IN const char * mode, OUT FILE ** file )
{
    FILE * handle;

#ifdef WIN32

    wchar_t unicodeMode[MAX_PATH];
    wchar_t unicodeName[MAX_PATH];

    int unicodeNameLen;
    int unicodeModeLen;

    unicodeNameLen = MultiByteToWideChar( CP_UTF8, 0, name, -1, unicodeName, 0 );

    if( unicodeNameLen != 0 )
    {
        if( MultiByteToWideChar( CP_UTF8, 0, name, -1, unicodeName, unicodeNameLen ) != 0 )
        {
            unicodeModeLen = MultiByteToWideChar( CP_UTF8, 0, mode, -1, unicodeMode, 0 );

            if( unicodeModeLen != 0 )
            {
                if( MultiByteToWideChar( CP_UTF8, 0, mode, -1, unicodeMode, unicodeModeLen ) != 0 )
                {
                    handle = _wfopen( unicodeName, unicodeMode );

                    if( handle != NULL )
                    {
                        *file = handle;
                        return true;

                    }else{

                        return false;
                    }

                }else{

                    return false;
                }

            }else{ // if( unicodeModeLen != 0 )

                return false;
            }

        }else{ // if( MultiByteToWideChar( CP_UTF8, 0, name, -1, unicodeName, unicodeNameLen ) != 0 )

            return false;
        }

    }else{ // if( unicodeNameLen != 0 )

        return false;
    }

#else

    handle = fopen64( name, mode );

    if( handle != NULL )
    {
        *file = handle;
        return true;

    }else{

        return false;
    }

#endif

}

Bool_T OsFile_Close( IN FILE * file )
{
    return ( fclose( file ) == 0 ) ? true : false;
}

Bool_T OsFile_Seek( IN FILE * file, IN Int64_T offset, IN int origin )
{
    int result;

#ifdef WIN32
    result = _fseeki64( file, offset, origin );
#else
    result =  fseeko64( file, offset, origin );
#endif

    return ( result == 0 ) ? true : false;
}

Bool_T OsFile_GetPos( IN FILE * file, OUT Int64_T * curPos )
{
#ifdef WIN32
    *curPos = _ftelli64( file );
#else
    *curPos =  ftello64( file );
#endif

    return ( *curPos != -1 ) ? true : false;
}

size_t OsFile_Read( IN FILE * file, IN int numOfBytes, OUT unsigned char * buffer )
{
    return fread( buffer, sizeof( unsigned char ), numOfBytes, file );
}

int OsFile_Eof( IN FILE * file )
{
    return feof( file );
}


texts: Review of a generic request handler class (RestSharp)

texts:
I wrote a class that uses RestSharp to access Rest and HTTP API web services. I tested it and it works however I was wondering if any changes could be made to it to make it better.

public class RequestHandler
{
    //Client to translate Rest Request intot HTTP request and process the result.
    private RestClient client;

    //this property stores the base URL
    const string baseUrl = "";

    //stores the account id and secret key if they will be needed for any authentication processes.
    readonly string account_id;
    readonly string secretKey;

    //this property stores the API key
    readonly string accessKey = "";

    //This constructor contains the account id and secret key that will be used for authorization when connecting to the API
    public RequestHandler(string account_id,string secretKey)
    {
        client = new RestClient(baseUrl);
        this.account_id = account_id;
        this.secretKey = secretKey;
    }

    //The default constructor
    public RequestHandler()
    {
        client = new RestClient(baseUrl);
    }

    public void Execute<T>(int id,Action<T> Success, Action<string> Failure) where T:new()
    {
        RestRequest request = new RestRequest();
        request.RequestFormat = DataFormat.Json;
        request.AddParameter("id",id,ParameterType.GetOrPost);

        client.ExecuteAsync<T>(request,(response) =>
        {
            if(response.ResponseStatus == ResponseStatus.Error)
            {
                Failure(response.ErrorMessage);
            }
            else
            {
                Success(response.Data);
            }
        });
    }
}


texts: Python code to check if an array has a sequence (1,3,4)

texts:
I recently applied for a job as a Python coder but was rejected.

This was the problem:

  Write a python code to check if an array has a sequence (1,3,4)

Assuming they were looking for expert Python programmers, what could I have done better?

# Tested with Python 2.7
import unittest

# Runtime: O(n)

def doesSeqAppear(int_arr):
    #check if input is a list
    if not isinstance(int_arr, list):
        raise TypeError("Input shall be of type array.")

    # check all elements are of type int
    if not all(isinstance(item, int) for item in int_arr) :
        raise ValueError("All elements in array shall be of type int.")

    arr_len = len(int_arr)
    if arr_len < 3:
        return False

    # Loop through elements
    for i in range(arr_len-2):
        if int_arr[i] == 1 and \
            int_arr[i+1] == 3 and \
            int_arr[i+2] == 4 :
            return True
    return False

class TestMethodDoesSeqAppear(unittest.TestCase):
    def test_only_single_seq(self):
        #Single time
        assert doesSeqAppear([1,3,4]) == True

    def test_multiple_seq(self):
        #multiple
        assert doesSeqAppear([2,2,1,3,4,2,1,3,4]) == True

    def test_neg_seq(self):
        #multiple
        assert doesSeqAppear([9,-1,1,3,4,-4,4]) == True

    def test_only_empty_seq(self):
        #empty
        assert doesSeqAppear([]) == False
    def test_only_single_elem_seq(self):
        #Single element
        assert doesSeqAppear([1]) == False

    def test_input_is_none(self):
        self.assertRaises(TypeError, doesSeqAppear, None)

    def test_raises_type_error(self):
        self.assertRaises(TypeError, doesSeqAppear, "string")

    def test_raises_value_error(self):
        self.assertRaises(ValueError, doesSeqAppear, [1,2,'a', 'b'])

if __name__ == '__main__':
    unittest.main()

#


texts: REST Web Api unit test endpoint validity with NUnit and Moq

texts:
I am unit testing that the URL that I give to my IRestClient is valid. This client talks to a third party Web API.

The test is as below:

    [Test]
    [ExpectedException("System.UriFormatException")]
    public void MakeRequest_EndPointIsInValid_ThrowsUriFormatException()
    {
        var stub = new Mock<IRestClient>();
        stub.Setup(x => x.MakeRequest()).Throws<UriFormatException>();

        string results = new RestClient("example", "method=payment&params[Key1]=Value1&params[Key2]=Value2&params[Key3]=Value3").MakeRequest();
    }

The RestClient class under test is

public class RestClient : IRestClient
{
    /// <summary>
    /// Web Api Url End point.
    /// </summary>
    public string EndPoint { get; set; }

    /// <summary>
    /// The Post data.
    /// </summary>
    public string PostData { get; set; }

    /// <summary>
    /// Do Request.
    /// </summary>
    /// <returns></returns>
    public string MakeRequest()
    {
        using (WebClient client = new WebClient())
        {
            client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";

            if (string.IsNullOrWhiteSpace(PostData)) throw new ArgumentNullException("PostData");
            if (string.IsNullOrWhiteSpace(EndPoint)) throw new ArgumentNullException("EndPoint");

            // I want to test this Uri parsing.
            Uri uriResult;
            if (!Uri.TryCreate(EndPoint, UriKind.Absolute, out uriResult) || uriResult.Scheme != Uri.UriSchemeHttps) throw new UriFormatException("EndPoint");

            return client.UploadString(uriResult, PostData);
        }
    }
}

How is this test and class under test?
Is my fake object a stub or a mock? I believe it's a stub as I am
just forcing the return of a UriFormatException.
Any improvements?


texts: Finding if sequential numbers for total exists

texts:
Question:
Given a sequence of positive integers A and an integer T, return whether there is a continuous sequence of A that sums up to exactly T

Example:

A = [23, 5, 4, 7, 2, 11], T = 20: True because 7 + 2 + 11 = 20
A = [1, 3, 5, 23, 2], T = 8: True because 3 + 5 = 8
A = [1, 3, 5, 23, 2], T = 7: False because no sequence in this array adds up to 7

Write code to find if sequential numbers for total exists.

Note: I'm looking for an O(N) solution. There is an obvious O(N^2) solution  but is not the final solution I'm looking for.

My answer code (in ruby) is the following. Please let me know if there is a more efficient way.

class Sequence
  def initialize(integers)
    @integers = integers
  end

  def continuous_sequence_for_total_exists?(total)
    sliced_array = slice_array(total)
    sliced_array.each do |array|
      array.each do
        if array.reduce(:+) == total
          return true
        else
          array.shift
        end
      end
    end

    return false
  end

  private

  # Slice array with any integer larger than max
  #
  # e.g.:
  # [1, 3, 5, 23, 2] => [1, 3, 5], [2]
  def slice_array(max)
    chunks = @integers.chunk{ |i| i < max || nil }
    chunks.map{ |answer, value| value }
  end
end


texts:
As the title says, the goal is to get all the possible palindromes of a string in C#:

public static bool IsPalindrome(this string source)
{
    for(int i = 0; i < source.Length / 2; i++)
    {
        if(source[i] != source[source.Length - 1 - i])
        {
            return false;
        }
    }

    return true;
}

public static IEnumerable<string> GetPossiblePalindromes(this string source, int maxPossibleChanges, IEnumerable<char> alphabet)
{
    var executionStack = new Stack<Tuple<string, int>>();
    executionStack.Push(Tuple.Create(source, 0));
    int maxChanges = Math.Min(maxPossibleChanges, source.Length);
    var generated = new HashSet<string>();
    generated.Add(source);

    if(maxPossibleChanges < 0)
    {
        yield break;
    }

    do
    {
        Tuple<string, int> currentRecord = executionStack.Pop();

        string currentString = currentRecord.Item1;
        if (currentString.IsPalindrome())
        {
            yield return currentString;
        }

        int currentNumberOfChanges = currentRecord.Item2;
        if (currentNumberOfChanges == maxChanges)
        {
            continue;
        }

        char[] chars = currentString.ToArray();
        foreach(char character in alphabet)
        {
            for(int i = 0; i < currentString.Length; i++)
            {
                char old = chars[i];
                if(character == old)
                {
                    continue;
                }
                chars[i] = character;
                var newString = new string(chars);
                if (generated.Contains(newString))
                {
                    chars[i] = old;
                    continue;
                }
                generated.Add(newString);
                executionStack.Push(Tuple.Create(newString, currentNumberOfChanges + 1));
                chars[i] = old;
            }
        }
    } while (executionStack.Count > 0);

    yield break;
}

Case sensitivity is taken into account and there is a max number of changes one can make to the original string in order to make it a palindrome. Also, a 1 charactes string is not considered a palindrome.

I wanted to ask for a review. I'm more interested in performance reviews but all the other reviews are more than welcome.


texts: Celsius and Fahrenheit Converter in JavaScript

texts:
I am learning JavaScript. Please review my code. Just created this Celsius & Fahrenheit Converter. Any suggestions to improve my code will be really helpful.
const celsiusToFahrenheit = document.getElementById('celsiusToFarhenhite');
const fahrenheitToCelsius = document.getElementById('farhenhiteToCelsius');
const converterButton = document.querySelector('.calculate');

converterButton.addEventListener('click', function(event){
event.preventDefault();

const celsiusToFahrenheitValue = (celsiusToFahrenheit.value * 9/5 + 32);
const fahrenheitToCelsiusValue = (fahrenheitToCelsius.value - 32) * 5/9;

if(celsiusToFahrenheit.value){
    document.write(`<h1>Celcius To Fahrenheit Result: </h1> ${celsiusToFahrenheitValue} &#8457;`);
}else if (fahrenheitToCelsius.value){
    document.write(`<h1>Fahrenheit To Celcius Result: </h1> ${fahrenheitToCelsiusValue} &#8451;`);
}else{
    document.write(`<h1>You must enter a number!</h1>`);
}
})


texts:
Where I work there's two different printers being used on a daily basis, one of them prints things from a particular program, which only uses the default printer. A lot of the times, during busy periods, people forget to switch the default printer, resulting in that program using the wrong printer, which isn't suitable for what's being printed.

The work PC is ancient and getting into the printers menu can take up to a few minutes. I am hoping my program will reduce spending so much time on the computer just to change the default printer.

This is the first time I've done up an interface in Tkinter, so I'd appreciate feedback if it can be done better.

import tkinter as tk
import tkinter.ttk as ttk

import win32print

def get_available_printers():
    return [printer[2] for printer in win32print.EnumPrinters(2)]

class PrinterManager(tk.Frame):

    def __init__(self, master, *args, **kwargs):
        tk.Frame.__init__(self, master, *args, **kwargs)
        self.master = master
        self.configure_interface()
        self.create_widgets()

    def configure_interface(self):
        self.master.title('Printer Manager')
        self.master.geometry('350x100')
        self.master.resizable(False, False)
        self.master.config(background='#626a77')

    def create_widgets(self):
        self.default_printer_label = tk.Label(self.master, bg='#626a77', fg='white')
        self.default_printer_label.place(x=10, y=12)
        self.update_default_printer_label()

        refresh_button = tk.Button(self.master, text='Refresh', command=self.update_default_printer_label)
        refresh_button.place(x=285, y=10)

        selected_printer = tk.StringVar()
        printer_choice_menu = ttk.Combobox(self.master, textvariable=selected_printer, values=get_available_printers(), width=35, state='readonly')
        printer_choice_menu.place(x=12, y=62)

        set_default_printer_button = tk.Button(self.master, text='Set', command=lambda: self.set_default_printer(selected_printer))
        set_default_printer_button.place(x=285, y=60, width=50)

    def update_default_printer_label(self):
        default_printer = win32print.GetDefaultPrinter()
        default_printer_text = 'Default printer: {}'.format(default_printer)
        self.default_printer_label.config(text=default_printer_text)

    def set_default_printer(self, printer_name):
        win32print.SetDefaultPrinter(printer_name.get())
        self.update_default_printer_label()

if __name__ == '__main__':
    root = tk.Tk()
    PrinterManager(root)
    root.mainloop()


texts: Group by range and include edge duplicates

texts:
I've created a method that groups Item entities below based on their Value property. The idea is to produce groups that also includes possible "edge duplicates", i.e.
[{ Value: 9 }, { Value: 10 }, { Value: 11 }]

With rangeSize set to 10 yields two groups:
[ [{ Value: 9 }, { Value: 10 }], [{ Value: 10 }, { Value: 11 }] ]

public IEnumerable<IEnumerable<DTO.Item>> GroupByValueRange(int rangeSize)
{
    var items = _itemRepository.GetAll().ToList();
    var steps = Math.Ceiling(items.Max(p => p.Value) / rangeSize);
    var groups = new List<IEnumerable<DTO.Item>>();

    for (var i = 1; i <= steps; i++)
    {
        var max = i * rangeSize;
        var min = (i - 1) * rangeSize;
        var currentGroup = items.Where(p => p.Value >= min && p.Value <= max);
        groups.Add(currentGroup.Select(p => _mapper.Map<DTO.Item>(p)));
    }

    return groups;
}

So the idea is to create groups with values like 0-10, 10-20, 20-30 etc...


texts:
I am using mod and my code works.  I am wondering if there is a more efficient way to write a method that returns the total number of divisors for an integer.

function getDivisorsCnt(n){
    var divisors = 0;
    mod = n;
    while (mod > 0){
      if(n % mod === 0){
        divisors++;
      }
      mod--;
    }
    return divisors;
}


texts: Loop through records, change property of records, send mail for each

texts:
I am trying to basically do the following

Get record from db.
Loop through records and send mail out for each record.
Update database records.

I would like to know what is the most optimal way to do this, including introducing some async if that would be best.

So I put a build-able sample together that goes from A-Z and I am looking for feedback on the best way to make this most efficient, basically in the need I would like to update the record in the db and end mail for that record

Main

class Program
{
    static void Main(string[] args)
    {
        var app = new App(new Sender(), new DbContext()); //params are DI'ed
        app.Run();
    }
}

App Class

public class App
{
    private readonly ISender _sender;
    private readonly DbContext _context;
    public App(ISender sender, DbContext context)
    {
        _sender = sender;
        _context = context;
    }

    public void Run()
    {
        var listFromDB = _context.Alerts;
        foreach (var alert in listFromDB)
        {
            _sender.Send(alert);
            alert.IsComplete = true;
        }
        _context.SaveChanges();
    }
}

Sender

public interface ISender
{
    void Send(Alert alert);
}
public class Sender:ISender
{

    public void Send(Alert alert)
    {
        var smtpClient = new SmtpClient();
        //....
        var msg = new MailMessage();
        smtpClient.SendMailAsync(msg);
    }
}

Support

public class Alert
{
    public string Title { get; set; }
    public string EmailAddress { get; }
    public bool IsComplete { get; set; }
}
public class DbContext //Entity Framework Core 2.0 object
{
    public List<Alert> Alerts { get; set; }

    public void SaveChanges()
    {
        //save to db;
    }
}


texts: Recording timeback seconds of video based on compared pixels from an image

texts:
The code reads from the screen, compares a pixel in a previously provided sample image and, if the pixels match, it records timeback seconds of video leading up to it. The output is put into a folder 'tm'. Since I do not assume the pixel to be occurring all the time, the writing process is buffered with a thread, so as not to slow down the capturing process. The pictures in the folder 'tm' can in the end be combined to make up a shortened movie, containing all the frames with the pixel in place.

I don't even know where to start optimizing. What should I improve in terms of readability and speed?

import PIL.ImageGrab
import PIL.Image
import time
from collections import deque
import threading
from numpy import *

def get_pixel_colour(i_x, i_y):
    return PIL.ImageGrab.grab().load()[i_x, i_y]

class framebuffer:
    def __init__(self,size):
        self.buffer = deque(maxlen=size)
        self.i= 0
    def add_frame(self, frame):
        self.buffer.append(frame)
    def remove_frame(self):
        return self.buffer.popleft()
    def write_frame(self):
        x = self.buffer.popleft()
        self.i+=1
        x.save("tm\screengrab"+ str(self.i).zfill(10) +".jpg")
        print "tm\screengrab"+ str(self.i).zfill(10) +".jpg written, ", len(self.buffer), "to go "
    def is_empfty(self):
        return (len(self.buffer)>0)

class mythread(threading.Thread):
    def run (self):
        while(True):
            if (len(self.frameb.buffer) > 0):
                self.frameb.write_frame()
            else:
                time.sleep(1)
    def setbuffer(self,frameb):
            self.frameb = frameb

seedimage = PIL.Image.open("seed.bmp")
pos_x = 983
pos_y = 263
recpixel = seedimage.load()[pos_x, pos_y]
print "The pixel is now", recpixel
fps = 50
skipticks = 1/(fps*1.0)
i= 0
timeback = fps * 3
allframes=framebuffer(timeback)
nextsnap=time.clock()
recordframes = framebuffer(None)
t= mythread()
t.setbuffer(recordframes)

print 'Starting thread'
t.setDaemon(True)
t.start()
print 'starting program'
print skipticks, fps
while (True):
    tim= time.clock()
    i=i+1
    x = PIL.ImageGrab.grab()
    allframes.add_frame(x)
    imp_pixel = x.load()[pos_x, pos_y]
    r, i = array(recpixel),array(imp_pixel)
    if (sum(r-i)<1 and sum(r-i)>-1 ):
        print "recognized", sum(r-i),"with size:", len(allframes.buffer)
        recordframes.buffer.extend(allframes.buffer)
        allframes.buffer.clear()
        sleep(10)

    # this is the sleep that limits the fps
    nextsnap+=skipticks
    sleeptime = nextsnap-time.clock()
    if (sleeptime>0):
        time.sleep (sleeptime)


texts: Improving the performance of my "type" function

texts:
I'm writing a JavaScript library, and I am using this function for type detection:

function type(obj){
    return  Object.prototype.toString.call(obj).replace(/([\[\]]|object|\s)/gi, "");
}

Their works ok, but compared to jQuery and MooTools it stinks.

http://jsperf.com/code-type-test-a-test

How can I improve its performance?


texts: Finding all integers in an array with odd occurrence

texts:
I am doing an interview exercise problem from here.

The problem is to find "all numbers that occurred an odd-number of times in an array".

Here is my high level psuedo code thinking:

Construct a map that will map integers to their frequencies.
Iterate through the array, use the map to record the frequency count.
Iterate through all the keys in the map and add the keys that have an odd value to another collection.
Convert that collection to an array and return it to the user.

Here is the my implementation of this high level psuedo code in Java:

public static int[] allOdd(int[] array) {
    Map<Integer, Integer> hm = new HashMap<Integer, Integer>();
    for(int c=0;c<array.length;c++) {
        if(hm.containsKey(array[c])) {
            hm.put(array[c], hm.get(array[c]) + 1);
        } else {
            hm.put(array[c], 1);
        }
    }
    List<Integer> allOdds = new ArrayList<Integer>();
    for(int key: hm.keySet()) {
        if(hm.get(key) % 2 == 1) {
            allOdds.add(key);
        }
    }
    int[] allOs = new int[allOdds.size()];
    for(int c=0;c<allOdds.size();c ++){
        allOs[c] = allOdds.get(c);
    }
    return allOs;
}

I tested this for two of my test cases and in both test cases ( {2,3,2,4,4,4,6,8,8} and {90,91,91,93,93,93,95,98,98,97} ), this function produced the right results([3, 4, 6] and [97, 93, 95, 90] respectively).

Is there anything I can do to improve the time and space complexity of this method. One of the worries I had was that I created too many collections (too much space) But to me each collection had its own purpose. The map was to map values to frequencies. The ArrayList was a dynamic structure to hold the odd occurrences. You needed to initialize the last array because ArrayList is a collection that holds objects so you need to manually iterate through the ArrayList and store those ints (Auto box) in the new array. To Array

Is there anything you can point out that can improve time and space efficiency in this function?


texts:
I am having trouble with the random number generator. For week 0 only, I want to set the starting number of roaches in House A (totalRoachesInHouseA) to 97 and the number of roaches in House B (totalRoachesInHouseB) to 79. Then, for weeks 1 to 10, I want to generate random numbers for both houses. I am trying to get the same numbers in the example simulation below.

Initial Population: Week 0: House 1 = 97; House 2 = 79
Week 1: House 1 = 119; House 2 = 109
Week 2: House 1 = 151; House 2 = 144
Week 3: House 1 = 194; House 2 = 189
Week 4: House 1 = 25; House 2 = 247
Week 5: House 1 = 118; House 2 = 235
Week 6: House 1 = 198; House 2 = 260
Week 7: House 1 = 280; House 2 = 314
Week 8: House 1 = 37; House 2 = 395
Week 9: House 1 = 187; House 2 = 374
Week 10: House 1 = 315; House 2 = 414

Here are the instructions for the project:

  Write a program which keeps track of the number of roaches in two
  adjacent houses for a number of weeks. The count of the roaches in the
  houses will be determined by the following:

  The initial count of roaches for each house is a random number between 10 and 100.
  Each week, the number of roaches increases by 30%.
  The two houses share a wall, through which the roaches may migrate from one to the other. In a given week, if one house has more roaches
  than the other, roaches from the house with the higher population
  migrate to the house with the lower population. Specifically, 30% of
  the difference (rounded down) in population migrates.
  Every four weeks, one of the houses is visited by an exterminator, resulting in a 90% reduction (rounded down) in the number of roaches
  in that house. Your implementation must use functions and local
  variables.

Here's what I have so far:

int roachesInHouseA, roachesInHouseB; //my two houses.
int temporaryHouseA, temporaryHouseB;
double totalRoachesInHouseA, totalRoachesInHouseB; //the total count of houses.
int week;

int main( )
{
    int temporaryHouseA = 0; // storage for arithmetic
    int temporaryHouseB = 0; // storage for arithmetic

    int totalRoachesInHouseA = 97; // test number for A
    int totalRoachesInHouseB = 79; // test number for B

    roachesInHouseA = rand() % 100 + 10;
    roachesInHouseB = rand() % 100 + 10;

    //The functions declaring the random count of roaches in both houses between
    //10 and 100.
    for (int Z = 1; Z < 12; Z++) // My for loop iterating up to 11 weeks.
    {
        totalRoachesInHouseA = totalRoachesInHouseA + roachesInHouseA * .3;
        totalRoachesInHouseB = totalRoachesInHouseB + roachesInHouseB * .3;

        // My function declaring that the roach population explodes by 30% weekly.
        cout << "The number of roaches in House A is " << totalRoachesInHouseA << endl;
        cout << "The number of roaches in House B is " << totalRoachesInHouseB << endl;

        if ((week == 4) || (week == 8)) // It's extermination time!
        {
            totalRoachesInHouseA = totalRoachesInHouseA - roachesInHouseA * .9;
            totalRoachesInHouseB = totalRoachesInHouseB - roachesInHouseB * .9;
        }
        else if (totalRoachesInHouseA > totalRoachesInHouseB) // Migration from
        //House A to HouseB
        {
            temporaryHouseA = totalRoachesInHouseA * .3;
            totalRoachesInHouseA = totalRoachesInHouseA - temporaryHouseA;
            totalRoachesInHouseB = totalRoachesInHouseB + temporaryHouseA;
        }
        else if (totalRoachesInHouseA < totalRoachesInHouseB) // Migration from
        // House B to House A
        {
            temporaryHouseB = totalRoachesInHouseB * .3;
            totalRoachesInHouseB = totalRoachesInHouseB - temporaryHouseB;
            totalRoachesInHouseA = totalRoachesInHouseA + temporaryHouseB;
        }
    }
}


texts: Calculate the difference between current date and age from personal ID

texts:
The goal is to show message for users that are less 25 years old. The personal ID consists of 081010333333, where 08year, 10month, 10date. I made code and it's very messy. So the question is: how to make it "right"? any advices and solutions are welcome. One on codepen and the code itself:

$('input').on('change keyup', function(i, el){
    var d = new Date(),
            getVal = $(this).val(),
            getYear = $(this).val().slice(0,2),
            getMonth = $(this).val().slice(2,4),
            getDay = $(this).val().slice(4,6),
            getCurrentYearFull = d.getFullYear(),
            getCurrentMonth = ("0" + (d.getMonth() + 1)).slice(-2),
            getCurrentDate = ("0" + (d.getDate())).slice(-2),
            getCurrentYearShort = d.getFullYear().toString().slice(2,4);

        if(getYear > getCurrentYearShort){
                getYear = "19" + getYear
            } else {
                getYear = "20" + getYear
            }
            var yearDiff = getCurrentYearFull - getYear;
            if (yearDiff >=10 && $('input').val().length >= 4) {
                    if(getCurrentMonth >= getMonth){
                         if (getCurrentDate >= getDay){
                             $(".check").text('good')
                         }
                        else {
                            $(".check").text('bad')
                        }
                    } else {
                        $(".check").text('bad')
                    }
            } else {
                $(".check").text('bad')

            }
        $('.test').text(yearDiff)
})

<input type="text" value="120330"/>


texts: Creating method to use one foreach instead multiple

texts:
I'm working with C#, and I have working code where I repeated same code every line, and that's because I'm creating list, conversions, extracting data, etc.

I have multiple foreach clauses, multiple lists, multiple conversions of list to datatables. My question is, what can I do to refactor this in order to have clean code?

 private void BtnLoadReport_Click(object sender, EventArgs e)
        {
            var db = new SQLDataMgr();

            List<string> DesignStatusList = new List<string>();
            List<string> ShopStatusList = new List<string>();
            List<string> CustomerTypeList = new List<string>();
            List<string> CustomerList = new List<string>();
            List<string> ResellerList = new List<string>();
            List<string> StateList = new List<string>();
            List<string> ProjectManagerList = new List<string>();
            List<string> SalesRepresentativeList = new List<string>();

            var checkedDesignStatus = cboDesignStatus.CheckBoxItems.Where(x => x.Checked);
            var checkedShopStatus = cboShopStatus.CheckBoxItems.Where(x => x.Checked);
            var checkedCustomerType = cboShopStatus.CheckBoxItems.Where(x => x.Checked);
            var checkedCustomer = cboShopStatus.CheckBoxItems.Where(x => x.Checked);
            var checkedReseller = cboShopStatus.CheckBoxItems.Where(x => x.Checked);
            var checkedState = cboShopStatus.CheckBoxItems.Where(x => x.Checked);
            var checkedProjectManager = cboShopStatus.CheckBoxItems.Where(x => x.Checked);
            var checkedSalesRepresentative = cboShopStatus.CheckBoxItems.Where(x => x.Checked);

            foreach (var i in checkedDesignStatus)
            {
                DesignStatusList.Add(i.Text);
            }
            foreach (var i in checkedShopStatus)
            {
                ShopStatusList.Add(i.Text);
            }
            foreach (var i in checkedCustomerType)
            {
                CustomerTypeList.Add(i.Text);
            }

            foreach (var i in checkedCustomer)
            {
                CustomerList.Add(i.Text);
            }
            foreach (var i in checkedReseller)
            {
                ResellerList.Add(i.Text);
            }
            foreach (var i in checkedState)
            {
                StateList.Add(i.Text);
            }
            foreach (var i in checkedProjectManager)
            {
                ProjectManagerList.Add(i.Text);
            }
            foreach (var i in checkedSalesRepresentative)
            {
                SalesRepresentativeList.Add(i.Text);
            }
            DataTable designStatusParameters = ToStringDataTable(DesignStatusList);
            DataTable shopStatusParameters = ToStringDataTable(ShopStatusList);
            DataTable customerTypeParameters = ToStringDataTable(CustomerTypeList);
            DataTable customerParameters = ToStringDataTable(CustomerList);
            DataTable resellerParameters = ToStringDataTable(ResellerList);
            DataTable stateParameters = ToStringDataTable(StateList);
            DataTable projectManagerParameters = ToStringDataTable(ProjectManagerList);
            DataTable salesRepresentativerParameters = ToStringDataTable(SalesRepresentativeList);

        }


texts:
I am trying to parse escape sequences as well as plain characters. Can this be made more succinct?

import Control.Applicative
import Data.Char
import Numeric
import Text.Parsec hiding ((<|>))

echar :: Parsec String () Char
echar = (char '\\' >>
         ((char 'b' >> return '\b')
          <|> (char 'f' >> return '\f')
          <|> (char 'n' >> return '\n')
          <|> (char 'r' >> return '\r')
          <|> (char 't' >> return '\t')
          <|> (char 'u' >> count 4 hexDigit >>= return . chr . fst . head . readHex)
          <|> (char 'v' >> return '\v')
          <|> (noneOf "u")))
        <|> noneOf "\\"


texts: Implementation of Singly Linked List (C++)

texts:
I tried to implement a singly linked list myself, sorry it is not commented but I think it should be pretty self-explanatory, if not feel free to comment. I know that using namespace std; is not optimal, but I figured it would be okay for this little example. Same goes for defining the class right in the main.cpp file (and in the declaration). I have two questions:

Is this even a correct implementation or did I miss something important? The methods worked as expected for me.
Would it make any sense to use smart pointers here? If yes, why? And what would I have to change for it to work?

Thank you for your time, I would appreciate any answers! :)
#include <iostream>

using namespace std;

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

class linked_list
{
public:

linked_list() : last{ NULL }, tmp{ NULL }, begin{ NULL } {};

~linked_list()
{
    clear();
}
void push_back(int32_t data)
{
    if (begin)
    {
        tmp = new Node;
        tmp->data = data;
        tmp->next = NULL;

        last->next = tmp;
        last = tmp;
        tmp = NULL;
    }
    else
    {
        begin = new Node;
        begin->data = data;
        begin->next = NULL;
        last = begin;
    }
}
void display_all()
{
    if (begin)
    {
        tmp = begin;
        while (tmp)
        {
            cout << tmp->data << endl;
            tmp = tmp->next;
        }
        tmp = NULL;
    }
    else
    {
        cout << "List is empty." << endl;
    }
}
void clear()
{
    while (tmp != last)
    {
        tmp = begin->next;
        delete begin;
        begin = tmp;
    }
    delete last;
    begin = NULL;
    tmp = NULL;
    last = NULL;
    }
private:
    Node* last;
    Node* begin;
    Node* tmp;
};

PS:
(Someone told me this would fit better on this site than on Stack Overflow so I am reposting.)


texts:
The premise of this program is to use the least amount of vehicles to allocate the available load.

What I did is allocate the largest amount of load on the truck that fits better.

This program's intention is not to optimize a load. I.e. if I have a load of 24, the program does not use two 12 capable vehicles, but the 30 one (because it is more costly to move two vehicles than one).
This code works as I expect but I would like to get suggestions on how to improve it / make it more efficient.

// Available vehicles
const vehicles = [
    {name: 'Camión', capacity: 5},
    {name: 'Rabón', capacity: 8},
    {name: 'Tráiler', capacity: 30},
    {name: 'Torton', capacity: 12, std: true},
];
function calculate(productList:any[]) {
    let groups = [];
    const totalSize: number = productList.reduce((accumulator, currentValue) => accumulator + currentValue);
    const stdVehicle = this.vehicles.find(v => {return v.std});
    // Sorting array
    this.vehicles.sort(function(a, b){return a.capacity - b.capacity});
    // Checking for exact match
    const exactMatch = this.vehicles.filter(v => {return v.capacity === totalSize});
    if (exactMatch.length) {
        // Exact Match found!
        exactMatch = exactMatch[0];
        return [{
            hasToPay: (stdVehicle.capacity >= exactMatch.capacity),
            vehicle: exactMatch,
            remaining: 0,
            load: exactMatch.capacity,
        }];
    }
    let remainingSize = totalSize;
    while(remainingSize > 0) {
        let closest = this.vehicles.filter(v => {return v.capacity > remainingSize});
        if (!closest.length) {
            // Total size is bigger than our biggest vehicle. Setting our biggest vehicle for first group
            closest = this.vehicles[this.vehicles.length - 1];
        } else {
            // Setting closest (but bigger) vehicle to allocate remaining size
            closest = closest[0];
        }
        groups.push({
            vehicle: closest,
            remaining: (closest.capacity - remainingSize < 0) ? 0 : closest.capacity - remainingSize,
            load: (remainingSize > closest.capacity) ? closest.capacity : remainingSize,
        });
        remainingSize -= closest.capacity;
    }
    // Deciding whether or not the customer has to pay for each group
    groups.map(r => {r.hasToPay = !(r.load === r.vehicle.capacity && stdVehicle.capacity <= r.vehicle.capacity)});
    console.log("====================================");
    return groups;
}
// Test cases
const a = [12, 12, 12]; // 3 items with the size of the std
const b = [1, 1, 3];    // Items that summed up fit exactly on a camión
const c = [10, 15, 5];  // Items that summed up fit exactly on a tráiler
const d = [30, 30, 12]; // 3 items that summed up fit exactly on 2 tráilers and 1 torton
const e = [9, 5];       // 2 items that summed up fit on a trailer and has remaining
console.log(this.calculate(a));
console.log(this.calculate(b));
console.log(this.calculate(c));
console.log(this.calculate(d));
console.log(this.calculate(e));


texts:
I have solved this question on Leetcode: https://leetcode.com/problems/palindrome-linked-list/description/. I convert the nodes into an ArrayList and am wondering if that's cheating? Other than that, how can I optimize this solution:

public class PalindromeLinkedList {

    public static void main(String[] args) {
        ListNode node = new ListNode(0);
        node.next = new ListNode(0);
        //node.next.next = new ListNode(1);
        //node.next.next.next = new ListNode(1);

        ArrayList firstHalf = new ArrayList();
        ArrayList secondHalf = new ArrayList();

        int count = 0;

        ListNode counterNode = node;
        while(counterNode != null) {
            count++;
            counterNode = counterNode.next;
        }

        int middle = count/2;
        boolean middleIgnored = count%2 != 0;
        for(int i = 0; i < middle; i++) {
            firstHalf.add(node.val);
            node = node.next;
        }

        if(middleIgnored) {
            node = node.next;
            System.out.println("middle ignored");
        }

        for(int i = middle + 1; node != null; i++) {
            secondHalf.add(node.val);
            node = node.next;
        }

        Collections.reverse(secondHalf);
        boolean isPalindrome = firstHalf.equals(secondHalf);

        System.out.println("first half: " + firstHalf);
        System.out.println("\nsecond half: " + secondHalf);
        System.out.println("\npalindrome? " + isPalindrome);

    }

}

class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
}


texts: Atomically incrementing a value in a map in Clojure

texts:
I am working out a bit of Clojure code that will take a ref to a map and increment a key value pair in the map.  I think I am using ref correctly, but Im not sure about atom.  Do I need to use swap! to be more idiomatic?  I am new to STM and Clojure, does this look thread-safe / sane?  What am I missing?

(defn increment-key [ref key]
    (dosync
        (if (= (get @ref key) nil)
            (alter ref assoc key (atom 1))
            (alter ref assoc key (atom (inc @(get @ref key)))))))

(defn -main [& args]
    (def my-map (ref {}))
    (increment-key my-map "yellow")
    (println my-map)
    (increment-key my-map "yellow")
    (println my-map))

Prints

$ lein run
#<Ref@494eaec9: {yellow #<Atom@191410e5: 1>}>
#<Ref@494eaec9: {yellow #<Atom@7461373f: 2>}>


texts:
This is my first attempt at creating an event system.

My plan is that upon publishing, the listener receives both a reference to the model and to the publisher. This allows the publisher class to have multiple owners, and provide a way for listeners to know exactly how they were called.

To do this I've made the base classes for the publisher/listener generic

abstract class AEventPublisher<Model, Publisher extends AEventPublisher<Model, ?>> {
    private List<IEventListener<Model, Publisher>> listeners;

    public AEventPublisher(){
        listeners = new ArrayList<IEventListener<Model, Publisher>>();
    }

    public void subscribe(IEventListener<Model, Publisher> listener) {
        listeners.add(listener);
    }

    public void unsubscribe(IEventListener<Model, Publisher> listener) {
        listeners.remove(listener);
    }

    protected void publish(Publisher publisher, Model sender) {
        for(IEventListener<Model, Publisher> listener : listeners){
            listener.actionPerformed(publisher, sender);
        }
    }

    public abstract void publish(Model sender);
}

interface IEventListener<Model, EventPublisher extends AEventPublisher<Model, ?>> {
    public void actionPerformed(EventPublisher publisher, Model sender);
}

The publish method was made protected and abstract, because I couldnt think of a way to get this in AEventPublisher to be casted as the Publisher extends AEventPublisher<Model, ?> type

Some defined event/listeners would then be:

public class GameEvents{
    public static interface IButtonEventListener extends IEventListener<MenuButton, ButtonEventPublisher>{}

    public static class ButtonEventPublisher extends AEventPublisher<MenuButton, ButtonEventPublisher> {
        @Override
        public void publish(MenuButton sender) {
            publish(this, sender);
        }
    }

    public static interface IJoystickEventListener extends IEventListener<Joystick, JoystickEventPublisher> {}

    public static class JoystickEventPublisher extends AEventPublisher<Joystick, JoystickEventPublisher> {
        @Override
        public void publish(Joystick sender) {
            publish(this, sender);
        }
    }
}

Now the listener Interfaces can be turned into anonymous classes to act as callbacks.

This would be an example usage as part of the constructor for my Player class.

joystickCallback = new IJoystickEventListener(){
    @Override
    public void actionPerformed(JoystickEventPublisher event, Joystick sender)
    {
        updatePlayerDirection(sender);
    }
};
joystick.getJoystickEventPublisher().subscribe(joystickCallback);
//Then before player is deleted, this would be called:
//joystick.getJoystickEventPublisher().unsubscribe(joystickCallback);