texts:
Click the divs to remove them. Remove all div's in the shortest time and minimal clicks (to do). Code needs streamlining.

<!DOCTYPE html>

I have a To Do list:

To Do

Add timer,
Add 'missed click counter',
Colours,
Size,
Positions,
Number,
Streamline code into DOM format,
Score,
Play again

Options

Flashers,
Multi-size,
Movers,
Bonuses (double points, static, combos, chains),
Anti-bonuses (move, faster, half points, bombs)


texts: Recursive download articles and dump to MongoDB

texts:
This is simple code that recursively downloads articles from the public WordPress API:

import requests

from pymongo import MongoClient
client = MongoClient()
db = client.wp

payload = {
    'number': 100
}

url = 'https://public-api.wordpress.com/rest/v1.1/sites/{site_id}/posts'
response = requests.get(url, params=payload).json()
found = response['found']
posts = response['posts']
print 'found {number} posts'.format(number=found)
db.posts.insert_many(posts)

def get_next_page(offset):
    print 'Inserted we have {left} posts left to go'.format(left=abs(found-offset))
    response = requests.get(url, params= {
        'number': 100,
        'offset': offset
    }).json()

    db.posts.insert_many(response['posts'])

    if int(response['found']) > offset:
        get_next_page(offset + 100)

get_next_page(100)


texts:
I have two functions that are used to prompt and recieve input from the user. One is for int and the other is for boolean. They work somewhat similar to each other, one uses try/catch and the other doesn't. Can they be improved upon or is one better than the other? I'm having trouble with the user interface, I'm not sure what should happen when the user gives an invalid input. I asked on userexperience and didn't get much feed back.

/*returns integer to question asked in prompt*/
public static int getNumber(String prompt)
{
    Scanner sc = new Scanner(System.in);
    while (true) {
        System.out.print("\t"+prompt+": ");
        String input = sc.next();
        try {
            return Integer.parseInt(input);
        } catch (NumberFormatException ne) {
            System.out.println("\tPlease enter an integer.");
        }
    }
}

/*returns boolean to question asked in message*/
public static boolean getBool(String message)
{
    Scanner sc = new Scanner(System.in);
    String answer;

    System.out.print("\t"+message+": ");
    while (true) {
      answer = sc.nextLine().trim().toLowerCase();
      if (answer.equals("y")) {
        return true;
      } else if (answer.equals("n")) {
        return false;
      } else {
         System.out.print("\tPlease answer y/n");
      }
    }

}

One problem is "please enter an integer". If the user is non-technical they may not know what an integer is, but I can't think of better wording.

Here is another version of the methods

/*returns integer to question asked in prompt*/
public static int getNumber(String prompt)
{
    Scanner sc = new Scanner(System.in);
    while (true) {
        System.out.print("\t"+prompt+": ");
        String input = sc.next();
        try {
            return Integer.parseInt(input);
        } catch (NumberFormatException ne) {
            System.out.println("\tPlease enter an integer.");
        }
    }
}

/*returns boolean to question asked in message*/
public static boolean getBool(String message)
{
    Scanner sc = new Scanner(System.in);
    String answer;

    do{
      System.out.print("\t"+message+" (y/n): ");
      answer = sc.nextLine().trim().toLowerCase();
      if (answer.equals("y")) {
        return true;
      } else if (answer.equals("n")) {
        return false;
      }
    }while(true);

}

An example of these functions being used is when they are called with

public static void main(String[] args)
{

    System.out.println("Please reply with y or n");
    boolean celsius = getBool("Temperature in celsius");
    boolean wind = getBool("Regularly windy");
    System.out.println("Please enter an integer");
    int minTemp = getNumber("Minimum temperature during day");
    int maxTemp = getNumber("Maximum temperature during the day");
    int minTempNight = getNumber("Minimum temperature during the night");
    int maxTempNight = getNumber("Maximum temperature during the night");
    //setup();
}

Example input/output

run:
Please reply with y or n
    Temperature in celsius (y/n): m
    Temperature in celsius (y/n): 5
    Temperature in celsius (y/n): y
    Regularly windy (y/n): asdf
    Regularly windy (y/n): y
Please enter an integer
    Minimum temperature during day: 5
    Maximum temperature during the day: 20
    Minimum temperature during the night: blah
    Please enter an integer.
    Minimum temperature during the night: 1
    Maximum temperature during the night: words
    Please enter an integer.
    Maximum temperature during the night: 10


texts: JavaScript function which checks the count of words in a string

texts:
Task to accomplish: Made a function which counts the amount of words in a sentence.

Please don't put attention to the HTML. Is just for testing-purposes.

var sentence = document.querySelector('#sentence');
var exec = document.querySelector('#exec');
var result = document.querySelector('#result');

// ## THE ACTUAL FUNCTION ###########
// ## Rest is just for testing ######

// Reports the count of words which are
//   contained in assigned string.

// Parameter (sentence): Are string is
//   expected. The string doesn't have
//   to be empty. It has to consist of
//   other characters then just blanks.

// Return a number: The count of words
//   in the assigned string.
//   In case of an error -1 is returned.

function getCountOfWords(sentence) {
  if (sentence.length === 0 ||
      sentence.search(/\w+/) === -1)
    return -1;

  if (sentence.search(/\s+/) === -1)
    return 1;

  return (sentence.match(/(^|\s)\w+/g)).length;
}

// ## END ACTUAL FUNCTION ###########

function execHandler() {
  result.value = getCountOfWords(sentence.value);
}

exec.addEventListener('click', execHandler);
.wrap {
  margin: 20px auto;
  width: 900px;
}

.wrap label {
  display: inline-block;
  width: 150px;
}

.wrap div {
  margin: 20px 0;
}

      Sentence to check:

    <input type="text" id="sentence"
           value="one Two2 Three 4four five123"
           size="80" />

    <button id="exec">Exec</button>

      Count of words:

    <input type="text" id="result" />

I have tried to catch everything which could wrong.
But perhaps there are cases which I haven't thought about?

Are their better (more elegant) ways to achieve the described task?


texts: PHP: Succint and scalable function to get what financial year we are in

texts:
I have the below

private function yearMenu() {
    $m = date('m');
    $y = date('Y');

    if (($m>3 && $y==2019) || ($m<4 && $y==2020)){
        $menu = 1;
    }
    if (($m>3 && $y==2020) || ($m<4 && $y==2021)){
        $menu = 2;
    }
    if (($m>3 && $y==2021) || ($m<4 && $y==2022)){
        $menu = 3;
    }
    if (($m>3 && $y==2022) || ($m<4 && $y==2023)){
        $menu = 4;
    }
    if (($m>3 && $y==2023) || ($m<4 && $y==2024)){
        $menu = 5;
    }
    if (($m>3 && $y==2024) || ($m<4 && $y==2025)){
        $menu = 6;
    }

    return $menu;
}

This code works as intended i.e. I want to be able to give each financial year an integer based on 2019-2020 being the base at value 1 and it increasing each year onward

I was wondering if there was a more succinct and scalable way to do this?

Thanks


texts:
Is below code a valid Singleton design pattern for Mongodb in Java?

Please suggest any improvements.

public class Mongo extends MongoClient {

    private static Mongo mongoClient = null;
    private static MongoDatabase mogoDB = null;

    private Mongo(ServerAddress server, List<MongoCredential> mongoCredentialList) {
        super(server, mongoCredentialList);
    }

    public static Mongo getMongoClient() {
        return getMongoClient("userName", "password", "127.0.0.1", 27017, "SampleDB");
    }

    public static Mongo getMongoClient(String userName, String pwd, String ip, int port, String dbName) {

        if (mongoClient == null) {

            logger.debug("******* Trying to connect to Mongo Server *******");

            ServerAddress server = new ServerAddress(ip, port);
            List<MongoCredential> mongoCredentialList = new ArrayList();
            char[] password = pwd.toCharArray();
            mongoCredentialList.add(MongoCredential.createCredential(userName, dbName, password));

            mongoClient = new Mongo(server, mongoCredentialList);

            logger.debug("******* Connected to the Mongo server Successfully *******");
        } else {
            logger.debug("Already connected to Mongo server...");
        }
        return mongoClient;
    }

    public static MongoDatabase getMongoDatabase() {

        if (mogoDB == null) {
            logger.debug("******* Trying to get Mongo DB - SampleDB - connection. *******");
            mogoDB = getMongoClient().getDatabase("SampleDB");
            logger.debug("******* Successfully Connected to - SampleDB - Mongo DB *******");
        }
        return mogoDB;

    }

    public static MongoDatabase getMongoDatabase(String dbName) {

        if (mogoDB == null) {
            logger.debug("******* Trying to get Mongo DB - " + dbName + " - connection. *******");
            mogoDB = getMongoClient().getDatabase(dbName);
            logger.debug("******* Successfully Connected to - " + dbName + " - Mongo DB *******");
        }
        return mogoDB;

    }
}


texts: Prettified GridView: is this JS code concise?

texts:
I been writing code for my company for years and there is never any constructive criticism for what I do. I am the only developer here and I would appreciate your opinion on this web page I made.  It grabs data from a mssql database and places it in a data table adds some calculations then displays the data in a gridview.  I added some css and javascript to make it look better.  But is my javascript too sloppy.

link: to codepen.io

<script>
    jQuery(function () {

          $(document).ready(function () {
              var xd = document.getElementById("datepicker");
              var xde = document.getElementById("datepicker2");
              var d = new Date();
              var d2 = new Date();

              var parlen = 0;
              var colwidth = document.getElementById('GridView1').rows[0].cells[0].offsetWidth;

              d.setDate(d.getDate() - 2);
              d2.setDate(d2.getDate() - 1);
              xd.value = d.toLocaleDateString();
              xde.value = d2.toLocaleDateString();
              $("th").css("background-color", "#5FE 1");
              $("td:last-child()").css("background-color", "#3FE 1");
              $("td:first-child()").css("background-color", "#EFE 1");

              parlen = $("th").length;

              $("#GridView1 tr td:contains('No Data')").css("background-color", "#EEE 1");
              $("tr:nth-child(2)").css("background-color", "#ba67f0");
              // $("td:nth-child()").hover($(this).css("background-color", "#EFE 1"), $(this).css("background-color", "#F3E 1"));
              $("#GridView1 tr td:nth-of-type(n)").hover(function () {
                  // var pl = this.parent.length();
                  var cb = 1 + this.cellIndex;
                  var rb = 1 + this.parentElement.rowIndex;
                  if (cb > 1 && cb < parlen) {
                      $("td:nth-child(" + cb + ")").css("background-color", "yellow");
                      $("td:nth-child(" + cb + ")").css("font-size", "16px");
                      $("td:nth-child(" + cb + ")").css("font-bold", "true");
                      $("tr:nth-child(" + rb + ") td").css("background-color", "yellow");
                      $("td:last-child()").css("background-color", "#3FE 1");
                      $("td:first-child()").css("background-color", "#EFE 1");
                      // $("td:nth-child(" + cb + ")").css("column-width", 2*colwidth);
                  }
              }, function () {
                  var cb = 1 + this.cellIndex;
                  var rb = 1 + this.parentElement.rowIndex;

                  if (cb > 1 && cb < parlen) {

                      $("td:nth-child(" + cb + ")").css("background-color", "white");
                      $("td:nth-child(" + cb + ")").css("font-size", "12px");
                      $("td:nth-child(" + cb + ")").css("font-bold", "true");
                      $("#GridView1 tr td:contains('No Data')").css("background-color", "#EEE 1");
                      $("tr:nth-child(" + rb + ") td").css("background-color", "white");
                      $("tr:nth-child(2) td").css("background-color", "#ba67f0");
                      $("td:last-child()").css("background-color", "#3FE 1");
                      $("td:first-child()").css("background-color", "#EFE 1");
                  }
              });

          });
</script>
```


texts: Inheritance selfmade or reinventing wheel

texts:
Background

I like to code JavaScript in a typical style with "classes" and inheritance. My goal was to create an easy way to make inheritance available and keep classes that inherits from others clean. Also I like to use the module pattern and uses its look and feel.

My solution

I hope the code is self-explanatory. I'm using it in all my newer projects and it seems to work fine.

 if(typeof(SimpleJSLib)==='undefined'){
     var SimpleJSLib = {}; // define namespace
 }
 SimpleJSLib.BaseObject = function(){
     // returns an object you wether can inherit from or instantiate it
     var createInheritObject = function(inheritFunctions){
         return {
             // instantiate the current class
             // iterates through all functions which the class inherits from and calls them
             construct : function(){
                 var me = {}, _protected = {};
                 for(var i = 0; i < inheritFunctions.length; i++){
                     me = inheritFunctions[i].call(me, me, _protected);
                     if(typeof(me)==='undefined'){
                         throw 'Inherit function did not return "me"';
                     }
                 }
                 // if a constructor is defined we call them and deliver the arguments this function was called with
                 if(typeof(_protected.construct)!=='undefined'){
                     _protected.construct.call(me, arguments);
                 }
                 return me;
             },
             // clones the pointers to the functions you inherit from
             // and returns another object you can instantiate or inherit from
             inherit : function(inheritFunction){
                 var _inheritFunctions = inheritFunctions.slice(0); // clone
                 _inheritFunctions.push(inheritFunction);
                 return createInheritObject.call(window, _inheritFunctions);
             }
         };
     };

     return {
         // allows you to inherit directly from BaseObject
         inherit : function(inheritFunction){
             // this is the first call of the function, so the the inheritFunctions array just contains one function
             return createInheritObject.call(window, [inheritFunction]);
         }
     }
 }();

Questions

Is there any good argument why I shouldn't use this code snippet?
How about performance? Is there anything I could make better?

Examples

Just a few simple ones.

var MyClass = SimpleJSLib.BaseObject.inherit(function(me, _protected){
    // protected
    _protected.myValue = 'value';
    _protected.doSomething = function(){
        console.log('something')
    };
    // public
    me.getMyValue = function(){
        return _protected.myValue;
    }
    return me;
});
var MySubClass = MyClass.inherit(function(me, _protected){
    me.anotherFunction = function(){
        _protected.doSomething();
    }
    return me;
});
var myClassInstance = MyClass.construct();
console.log(myClassInstance.getMyValue());
var mySubClassInstance = MySubClass.construct();
console.log(mySubClassInstance.anotherFunction());

Using the constructor

var MyClass = SimpleJSLib.BaseObject.inherit(function(me, _protected){
    _protected.valueOne = null;
    _protected.valueTwo = null;
    _protected.construct =  function(parameters){
        _protected.valueOne = parameters[0];
        _protected.valueTwo = parameters[1];
    };
    return me;
});
var myClassInstance = MyClass.construct('valueOne', 'valueTwo');

Singelton

var Singelton = SimpleJSLib.BaseObject.inherit(function(me, _protected){
    return me;
}).construct(); // mention the construct!


texts: Reporting duplicate entry for a given set of data

texts:
While solving a problem on an online judge, I tried with these two implementations.

These two implementations do the same thing. Task is to report duplicate entry for a given set of data.

Implementation #1 : Converts input data to a String and adds to a HashSet. After all the input is read, appropriate message is displayed.

class Databse2 {

    public static void main(String[] args) throws Exception{
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        int t=Integer.parseInt(br.readLine());//number of test cases
        int N=0,R=0,C=1;
        while(t-->0){ //while there are more test cases
            HashSet<String> set=new HashSet<String>();
            StringTokenizer st=new StringTokenizer(br.readLine());
            while(st.hasMoreTokens()){
                N=Integer.parseInt(st.nextToken());
                R=Integer.parseInt(st.nextToken());//Number of Rows of data
            }

            int ID=0,SC=0;boolean haha=true;
            for(int i=0;i<R;i++){ //for number of rows read each record in the row
                st=new StringTokenizer(br.readLine());
                while(st.hasMoreTokens()){
                    ID=Integer.parseInt(st.nextToken());
                    SC=Integer.parseInt(st.nextToken());
                }
                String key=ID+""+SC;//convert to string,this combo is used to check for duplicates
                haha=haha && set.add(key);

            }
            if(haha)
                System.out.println("Scenario #"+C+": possible");
            else System.out.println("Scenario #"+C+": impossible");
            C++;
        }
    }
}

Running time = 3.41 sec (for N number of test cases)

Implementation #2: Same task is accomplished as in Implementation #1 but in a different way. An object is created based on input type and added to HashSet.

class Database {

private int ID;
private int SC;

public Database(int ID,int SC){
    this.ID=ID;
    this.SC=SC;
}
@Override
public boolean equals(Object obj) {
    return (obj instanceof Database) ? ID==((Database)obj).ID:SC==((Database)obj).SC;
}

@Override
public int hashCode() {
    return 31*(ID+SC);
}

public static void main(String[] args) throws Exception{
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    int t=Integer.parseInt(br.readLine());
    int N=0,R=0,C=1;
    while(t-->0){
        HashSet<Database> set=new HashSet<Database>();
        StringTokenizer st=new StringTokenizer(br.readLine());
        while(st.hasMoreTokens()){
            N=Integer.parseInt(st.nextToken());
            R=Integer.parseInt(st.nextToken());
        }
        int ID=0,SC=0;boolean haha=true;
        for(int i=0;i<R;i++){
            st=new StringTokenizer(br.readLine());
            while(st.hasMoreTokens()){
                ID=Integer.parseInt(st.nextToken());
                SC=Integer.parseInt(st.nextToken());
            }
            haha=haha?set.add(new Database(ID, SC)):false;
        }
        String str=haha?"Scenario #"+C+": possible":"Scenario #"+C+": impossible";
        System.out.println(str);
        C++;
    }
}
}

Running Time #2 = 2.74 sec (for N number of test cases)

What causes implementation #2 to be faster? Is it the hashCode method?


texts: Generating URL and status for an S3 bucket

texts:
The following program generates the S3 URL and response (status code?) for the key, provided the bucket name and if the S3 URL is a mess (wrong url), then it generates empty string as URL and error as the response.

The code works fine, but the way it handles the messy S3 url seems buggy to me. Please provide some insights to design a better error handling mechanism and a good way to generate the response a.k.a status code?

from boto.s3.connection import S3Connection

class URLGenerator:
    def __init__(self, access_id, access_key, bucket_name, expiry=0):
        """
        Initialization parameters to get url from S3.
        :param access_id: S3 access id
        :param access_key: S3 access key
        :param bucket_name: the name of the bucket to open
        :param expiry: the expiration of the access
        :return: instantiates various attributes
        """
        self.conn = S3Connection(access_id, access_key)
        self.bucket_name = bucket_name
        self.expiry = expiry

    def generate_url(self, k):
        """
        Generates the url by finding the key :param k in the bucket and generates url for it.
        This key is the part of the GET request.
        :param k: the key
        :return: url for the file in S3 and the response for the same,
        """
        resp_dict = {}

        bucket = self.conn.get_bucket(self.bucket_name)

        try:
            key = bucket.get_key(k)
            resp_dict['ok'] = 'success'
            generated_url = key.generate_url(expires_in=self.expiry)
        except AttributeError:
            resp_dict['error'] = "File doesn't exist or check back your S3 URL."
            generated_url = ''
        return generated_url, resp_dict

    def clean_url_and_response(self, id):
        """
        Cleans up the unwanted query methods and authentication tokens in the url generated by
        the self.generate_url() method.
        :param id: the key
        :return: the stripped url and the formatted error or success message based upon the GET request.
        """
        url, resp = self.generate_url(id)
        try:
            url = url.split('?')[0]
        except AttributeError:
            url = ''
        return url, list(resp.values())[0]

    def close(self):
        self.conn.close()


texts: Filtering data from MYSQL database based on parameters passed with POST request

texts:
I am working on a PHP MVC project for my portfolio. Its an web app where you can store contacts (email and phone number). I am having trouble with filtering contacts based on filter form that has 3 options https://ibb.co/8dJbSWd

I wrote code that works fine but I am sure there is better way of doing this. Here is the code that I wrote for solving this problem.

public function filterContacts($user_id, $group, $email, $phone){

    $query = 'SELECT * FROM contacts WHERE user_id = :user_id ';

    //Nothing is selected
    if($group == '0' && $email == '' && $phone == ''){

        $this->db->query($query . ' ORDER BY name');
        $this->db->bind(':user_id', $user_id);
        return $this->db->resultSet();

        //Everything is selected
    } else if ($group !== '0' && $email !== '' && $phone !== ''){

        $query .= 'AND contact_group = :group AND email != "" AND phone_number != ""';

        $this->db->query($query . 'ORDER BY name');
        $this->db->bind(':user_id', $user_id);
        $this->db->bind(':group', $group);

        return $this->db->resultSet();

        //Just group
    } else if ($group !== '0' && $email == '' && $phone == ''){

        $query .= 'AND contact_group = :group ';

        $this->db->query($query . 'ORDER BY name');
        $this->db->bind(':user_id', $user_id);
        $this->db->bind(':group', $group);

        return $this->db->resultSet();

        //Just email
    } else if ($group == '0' && $email !== '' && $phone == ''){

        $query .= 'AND email != "" ';

        $this->db->query($query . 'ORDER BY name');
        $this->db->bind(':user_id', $user_id);

        return $this->db->resultSet();

        //Just phone
    }  else if ($group == '0' && $email == '' && $phone !== ''){

        $query .= 'AND phone_number != "" ';

        $this->db->query($query . 'ORDER BY name');
        $this->db->bind(':user_id', $user_id);

        return $this->db->resultSet();

        //Group and email
    } else if($group !== '0' && $email !== '' && $phone == ''){

        $query .= 'AND contact_group = :group AND email != ""';

        $this->db->query($query . 'ORDER BY name');
        $this->db->bind(':user_id', $user_id);
        $this->db->bind(':group', $group);

        return $this->db->resultSet();

        //Group and phone number
    } else if($group !== '0' && $email == '' && $phone !== ''){
        $query .= 'AND contact_group = :group AND phone_number != ""';

        $this->db->query($query . 'ORDER BY name');
        $this->db->bind(':user_id', $user_id);
        $this->db->bind(':group', $group);

        return $this->db->resultSet();

        //Email and phone number
    } else if($group == '0' && $email !== '' && $phone !== ''){

        $query .= 'AND phone_number != "" AND email != ""';

        $this->db->query($query . 'ORDER BY name');
        $this->db->bind(':user_id', $user_id);

        return $this->db->resultSet();
    }

}

As you can see I used a lot of if statements to make different queries in Contact model which is possible because i have only 3 filtering options but I cannot imagine doing this with 10 options.

So I was wondering is there a better way of solving this?

Here is link to my github repository if you want to see rest of the code https://github.com/Smiley-dev/Phonebook-demo


texts: Multithreading synchronization between reading and writing in a channel

texts:
I was hoping to get some feedback on what the recommended design pattern are for this subject.

public class Channel {

    private AtomicInteger buffer = new AtomicInteger(0);

    public void read() {
        // This function should keep blocking until there is something to read.

        while (buffer.get() == 0) {
            // Maybe a sleep? (Although NetBeans gives a warning for a sleep in a loop)
        }

        buffer.decrementAndGet();
    }

    public void write() {
        // This function should just write (nothing) to the buffer (by increasing the counter of the imaginary buffer).
        buffer.incrementAndGet();
    }
}

Is this safe for use in multithreading? Or is there a better approach?


texts:
I wrote code for my needs (i.e. collecting YouTube links from a page) and it is simple, but now I just want to know what can I do just to make it a better and properly written one. For example, I think I should have try/catch blocks/exceptions in my methods, or get/set properties. What tests can I write to test the code? I don't know to be honest, but how would the code look if you had written it?

public class Parser
{
    public static void Main()
    {
        Console.WriteLine("Enter the url of the page:");
        var url = Console.ReadLine();

        var numOfPages = GetNumberOfPages(url);
        var numOfLinks = 1;

        for (int page = 0; page <= numOfPages; page++)
        {
            if (page != 1)
            {
                if (page == 0)
                {
                    GetYouTubeLink(url).ForEach(x => Console.WriteLine($"{numOfLinks++}." +
                        $"{x.Replace("embed/", "watch?v=").Replace("?feature=oembed", "")}"));
                }
                else
                {
                    var newUrl = url + string.Format($"{page}/");
                    GetYouTubeLink(newUrl).ForEach(x => Console.WriteLine($"{numOfLinks++}." +
                        $"{x.Replace("embed/", "watch?v=").Replace("?feature=oembed", "")}"));
                    newUrl = string.Empty;
                }
            }
        }
    }

    private static HtmlDocument GetWebPageHtmlFromUrl(string url)
    {
        var webGet = new HtmlWeb();

        return webGet.Load(url);
    }

    private static int GetNumberOfPages(string url)
    {
        var pages = GetWebPageHtmlFromUrl(url)
            .DocumentNode.SelectNodes("//div[@class='page-link']")
            .Descendants("a")
            .Last().InnerText;

        return int.Parse(pages);
    }

    private static List<string> GetYouTubeLink(string url)
    {
        var links = new List<string>();
        var iframeLinks = GetWebPageHtmlFromUrl(url).DocumentNode.SelectNodes("//iframe");

        if (iframeLinks != null)
        {
            foreach (var link in iframeLinks)
            {
                links.Add(link.Attributes["src"].Value);
            }
        }

        return links;
    }
}


texts:
The class Functions can store/load any functions. It does this by assigning a unique name to every function that gets added. You can then call the function by specifying its name and return type.

Here is a sample usage

//Create class
Functions funcs;

//Add 2 functions (foo -> void(int, int) | add -> int(int, int))
funcs.add("foo", foo);
funcs.add("add", add);

//Call them
int r = funcs.call<int>("add", 3, 2);
funcs.call<void>("foo", r, 2);

Here is the actual class

class Functions
{
public:
    template<typename T, typename... Ts>
    void add(std::string name, T(*func)(Ts...))
    {
        mFunctions.insert(std::make_pair(name, func));
    }

    template<typename T, typename... Ts>
    T call(std::string name, Ts... args)
    {
        try
        {
            return boost::any_cast<T(*)(Ts...)>(mFunctions.at(name))(args...);
        }
        catch (const std::out_of_range&)
        {
            throw std::invalid_argument("Function doesn't exist!");
        }
    }
private:
    std::map<std::string, boost::any> mFunctions;
};

Is there anything to be improved, like maybe naming, programming techniques, ...? Some general feedback would be appreciated.


texts: Detecting if two strings are anagrams using TreeMap

texts:
I decided to use Java TreeMap because it seems like a great data structure to fit this problem. However, I am not sure if there could be much simpler methods using better data structure or how I could start improving the time complexity of this algorithm. I would also like to know how I can improve the style of the current code.

Is the time complexity of following algorithm \$O(n \log n)\$?

/**
 * Created by mona on 5/25/16.
 */
import java.util.Map;
import java.util.TreeMap;

public class isAnagram {

    public static boolean areAnagrams( String s1 , String s2 ) {

        if ( s1.length() != s2.length() ) {
            return false;
        }

        Map< Character , Integer > charFrequencyS1 = new TreeMap<>();
        Map< Character , Integer > charFrequencyS2 = new TreeMap<>();

        for ( int i=0 ; i<s1.length() ; i++ ) {
            if ( charFrequencyS1.containsKey(s1.charAt(i)) ) {
                int freq = charFrequencyS1.get(s1.charAt(i));
                charFrequencyS1.put(s1.charAt(i), freq+1);
            }

            else {
                charFrequencyS1.put(s1.charAt(i), 1);
            }

            if ( charFrequencyS2.containsKey(s2.charAt(i)) ) {
                int freq = charFrequencyS2.get(s2.charAt(i));
                charFrequencyS2.put(s2.charAt(i), freq+1);
            }

            else {
                charFrequencyS2.put(s2.charAt(i), 1);
            }

        }

        return charFrequencyS1.equals(charFrequencyS2);

    }

    public static void main( String args[] ) {

        String s1="mona";
        String s2="noea";

        System.out.println(areAnagrams(s1,s2));

    }
}


texts: Faster JavaScript fuzzy string matching function?

texts:
I'm using the following function to fuzzy match strings:

function fuzzy_match(str,pattern){
    pattern = pattern.split("").reduce(function(a,b){ return a+".*"+b; });
    return (new RegExp(pattern)).test(str);
};

Example:

fuzzy_match("fogo","foo") //true
fuzzy_match("jquery.js","jqjs") //true
fuzzy_match("jquery.js","jr") //false

It's very slow, though. How can I optimize that function?


texts: Website for allowing data evaluation from submission

texts:
I'm making a really basic website where users essentially just submit data into some forms and they will be able to review their data in another page. I feel like I'm going to be repeating myself far too much.
This is how I'm planning to display the users records, the trouble I'm having is I have about six more tables of data that is slightly different. So I can't just hard-code a template because the number of columns and the names of the columns is slightly different in each table. I know I could just make six different HTML files but that just seems silly. I feel like I need to somehow loop over the attributes of the models and then somehow display them in the template?
Is there a better way of displaying database data in a template?
class (db.Model):
    __abstract__ = True
    employee_name =  db.Column(db.String(50), nullable=False)
    date_submitted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    comment =  db.Column(db.String(100), nullable=True)

class FridgeFreezerTempTable(Base):
    id = db.Column(db.Integer, primary_key=True)
    unit_name = db.Column(db.String(50), nullable=False)
    unit_type = db.Column(db.String(50), nullable=False)
    temperature = db.Column(db.String(10), nullable=False)
    company_id = db.Column(db.Integer, db.ForeignKey('user.id'),nullable=False)

@app.route("/unit_temp_records/<int:page_number>")
def unit_records(page_number):
    """
    records = pagiantion object
    page number = the current page

    """
    records = FridgeFreezerTempTable.query.filter_by(user=current_user).paginate(per_page=5,
             page=page_number, error_out=True)
    return render_template("unit_temp_records.html", user_records=records, table=table)

{% extends "records.html"%}

{%block recordcontent%}

            #
            Unit Name
            Unit Type
            Temperature
            Employee Name
            Comment
            Date Submitted

        {% for record in user_records.items %}

                {{ loop.index }}
                {{record.unit_name}}
                {{record.unit_type}}
                {{record.temperature}}

                {{record.employee_name}}
                {{record.comment}}
                {{record.date_submitted}}

        {% endfor %}

    {% for page in user_records.iter_pages() %}
    {% if page %}
    {{ page }}
    {% else %}
    .
    {% endif %}
    {% endfor %}

{% endblock%}
```


texts: REST service to list new, continuing, and terminated subscribers during some period

texts:
I have a use case which says:

  Your REST service will consume a JSON object that contains a list of
  emails for subscribers at the start of the subscription period, and a
  list of subscribers at the end of the subscription period. Your
  service must return a list of subscribers who are new, subscribers who
  stayed, and subscribers who unsubscribed.

  Example JSON input:

{
    "start" : [
        "test1@test.com",
        "test2@test.com"
    ],
    "end" : [
        "test1@test.com",
        "test3@test.com"
    ]
}

  Example JSON output:

{
    "new" : [
        "test3@test.com"
    ],
    "stayed" : [
        "test1@test.com"
    ],
    "unsubscribed" : [
        "test2@test.com"
    ]
}

The way I implemented it is:

Controller

@POST
@Timed
@Consumes(MediaType.APPLICATION_JSON)
public SubscriptionResponse subscriptionDetail(SubscriptionRequest request) {
    return new SubscriptionResponse(request);
}

Response

public SubscriptionResponse (SubscriptionRequest request) {
        //Get the common subscriptions
        List<String> common = new ArrayList<String>();
        common.addAll(request.getEnd());
        common.retainAll(request.getStart());
        //Filter out unsubscribed
        List<String> unsubscribed = request.getStart();
        unsubscribed.removeAll(common);
        //Get the new subscription
        List<String> newSub = request.getEnd();
        newSub.removeAll(common);
        unsubscribed.removeAll(common);

        this.newSub = newSub;
        this.stayed = common;
        this.unsubscribed = unsubscribed;
    }

Is it the right way of implementing it? What are the pros (if any) and cons?


texts:
I'm a bit lost with implementing MCV pattern on javascript.

Where should events (such as 'click','change') come in on MVC in javascript?

I have this event function,

   var EventExample = function (controller, view) {

       this.controller = controller;
       this.view = view;
       return this;
   };

   EventExample.prototype.clicked = function ( ) {

        var $root = this;

        var id = $("#input-text").val();

        $root.controller.find( id );

        return $root.view.render();
   };

And I have this function to bind all MVC, Mapper, Service, etc together,

   function bootstrapper() {

        // get a new model.
        var model = new ModelExample();

        // get a new model.
        var mapper = new MapperExample();

        // get a new service.
        var service = new ServiceExample( mapper, model);

        // get a new controller.
        var controller = new ControllerExample(service);

        // get a new view.
        var view = new ViewExample(model);

        // get a new event.
        var event = new EventExample(controller, view);

        $('#search-button').click(function(){
            event.clicked();
        });
   }

That is how I call the event function in there, but it seems weird.

I looked at this blog, the event (click) seems must be wrapped inside a function? if so, is it supposed to be in a controller, or in a model, or in a mapper?

Are all events considered Observers in the design patterns?

Any ideas how I should go with events?

My entire MVC code is on jsfiffle


texts:
Look for all six letter words which are composed of two concatenated smaller words.

Please give me feedback regarding good coding standards.

import java.io.File
class KataExercise(val wordLength: Int) {
    fun concatenatedWords(): List<String> {
        val searchWords = dictionary
                .filter { it.length == wordLength }
        val result = mutableListOf<String>()
        for (subWord in smallDictionary) {
            val subWordLength = subWord.length
            (smallDictionary)
                    .filter { it.length + subWordLength == wordLength }
                    .map { it + subWord }
                    .filter { it in searchWords }
                    .forEach { result.add(it) }
        }
        return result.toList()
    }
    private val dictionary = File("dict.text").readLines()
            .filter { "'" !in it }
    private val smallDictionary: List<String> = dictionary
            .filter { it.length < wordLength}
}


texts:
I have created a nice url structure for my site.

In my .htaccess I have:

FallBackResource /index.php

And in my router class I have:

class init {

function __construct($url)
{
    $URLElements = explode('/', $url) ; // Adjust if needed.

    if($url)
    {
        $class = $URLElements[0] ;

        if(substr_count($url, '/') == 1)
        {
            $method = $URLElements[1] ;
        }

    }

    if(($t = substr_count($url, '/')) > 1)
    {
        for($i=2;$i<$t+1;$i++) {
            echo $URLElements[$i].'<br />';
        }
    }

}

}

Is this ok and what are your thoughts (how can it be improved etc)?


texts: Append blank value(s) to missing fields in a CSV line

texts:
I have a small app that takes in CSV files. It reads the CSV file and before it inserts a line into the DB it checks certain conditions on the line.

Now, let's say the length of the line should be 5.

These are the headers:

colA,colB,colC,colD,colE

and this is one line of a CSV file the program is reading:

a, b

I want to now return back a line of length 5 (ignore the header and spacing I'm just trying to make it clearer on why I want to return it this way):

colA, colB, colC, colD, colE
"a",  "b",  "",   "",   ""

This is my current code on how to solve this:

private String buildErrorLine(String[] line) {
    if(line.length < 5) {
        return appendCommas(buildShortErrorLine(line, 5));
    } else {
        return appendCommas(line);
    }
}

private String[] buildShortErrorLine(String[] line, int lineSize) {
    ArrayList<String> arrayListLine = new ArrayList<String>(Arrays.asList(line));
    int size = lineSize - arrayListLine.size();
    for(int i=0; i<size; i++) {
        arrayListLine.add("");
    }
    System.out.println(arrayListLine.toString());
    return arrayListLine.toArray(new String[lineSize]);
}

private String appendCommas(String[] line) {
    StringBuilder sb = new StringBuilder();
    for (String n : line) {
        if (sb.length() > 0) sb.append(',');
        sb.append("\"").append(n).append("\"");
    }
    return sb.toString();
}

This will be the final output:

colA, colB, colC, colD, colE, colD(error)
"a",  "b",  "",   "",   "",   "the error"

Is there a cleaner or faster way to do this? Also, don't worry about checks for lines that are bigger than 5.


texts: Find the common elements of the lists in a list of lists

texts:
Considering the problem:

Make a function to find the common elements of the lists in a list of lists.
Example:
common ( [ [1,2,3,3,5,11], [2,2,2,3,3,5], [2,2,3,3,4,5,6,7,18,19], [3,5,10,15] ] ) = [3, 5].

I came up with this solution:
import Data.List(group, nub, sort)

-- |
-- This function returns the elements common to all lists in a list of lists.
--
commonXss :: Ord a => [[a]] -> [a]
commonXss xss = concat [x | (x, y) <- countElemAppearsXss xss, y == length xss]

-- |
-- This function takes a list of lists and returns a list of tuples. Each tuple
-- (x, y) is made of x == [element] and y == number of lists in which that
-- element appeared.
--
countElemAppearsXss :: Ord a => [[a]] -> [([a], Int)]
countElemAppearsXss xss = freq $ sort $ concat $ map nub xss

-- |
-- This function returns a list of tuples. Each tuple (x, y) is made of
-- x == [element] and y == it's frequency.
--
freq :: Ord a => [a] -> [([a], Int)]
freq xs = map (\x -> ([head x], length x)) . group . sort $ xs

Is there a simpler way, more straightforward way that I'm missing? Perhaps in a library? How about the style?


texts: Counting words from standard input in Swift

texts:
I know Swift isn't exactly meant to be used to write your classic stdin to stdout scripts, and that Python, Ruby, Perl, bash, awk, and friends are much better in this area, but I'd still like to see how well it can be done.

The problem I chose is: Read from standard input, and write to standard output a space-separated report of each of the words (lowercased) and their counts, sorted by word. For simplicity, words are defined as containing Basic Latin letters (U+0061 through U+007A) and the apostrophe (U+0027) only.

In Ruby, just for illustration, we can do this:

counts = Hash.new(0)
ARGF.each do |line|
  line.downcase.scan /[a-z']+/ {|word| counts[word] += 1}
end
counts.sort.each do |word, count|
  puts "#{word} #{count}"
end

Now, struggling with Swift, all I can come up with is this mess:

import Foundation

let standardInput = NSFileHandle.fileHandleWithStandardInput()
let input = standardInput.availableData
let text = String(data: input, encoding: NSUTF8StringEncoding)!
var counts = [String: Int]()

func isWordChar (c: Character) -> Bool {
    return "abcdefghijklmnopqrstuvwxyz'".rangeOfString("\(c)") != nil
}

for word in (text.lowercaseString.characters.split{!isWordChar($0)}.map(String.init)) {
    if let count = counts[word] {
        counts[word] = count + 1
    } else {
        counts[word] = 1
    }
}

for (word, count) in (counts.sort { $0.0 < $1.0 }) {
    print("\(word) \(count)")
}

There are so many problems with this, particularly:

I'm not sure how to read "line by line" or at least in chunks from stdin. Ruby and Python give you this for free. My Swift code reads up to the theoretical 8EiB limit, and as we know, with big data we want to process as we read rather than slurping in the whole file first.
It appears Swift has no native regex support, so rather than using all the Objective-C regex support, I went with split which works on Swift strings. Is there a simple way to use the regexes instead of splitting?
I think my use of split with the little helper can be improved.
I'm not happy with my use of ! to unwrap the optional string.
Is there a better way to do the counting with the dictionary? Ruby's default value for hash lookups is fabulous here... Can Swift do the same?

Can the Swift code here be professionalized?


texts: Collect messages from a job to send in body of one email

texts:
I have a Spring service that calls a few methods to
@Service
@RequiredArgsConstructor
@Slf4j
public class CarService {

    private final CarRepository carRepo;
    private final Mail mail;

    public void syncCars(Set<CarInfo> carInfos) {

        carInfos.forEach(carInfo ->
               carRepo.findByCarInfo(carInfo.getId()) // returns Optional
                 .map(car -> updateCar(car, carInfo))
                 .orElseGet(() -> createCar(carInfo)));
    }

    public void createCar(Car car) {
       // some processing code
       // not shown for brevity
       mail.send("Following car created " + car);
    }

    public void updateCar(Car car, CarInfo carInfo) {
       if (car.getPrice() - carInfo.getPrice() > 1000) {
         mail.send(String.format("Price for %s changed by %s", car, car.getPrice() - carInfo.getPrice());
       }
       // some processing code
       // not shown for brevity
    }

    public void deleteCar(Car car) {
       // some processing code
       // not shown for brevity
       mail.send("Following car deleted " + car);
    }
}

Mail is a Spring component:
@Component
@Slf4j
public class Mail {

    private final JavaMailSender javaMailSender;
    private final String appEmailAddress;
    private final String[] adminEmailAddresses;

    public Mail(JavaMailSender javaMailSender, MailProperties properties) {
        this.javaMailSender = javaMailSender;
        appEmailAddress = properties.getAppEmailAddress();
        adminEmailAddresses = properties.getAdminEmailAddresses();
    }

    public void sendEmail(String bodyText) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(appEmailAddress);
            message.setTo(adminEmailAddresses);
            message.setSubject("Car Sync Report");
            message.setText(bodyText);
            javaMailSender.send(message);
        } catch (MailException me) {
            log.error("Unable to send message due to the following error: "
                    + me.toString());
        }
    }

}

With this code, the CarService may send multiple emails on one call to syncCars. However, I would like for it to only send one email with all the messages.
I could create an instance field to hold the email body messages but CarService is a singleton and that would likely have concurrency issues. Another approach is to pass a String or StringBuilder to each method to collect the messages and then call mail.send at the end of the syncCars method. Is there another way to collect the messages to send in an email without passing an additional collection object to each method while avoiding concurrency issues? This seems like a cross-cutting concern here.


texts: Calculate cumulative salary including raises

texts:
Is there a way to make this more pythonic?

def money():
    current_salary = float(input("What is your current salary? "))
    years = int(input("How many years would you like to look ahead? "))
    amount_of_raise = float(input("What is the average percentage raise you think you will get? ")) * 0.01

    for years in range(1, years + 1):
        current_salary += current_salary * amount_of_raise
        print('Looks like you will be making', current_salary,' in ', years,'years.')
money()


texts:
It seems like this code should be shorter, but with all the error checking it is long and hard to follow. This is for a simulation of vehicles crossing a bridge, and this part is dealing with mutexes. I tried extracting a function that is passed the mutex and locks/unlocks it and prints any errors, but when I did that it broke the code (it's been my experience on this site to not include any broken code so I won't elaborate on what I tried).

/*global variables*/
pthread_mutex_t Bridge = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t okToOutput = PTHREAD_MUTEX_INITIALIZER;
/*...*/
/*this is the function that gets passed to pthread_create()*/
void* startSim(void *arg)
{

    Vehichle* inData = (Vehichle*)arg;
    if(usleep(inData->sleepT1))
        cerr << "Vehichle " << inData->licencePlate << " failed to sleep" << endl;
    if(pthread_mutex_lock(&okToOutput))
        cerr << "failed to lock output" << endl;
    cout << "Vehichle " << inData->licencePlate << " is ready to go " << dirToStr(inData->direction) << endl;
    if(pthread_mutex_unlock(&okToOutput))
        cerr << "failed to unlock output" << endl;

    if(pthread_mutex_lock(&Bridge))
        cerr << "failed to lock bridge" << endl;
    if(pthread_mutex_lock(&okToOutput))
        cerr << "failed to lock output" << endl;
    cout << "Vehichle " << inData->licencePlate << " is ON the main bridge going " << dirToStr(inData->direction) << endl;
    if(pthread_mutex_unlock(&okToOutput))
        cerr << "failed to unlock output" << endl;
    if(usleep(inData->sleepT2))
        cerr << "Vehichle " << inData->licencePlate << " failed to sleep" << endl;
    if(pthread_mutex_lock(&okToOutput))
        cerr << "failed to lock output" << endl;
    cout << "Vehichle " << inData->licencePlate << " is OFF the main bridge after going " << dirToStr(inData->direction) << endl;
    if(pthread_mutex_unlock(&okToOutput))
        cerr << "failed to unlock output" << endl;
    if(pthread_mutex_unlock(&Bridge))
        cerr << "failed to lock bridge" << endl;

    return NULL;
}

My compiler doesn't properly support C++11 so no smart pointers etc.


texts: Adding events to multiple markers in a Google map

texts:
I was looking over questions related to setting up markers on a Google map, and though the following works perfectly fine for me, it was different from the other (and accepted) answers. I just wanted to see if I'm doing something incorrect, or just a different way.

Mine:

this references the marker, and you can pull any data you have associated with it simply by calling it within the loop that creates all of the markers.

google.maps.event.addListener(marker, "click", function(){
     infowindow.setContent(this.position.toString());
     infowindow.open(this.map, this);
});

Accepted:

 google.maps.event.addListener(marker, 'click', (function(marker, i) {
     return function() {
     infowindow.setContent(locations[i][0]);
     infowindow.open(map, marker);
    }
 })(marker, i));


texts:
I finally managed to get the code to work properly. It makes the player object move faster if the user double taps the arrow key with a few 'ticks' (new frames) after the 1st stroke. - User presses and has a limited time to press again to sprint the object. If the time runs out the user has to try again.

However, It'd be better I believe to be working with time, miliseconds and not 'ticks', as what I intend involves lots of key combinations that have x seconds to be pressed.

I would like to know the redundancies in the code, what can be made into a class and something better then screen refresh to time things up (delays?).

package
{

import flash.display.Sprite;
import flash.display.Graphics;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.ui.Keyboard;
import flash.events.KeyboardEvent;

public class Main extends Sprite {
var keys:Array = [];
var player:Sprite = new Sprite();
var sprint, condition1, condition2, timerStart, keyUp, keyDown:Boolean;
var timer:int;

public function Main():void {

player.graphics.beginFill(0x000000);
player.graphics.drawCircle(0, 0, 25);
player.graphics.endFill;

addChild(player);
player.x = 100;
player.y = 250;

player.addEventListener(Event.ENTER_FRAME, update);
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
}

function update(e:Event):void {

  if ((timerStart)&&(timer>0)) {
    timer --;
    condition1 = true;
  }

  if (keyUp) {
    if ((condition1) && (timer > 0)) {
       condition2 = true;
    }

    if (sprint) {
      timerStart = false;
      condition1 = false;
      condition2 = false;
      sprint = false;
      timer = 7;
    }

    if (timer <= 0) {
      timerStart = false;
      condition1 = false;
      condition2 = false;
      sprint = false;
      timer = 7;
    }
}

if (keys[Keyboard.RIGHT]) {
timerStart = true;

if ((condition1) && (condition2)) {
sprint = true;
}

if (sprint) {
player.x += 7;
} else player.x += 2;
            }

function onKeyDown(e:KeyboardEvent):void {
keys[e.keyCode] = true;
keyUp = false;
keyDown = true;
}

function onKeyUp(e:KeyboardEvent):void {
keys[e.keyCode] = false;
keyUp = true;
keyDown = false;
}

} // class
} // package


texts:
I've searched the web if there is a generic indexer in c# (4.0 / WPF) but could not find anything about it.

So I came up with my own solution and would like to share it with you. I hope to get some feedback on improvements.

public dynamic this[string attribute, Type type]
{
    get
    {
        try
        {
            return Convert.ChangeType(base.GetAttribute(attribute), type);
        }
        catch (Exception)
        {
            return this[attribute];
        }
    }
}

Short explanation of how i use it: my class derives from a generic class which again derives from XmlElement (WPF). The generic class offers a generic method to add XmlAttributes where their can be of any data type.

Here are some examples of usage:

    task.AddAttribute<bool>("boolAttrib");
    bool boolAttrib = false;
    boolAttrib = task["boolAttrib", boolAttrib.GetType()];

    task.AddAttribute<DateTime>("datetimeAttrib", new DateTime(2013, 11, 4));
    DateTime datetimeAttrib = new DateTime();
    datetimeAttrib = task["datetimeAttrib", datetimeAttrib.GetType()];

As there is no such thing as a generic indexer and the "out" keyword cant be used this was the only solution i came up to.

Any advice to improve it is highly appreciated! Thanks! :)


texts: Concatenating a SoundCloud Playlist Update JSON

texts:
I am currently working on an implementation of SoundCloud for a 3rd party iOS app, and as there is no SDK anymore I am doing all my calls via Alamofire.

This is what SC expects you to send in your body params:

{ "playlist":
    {"tracks":[
        {"id":"__"},
        {"id":"__"},
        {"id":"__"}]
    }
}

I hand over the current playlist where the song should be added in the playlist object to extract all the ids from tracks that are part of it atm - as SC expects you so send all the old track ids + your new one in a .PUT call

This is what the ID dance looks at the moment:

var allTracks = [Int]() //SC track id comes in as an Int

allTracks.append(trackId) //trackId is the new track

for track in playlist.tracks {
    var I = track.id
    allTracks.append(I)
}

var myparams = Dictionary<String,AnyObject>() //my Alamofire body-params

var myTracks = [Dictionary<String,AnyObject>]()

for id in allTracks {
    var D = ["id":id]
    myTracks.append(D)
}

myparams["playlist"] = ["tracks":myTracks]

As I am still fairly new to Swift/iOS Development I was looking for a more elegant way than to just throw stuff around 3x and end up basically appending it the way it came in.


texts:
I was experimenting with some code to fetch the current weather data as well as getting the hourly forecast. I could have done written some functions to get the thing done but I want to learn object composition to learn more about it. Below is my code:

import axios from 'axios'

const weatherService = {
  fetch: async endpoint => await axios.get(endpoint)
}

const weatherApi = {
  currentWeather: async city => {
    try {
      const { data: { data } } = await this.service.fetch(this.config.endpoints.curr + city)
      return this.handleCurrentData(data)
    } catch(e) {
      this.handleError(e)
    }
  },
  hourlyForecast: async city => {
    try {
      const { data: { data } } = await this.service.fetch(this.config.endpoints.hour + city)
      return this.handleHourlyData(data)
    } catch(e) {
      this.handleError(e)
    }
  }
};

const defaultConfig = {
  endpoints: {
    curr: `http://api.openweathermap.org/data/2.5/weather?q=`,
    hour: `http://api.openweathermap.org/data/2.5/forecast?q=`
  }
};

const api = (api, config, service) => {
  return {
    Object.create(weatherApi),
    Object.create(service),
    Object.create(config),
    ...obj
  }
};

// dependency injection for testing
module.exports = (obj, config=defaultConfig, service=weatherService) => {
  return api(obj, config, service)
};

// Usage
const weatherAPI = require('api')({
  handleCurrentData: (data) => console.log(data),
  handleHourlyData: (data) => console.log(data)
});

weatherAPI.currentWeather('London');
weatherAPI.hourlyWeather('London');

I would like to know if my approach is correct? also, what can I do to improve the readability, flexibility of the code?


texts:
i have found this article on how to loop through multi-dimensional arrays quickly.
http://nadeausoftware.com/articles/2012/06/c_c_tip_how_loop_through_multi_dimensional_arrays_quickly

I am using Method 6: Nested loops with linear array and single incrementing index.
It says Method 8: Single loop with linear array and incrementing index is faster.
but i require nested loops indexes as well. when i try to calculate the nested loops indexes via if clauses. my code slows down(at least worst than nested loop approach) can you recommend anything for calculating individual indexes.

 int x1=0,x2=0;
  for (int i1 = 1; i1 <= 10000; i1++){
             for (int i = 0; i < 10000; i++){

                x1++;
                if(x1>100){
                    x1=0;
                    x2++;
                 }
                 a[i] = 0;
                 if (x1 > 10)
                 {
                     a[i] += a[i - 10*1];
                 }
                 if (x2 < 95)
                 {
                     a[i] += a[i + 5*100];
                 }
             }
         }

for  multidimensional array structure a[x1][x2]. I want to calculate a[x1][x2]=a[x1-10][x2]+a[x1][x2+5] which a[x1][x2] is converted to a[x1+x2*100]

program code
http://ideone.com/oKVdQI

Is there a way I can improve this code in terms of speed?


texts: Convert IEnumerable to HTML table string

texts:
My code can generate HTML table strings well, but it depends on JSON.NET.

I'm converting IEnumerable to an HTML table string using Json.NET but I think I shouldn't.

void Main()
{
    var datas = new[] { new {Name="Test"} };
    var array = datas.ToArray().ToHtmlTable(); //Run Success
    var set = datas.ToHashSet().ToHtmlTable();//Run Succes
    var list = datas.ToList().ToHtmlTable(); //Run Succes
    var enums = datas.AsEnumerable().ToHtmlTable(); //Run Succes
}

public static class HTMLTableHelper
{
    public static string ToHtmlTable(this IEnumerable enums)
    {
        return ToHtmlTableConverter(enums);
    }

    public static string ToHtmlTable(this System.Data.DataTable dataTable)
    {
        return ConvertDataTableToHTML(dataTable);
    }

    private static string ToHtmlTableConverter(object enums)
    {
        var jsonStr = JsonConvert.SerializeObject(enums);
        var data = JsonConvert.DeserializeObject<System.Data.DataTable>(jsonStr);
        var html = ConvertDataTableToHTML(data);
        return html;
    }

    private static string ConvertDataTableToHTML(System.Data.DataTable dt)
    {
        var html = new StringBuilder("
");

        //Header
        html.Append("

");
        for (int i = 0; i < dt.Columns.Count; i++)
            html.Append("" + dt.Columns[i].ColumnName + "	");
        html.Append("

");

        //Body
        html.Append("
");
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            html.Append("
");
            for (int j = 0; j < dt.Columns.Count; j++)
                html.Append("" + dt.Rows[i][j].ToString() + "	");
            html.Append("
");
        }

        html.Append("
");
        html.Append("
");
        return html.ToString();
    }
}

I think it is bad because SerializeObject to string could be DeserializeObject to DataTable is a waste of efficiency.

var jsonStr = JsonConvert.SerializeObject(enums);
var data = JsonConvert.DeserializeObject<System.Data.DataTable>(jsonStr);

I want to remove dependencies on JSON.NET because it can reduce the size of the library.

Do you think I should replace them with something else if there is a better way?


texts: API Get Request to pull data from an online database

texts:
This code gets detailed information about a particular game from an online database using an API Get request. The question I have doesn't pertain to the request but is more about the code itself. The code works. I just think it is long for what needs to be done though. I was wondering if this code is able to be refactored because there are a few places the code just looks the same. I have been trying for last couple of days to get this done with no avail. Any help will be appreciated.

def self.get_game_details(game_selection)
    if Game.all[game_selection.to_i - 1].description == nil
        response = RestClient.get("#{DETAIL_URL}#{Game.all[game_selection.to_i - 1].slug}", headers = {"x-rapidapi-host" => ENV["HOST"], "x-rapidapi-key" => ENV["API_KEY"]})
        data = JSON.parse(response.body)

        Game.all[game_selection.to_i - 1].description = data["description"]
        Game.all[game_selection.to_i - 1].released = data["released"]
        Game.all[game_selection.to_i - 1].metacritic_rating = data["metacritic"] unless data["metacritic"] == nil # default to 0 if no data

        data["ratings"].each do |rating|
            case rating["title"]
            when "recommended"
                Game.all[game_selection.to_i - 1].recommended_rating = rating["percent"] unless rating["percent"] == nil # # default to 0.0 if no data
            when "exceptional"
                Game.all[game_selection.to_i - 1].exceptional_rating = rating["percent"] unless rating["percent"] == nil # # default to 0.0 if no data
            when "meh"
                Game.all[game_selection.to_i - 1].meh_rating = rating["percent"] unless rating["percent"] == nil # # default to 0.0 if no data
            when "skip"
                Game.all[game_selection.to_i - 1].skip_rating = rating["percent"] unless rating["percent"] == nil # # default to 0.0 if no data
            end
        end
    end
end


texts: Getting around gsl/span's restriction on temporaries

texts:
The goal of this code is to allow temporary RHS variables to be used in a span, specifically as an argument to a function, to be deleted later after the function completes, allowing the passing of temporaries to such span accepting functions.
How would I improve this code? Can I make it smaller and more readable? Is the temp_span api fine as it is to telegraph "Only put temporaries here" or is there something else I should be doing?
#include <gsl/span>
namespace gsl{

    template<typename T>
    class TempSpan{
    public:
        T value;
        explicit TempSpan(T&& t) : value(t){};
        operator gsl::span<typename T::value_type>() {
            return value;
        }
    private:
    };

    template<typename T>
    TempSpan<std::vector<T>> temp_span(std::initializer_list<T>&& t){
        return TempSpan(std::vector<T>(t));
    }
    template<typename T>
    TempSpan<T> temp_span(T&& t){
        return TempSpan(std::move(t));
    }

}

#include <iostream>

void foo(gsl::span<int> values){
    for(const auto& value: values){
        std::cout << value << "\n";
    }
}

int main(){
    foo(gsl::temp_span(std::vector<int>{1,2,3}));
    // 1
    // 2
    // 3
    foo(gsl::temp_span({4,5,6}));
    // 4
    // 5
    // 6
    return 0;
}


texts: Stored procedure to swap account holders

texts:
I'm doing an exercise, and would like to know if what I'm doing is correct and follows the correct structure for rollback in case a transaction fails. I would like to know as well if my try...catch statements are well implemented.

create procedure spTeste2(
    @tit1 bigint = 111,
    @tit2 bigint = 222
) as
begin try
if exists(select primeiroTitular, segundoTitular from ContasBancarias where (primeiroTitular = @tit1 and primeiroTitular is not null) and (segundoTitular = @tit2 and segundoTitular is not null))
    begin
        declare @nib varchar(50) = (select nib from ContasBancarias where primeiroTitular = @tit1 and segundoTitular = @tit2)

        begin transaction
            update ContasBancarias set primeiroTitular = @tit2 where nib = @nib
            update ContasBancarias set segundoTitular = @tit1 where nib = @nib
        commit transaction
    end
else
    begin
        raiserror('Pelo menos um destes titulares não existe, ou não estão nesta ordem', 16, 1)
    end
end try
begin catch
    print ERROR_MESSAGE()

    IF @@TRANCOUNT > 0
        ROLLBACK transaction
end catch

The table ContasBancarias has the following structure:

nib
primeiroTitular
segundoTitular

This code aims to switch the value from primeiroTitular to segundoTitular, and vice versa.

For example, if on a particular row primeiroTitular contains the value 5678 and segundoTitular contains the value 9635, after this stored procedure is executed, primeiroTitular should have 9635 and segundoTitular should have 5678.


texts: Optimally allocating a resource with time-varying demand and cost

texts:
I'm working on the following DP which finds the optimal way to allocate a resource. At each time step I can either allocate (0.2 resources) at cost C or not in which case the storage is reduced by the demand. The cost C depends on which time step I do the allocation.

I need to add quite a few more complex features, but this is the bare working version in Python 2.7:

from math import floor
import numpy as np
import time

def discretise(x,levels = 40,Hmax = 2, Hmin = 0):
    # discretise the levels of storage
    factor = levels / (Hmax-Hmin)
    return floor(x*factor)/factor

# function to track the storage evolution at the stages
def record(D,key,item):
    """Records the value of item in the dictionary d with k"""
    if key in D.keys():
        D[key].append(item)
    else:
        D[key] = [item]

    return D

# Memoization decorator i found online that works
def memoize(f):
    cache = {}

    def memoizedFunction(*args):
        if args not in cache:
            cache[args] = f(*args)
        return cache[args]

    memoizedFunction.cache = cache
    return memoizedFunction

# define demands and cost (Energy)
D = [0.1, 0.1, 0.13, 0.2, 0.4, 0.3, 0.1]
Energy  = [2.0, 5.0,  9.0, 3.0, 7.0, 4.0, 6.0]

@memoize
def val(h,i=0):
    if h < 0 or h > 2: # h < Hmin or h > Hmax:
        return 1000000000
    elif i == T:  # i = T
        return -h*5 # h*m the linear value of h at i = T
    else:
        #           pump off         pump on
        record(H,i,discretise(h))

        no_pump = val(discretise(h-D[i]),i+1) # don't allocate
        pump = Energy[i] + val(discretise(h+0.2-D[i]),i+1) # allocate

        v = min(no_pump  , pump   )

        # record optimal policy
        if v == no_pump:
            pos = 0
        else:
            pos = 1

        record(X,i+1,pos)
        record(V,i+1,v)

        return v

T = 7
H = {}
V = {}
X = {}
ts = time.time()
for ii in xrange(0,20):
    print val(ii/10.0)

te = time.time()

print te - ts

How can I get this code nicer / more pythonic?


texts: PHP script that returns an error message based on what $_POST parameters are missing

texts:
I have a script that checks if the specified set of $_POST variables are supplied and not empty and returns an error string that is human readable.
Here's my code:
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    // Local variables initialization
    $missing = [];

    $checkVariables = [
        'name', 'address', 'contact'
    ];

    // Check for nulls or non existent payload
    foreach ($checkVariables as $item) {
        if (empty($_POST[$item]) || !array_key_exists($item, $_POST)) {
            $missing[] = $item;
        }
    }

    $missingCount = count($missing);
    if ($missingCount > 0) {
        $missingString = '';

        if ($missingCount === 1) {
            $missingString = $missing[0];
        } else if ($missingCount === 2) {
            $missingString = implode(' and ', $missing);
        } else {
            $lastItem = array_pop($missing);
            $partialMissingString = implode(', ', $missing);

            $missingString = $partialMissingString . ", and {$lastItem}";
        }

        $verb = $missingCount > 1 ? 'are' : 'is';
        $field = $missingCount > 1 ? 'fields' : 'field';
        $errorString = "Incomplete information received. " .
            "The {$missingString} {$field} {$verb} missing. " .
            "Please check your inputs and try again.";

        // Exits the script
        OutputResponse::sendResponse(400, $errorString);
    }
    // if there's no missing continue running the script
    // more code here but it's not the focus of this code review
}

My OutputResponse code:
class OutputResponse
{
    public static function sendResponse(string $statusCode, $messageBody): void
    {
        if ($statusCode == 500) {
            header("HTTP/1.1 500 Internal Server Error");
        } else if ($statusCode == 405) {
            header('HTTP/1.1 405 Method Not Allowed');
        } else if ($statusCode == 404) {
            header("HTTP/1.1 404 Not Found");
        } else if ($statusCode == 403) {
            header("HTTP/1.1 403 Forbidden");
        } else if ($statusCode == 401) {
            header("HTTP/1.1 401 Unauthorized");
        } else if ($statusCode == 400) {
            header("HTTP/1.1 400 Bad Request");
        } else {
            header("HTTP/1.1 200 OK");
        }

        header('Content-Type: application/json');
        echo json_encode([
            'code' => $statusCode,
            'data' => $messageBody
        ]);

        exit;
    }
}

The script expects $_POST['name'], $_POST['address'], and $_POST['contact'] to be not null or empty. The array keys to be checked are in the $checkVariables array.
For simplification, I'm dropping the $_POST in the next examples.
If name is the only one missing:
{
    "code": "400",
    "data": "Incomplete information received. The name field is missing. Please check your inputs and try again."
}

If name and contact are missing:
{
    "code": "400",
    "data": "Incomplete information received. The name and contact fields are missing. Please check your inputs and try again."
}

If all three are missing:
{
    "code": "400",
    "data": "Incomplete information received. The name, address, and contact fields are missing. Please check your inputs and try again."
}

Personally, the part on the if ($missingCount > 0) block is the messiest or unoptimized.
Any improvements or critiques are welcome!


texts: First stage of a complex calculator implementation in C++

texts:
The following code shows the primary data structure of my calculator.

Header file contents :- theCalc.hpp

#ifndef THECALC_H_
#define THECALC_H_

#include "iostream"
#include "utility"
#include "string"
#include "cstring"
#include "cmath"

using namespace std;

class theCalc
{

protected :
    pair <float, float> inputNumberPair;
    pair <float, float> outputNumberPair;
    float flFirstNumber;
    float flSecondNumber;

public :
    void getTheInputs (string firstNumber, string secondNumber);
};

#endif

Implementation file content :- theCode.cpp

#include "theCalc.h"

void theCalc::getTheInputs(string firstNumber, string secondNumber)
{
    flFirstNumber = stof (firstNumber);
    if (!secondNumber.empty())
    {
    flSecondNumber = stof (secondNumber);
    }
    inputNumberPair = make_pair(flFirstNumber, flSecondNumber);

    cout << inputNumberPair.first << endl;
    if (!secondNumber.empty())
        {
    cout << inputNumberPair.second << endl;
        }
}

Someone to go through the code and please suggest me whether I am doing good in OOP and data structure implementation. Please suggest me is my methodologies good as a robust algorithm or I am making things complicated unnecessarily.

I am now in the learning process and need my code to be reviewed as I am a beginner.

Please take a look at the shared github the following link for the overall code.

https://github.com/arviCV/bHive2


texts:
I am developing a network application and therefor need to specify the packets I want to send. I have a basic interfaces class and one for the packets that implement them.

public interface IPacket
{
}

public interface IServerPacket : IPacket
{
}

public interface IServerChatPacket : IServerPacket
{
    ServerChatPacketType Type { get; }
}

public interface IServerAccountPacket : IServerPacket
{
    ServerAccountPacketType Type { get; }
}

The specification of an IServerPacket is needed for easier and faster serialization. Anyways, now I can use these sub-interfaces for chat server and account communication with the connected clients.

[Serializable]
public struct ServerChatIncomingMessagePacket : IServerChatPacket
{
    public readonly string text;

    public ServerChatPacketType
    {
        get { return ServerChatPacketType.IncomingMessage; }
    }

    public ServerChatIncomingMessagePacket(string text)
    {
        this.text = text;
    }
}

[Serializable]
public struct ServerAccountAnswerLoginPacket : IServerAccountPacket
{
    public readonly bool success;

    public ServerAccountPacketType
    {
        get { return ServerAccountPacketType.AnswerLogin; }
    }

    public ServerAccountAnswerLoginPacket(bool success)
    {
        this.success = success;
    }
}

Is this the right way to do it? Currently I really have no problems with this, but maybe I am using the interfaces or structs wrong? I am not new into C# or OOP but there may be some way that solves this in a different manner or with better performance (structs have a chance to hold much data which is unpractical for this type kind)?


texts: Bash function to create the next SVN release tag

texts:
I've created the below script and would appreciate any feedback.

# svn directory ^/tags/release/
# 1/
# 2/
# 3/
# 4/
# usage: svnnextrelease fixes email formatting
# generated line: svn cp ^/trunk ^/tags/release/# -m'fixes email formatting'

function svnnextrelease(){
NextVersion=$(svn ls ^/tags/release | tail -n 1 | while read tag; do expr $(echo "${tag%?}") + 1; done)
# svn ls ^/tags/release, listing the directories
# tail -n 1, give me the last (latest) directory
# while loop reads result
# expr $(echo "${tag%?}") + 1, echo statment removes the "/" so 4/ becomes 4. expr then increments it.
# echo $NextVersion; 5

svn cp ^/trunk ^/tags/release/$NextVersion -m'$@'
}


texts: Module that warns (a chatbot) about high rate of messages

texts:
This is a module I use in chatbot type programs which issue responses to certain private messages from other users. I run incoming messages through this in order to limit the number of responses a user is able to provoke within a short amount of time.

guardian.py

import time

class Guardian:
    ''' Anti-flooding mechanism. Tracks how fast users are sending messages. '''

    def __init__(self, flood_limit):
        # Abstract number that represents how quickly you can flood
        self.FLOOD_LIMIT = flood_limit
        # "username": (int) goes down with time, goes up with every message
        self.dict = {}
        self.timer = time.time()

    def update_timer(self):
        ''' Count down the flood timer values for every logged user. '''
        now = time.time()

        time_elapsed = now - self.timer

        self.timer = now

        cooled_down_users = []

        # Check every logged user against the timer and prune cooled-down ones.
        for user in self.dict:
            self.dict[user] -= time_elapsed

            if self.dict[user] < 0:
                cooled_down_users.append(user)

        for user in cooled_down_users:
            del self.dict[user]

    def is_flooding(self, user, limit=None):
        ''' Tallies a user and returns True if they are above the limit. '''
        if limit == None:
            limit = self.FLOOD_LIMIT

        self.update_timer()

        if user in self.dict:
            self.dict[user] += 2

            if self.dict[user] > limit:
                return True
            else:
                return False

        else:
            self.dict[user] = 2
            return False

Usage looks something like this:

import guardian

anti_flood = guardian.Guardian()

... # Receive some message from the network, etc..

flood_warning = anti_flood.is_flooding(username, OPTIONAL_FLOOD_LIMIT_INTEGER)

if flood_warning:
    reply = "You are sending too many requests too quickly."
else:
    reply = "Here is the response you requested."

... # Send a message back, change something based on the request, and so on.

I have tried to make the module more or less general purpose, so that it could be used for other, similar tasks, such as kicking / banning users who flood a chat room. However, the way it is actively running through its internal dict of users on every message might cause issues in high traffic applications.

I can also imagine a potential issue if many different users conspire to flood the script with messages, therefore bypassing the individual limit.

I'm primarily looking for critique and guidance on readability, usability, generally anything pertaining to having my code read and used by other developers, but design, functionality, optimization, anything goes, of course.

My aim is to take a step toward becoming a useful programmer in the future, rather than just making stuff that never leaves the confines of my hard drive.


texts:
I am learning python by solving python module from HackerRank. This problem is Find the Percentage.

  You have a record of N students. Each record contains the student's
  name, and their percent marks in Maths, Physics and Chemistry. The
  marks can be floating values. The user enters some N integer followed
  by the names and marks for N students. You are required to save the
  record in a dictionary data type. The user then enters a student's
  name. Output the average percentage marks obtained by that student,
  correct to two decimal places.

  Sample Input 0

3
Krishna 67 68 69
Arjun 70 98 63
Malika 52 56 60
Malika

  Sample Output 0

56.00

I need to improve this code by using better functions available in python.

def percentage(name):
    """
    Find percentage of marks of the student
    """

    marks = student_marks[name]
    total_marks = 0
    for mark in marks:
        total_marks += mark

    return format(total_marks/len(marks), '.2f')

if __name__ == '__main__':
    n = int(input())
    student_marks = {}
    for _ in range(n):
        name, *line = input().split()
        scores = list(map(float, line))
        student_marks[name] = scores
    query_name = input()
    print(percentage(query_name))


texts: Deleting a node in a singly linked list?

texts:
Please critique the following code on removing a node from a singly linked list, at the moment it seems to me like the code is quite clunky.
typedef struct Node {
    int data;
    struct Node* next;
}Node;

Node* create(int A[], int n){
    Node *head = malloc(sizeof(Node));
    Node *temp = NULL;
    Node *tail;
    head->data = A[0];
    head->next = NULL;
    tail = head;
    int i;
    for (i = 1; i < n; i++){
        temp = malloc(sizeof(Node));
        temp->data = A[i];
        temp->next = NULL;
        tail->next = temp;
        tail = temp;
    }
    return head;
}

void delete(Node** head, int index) {
    Node* temp;
    Node* curr;
    Node* prev = NULL;
    curr = *head;
    int pos;
    if (*head == NULL) {
        return;
    }
    if (index == 0) {
        temp = curr->next;
        *head = temp;
        free(curr);
    }
    else {
        for (pos = 0; pos < index; pos++) {
            prev = curr;
            curr = curr->next;
        }
        prev->next = curr->next;

        free(curr);
    }

}

int main(){
    int A[] = {3, 5, 7, 9, 10};
    Node *head = create(A, 5);
    delete(&head, 1);
    return 0;
   }


texts: Open source Pastebin tool made in JSP and servlet

texts:
I'm a student and still studying. I just made my own Pastebin tool to generate source code. I've also contributed this project as an open source. You could see this project from here.

If you wish to see the demo, you could visit here.

Now after this, I've made this project using JSP and servlet. Actually, when the user presses "Generate source codes", the URL looks something like this:

  http..//viewCode.jsp?id=10428

Please contribute your opinions here. Here is my source code to generate the URL like this:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>

<%@ page language="java" import="java.sql.*" %>
<%@ page language="java" import="java.util.*" %>
<%@ page language="java" import="org.apache.commons.lang3.StringEscapeUtils" %>
<%@ page language="java" import="org.apache.*" %>

<%

    String submit_code1=request.getParameter("paste_code");
    String title_code=request.getParameter("title_code");

    Random random = new Random(System.currentTimeMillis());
    int gen_key=10000 + random.nextInt(20000);

    String submit_code2 = StringEscapeUtils.escapeHtml4(submit_code1);

    try{
    Class.forName("com.mysql.jdbc.Driver");
    Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/db_name", "root", "1234");
    PreparedStatement pstmt=con.prepareStatement("insert into paste_tool(gen_key, title, source_codes) VALUES(?, ?, ?)");

    pstmt.setInt(1, gen_key);
    pstmt.setString(2, title_code);
    pstmt.setString(3, submit_code2);

    pstmt.executeUpdate();

    pstmt.close();

    response.sendRedirect("viewCode.jsp?id="+gen_key);

}
catch(Exception e){
    e.printStackTrace();
}
%>


texts: SICP exercise 1.28 - miller-rabin primality test

texts:
From SICP

  Exercise 1.28:

  One variant of the Fermat test that cannot be fooled is
  called the Miller-Rabin test (Miller 1976; Rabin 1980). This starts
  from an alternate form of Fermat’s Little Theorem, which states that
  if \$n\$ is a prime number and \$a\$ is any positive integer less than \$n\$, then
  \$a\$ raised to the \$n-1\$-st power is congruent to \$1 \mod n\$.

  To test the
  primality of a number \$n\$ by the Miller-Rabin test, we pick a random
  number \$a < n\$ and raise \$a\$ to the \$n-1\$-st power \$\mod n\$ using the expmod
  procedure. However, whenever we perform the squaring step in expmod,
  we check to see if we have discovered a “nontrivial square root of \$1
\mod n\$,” that is, a number not equal to \$1\$ or \$n-1\$ whose square is
  equal to \$1 \mod n\$.

  It is possible to prove that if such a nontrivial
  square root of \$1\$ exists, then \$n\$ is not prime. It is also possible to
  prove that if \$n\$ is an odd number that is not prime, then, for at least
  half the numbers \$a < n\$, computing \$a^{n-1}\$ in this way will reveal a
  nontrivial square root of \$1 \mod n\$. (This is why the Miller-Rabin
  test cannot be fooled.)

  Modify the expmod procedure to signal if it
  discovers a nontrivial square root of \$1\$, and use this to implement the
  Miller-Rabin test with a procedure analogous to fermat-test. Check
  your procedure by testing various known primes and non-primes.

  Hint:
  One convenient way to make expmod signal is to have it return \$0\$.

According to the book this is a probabalistic algorithm. My tests gave mostly correct results.

Here's my code.

;; modified expmod procedure
(define (expmod base exp m)
  (cond ((= exp 0) 1)
        ((even? exp)
         (if (and (not (= base 1))
                  (not (= base (- m 1)))
                  (not (= exp (- m 1)))
                  (= (remainder base m) 1))
             0
             (remainder
              (expmod (square base) (/ exp 2) m)
              m)))
        (else
         (remainder
          (* base (expmod base (- exp 1) m))
          m))))

(define (miller-rabin-test n)
  (define (try-it a)
    (= (expmod a (- n 1) n) 1))
  (try-it (+ 1 (random (- n 1)))))

(define (fast-prime? n times)
  (cond ((= times 0) true)
        ((miller-rabin-test n)
         (fast-prime? n (- times 1)))
        (else false)))

How can I improve this code and make it faster?


texts:
I solved this prime number verifier problem:

import scala.io.StdIn

object Main extends App {
  val testCases = StdIn.readInt

  for (i <- 0 until testCases) {
    val limits = StdIn.readLine.split(" ")
    val m: Int = limits(0).toInt
    val n: Int = limits(1).toInt
    for (j <- m to n) {
      var prime = false
      if (isPrime(j))
        println(j)
    }
    println()
  }

  def isPrime(number: Int) : Boolean = {
    if (number == 1)
      false
    else {
      for (h <- 2 to Math.sqrt(number).asInstanceOf[Int]) {
        if (number % h == 0 || number == 1) {
          return false
        }
      }
      true
    }
  }
}

I wrote the code this way because Scala doesn't have break statements, and return statements aren't very functional either. How do I go about writing this code in a more functional and idiomatic manner?


texts: Bash script for getting geolocation (latitude, longitude and country code)

texts:
I have a bash script, where I need to get the user's geolocation (latitude, longitude and country code). If a GPS device is present, I use gpspipe. But a lot of laptops/computers don't have GPS devices (yet). I need the location as accurate as possible, and getting the geolocation by IP address is (by far) too unreliable.

I ended up with the following bash script with the following dependencies: Python with sys, urllib and json libraries, wget and a working internet connection.

LAT=""
LNG=""
CTRY=""
IFS=$'\n'
printf "Give your location (street name, city, country, etc): "
read LOCATION
while [ -z "$LAT" ]; do
    printf "Querying Google Geo API... "
    LOCATION=$(echo $LOCATION | python -c "exec(\"import urllib,sys;\\nprint(urllib.quote_plus(sys.stdin.readline()))\")")
    URL="https://maps.googleapis.com/maps/api/geocode/json?address=$LOCATION"
    GOOGLEAPIS=$(wget -qO- $URL)
    STATUS=$(echo $GOOGLEAPIS | python -c "exec(\"import json,sys;\\nobj=json.load(sys.stdin);\\nprint(obj['status'])\")")

    case "$STATUS" in
    *OK*)
        OPTIONS=($(echo $GOOGLEAPIS | python -c "exec(\"import json,sys;\\nobj=json.load(sys.stdin);\\nfor x in obj['results'][::]:print(x['formatted_address'])\")"))
        OPT=$OPTIONS
        NRFOUND=${#OPTIONS[@]}
        IDX="0"

        if [[ $NRFOUND -ge 2 ]]; then
            printf "More than one option found. Please select your location from the list:\n"
            select OPT in "${OPTIONS[@]}";
            do
                IDX=$(($REPLY - 1))
                break
            done
        fi
        LAT=$(echo $GOOGLEAPIS | python -c "exec(\"import json,sys;\\nobj=json.load(sys.stdin);\\nprint(obj['results'][$IDX]['geometry']['location']['lat'])\")")
        LNG=$(echo $GOOGLEAPIS | python -c "exec(\"import json,sys;\\nobj=json.load(sys.stdin);\\nprint(obj['results'][$IDX]['geometry']['location']['lng'])\")")
        CTRY=$(echo $GOOGLEAPIS | python -c "exec(\"import json,sys;\\nobj=json.load(sys.stdin);\\nfor x in obj['results'][$IDX]['address_components']:\\n\\tif x['types'][0] == 'country':print(x['short_name'])\")")
        break
        ;;
    *)
        printf "Google could not find your location based on your query. Google says: $STATUS\nPlease enter another location description.\n"
        read LOCATION
        ;;
    esac
done
unset $IFS
printf "Selected location: %s\nYour latitude/longitude location set to: (%s, %s).\nYour countycode is set to: %s\n" $OPT $LAT $LNG $CTRY

The code works (as required here on CR) and a sensible geolocation is found for a lot of queries. But, as I'm no seasoned shell writer, I'd like your review on this code. Do you see any pitfalls, corrections, improvements (on the coding), etc?


texts:
Just for the fun of it, I wanted to have a hidden keypress function on my website that performs an event when the user types in the Contra code for thirty lives. I'm curious how the implementation for this simple piece of code holds up and where it could be improved.

Note: keypress doesn't seem to detect the arrow keys so I used the arrows from the numpad

var codeCount = 0;

//[up, up, down, down, left, right, left, right, b, a, start]
var contraCode = [38, 38, 40, 40, 37, 39, 37, 39, 66, 65, 13];

$(window).keydown(function(input) {
  var key = input.which;
  if (contraCode[codeCount] === key) {
     codeCount++;

     //if 11 keys have sequentially matched the cheat code
     if (codeCount === 11) {
        alert('You got 30 lives!');
     }
  }
  else {
     codeCount = 0;
  }
});


texts: Passing Row Index of TableViewCell (custom) to another view controller

texts:
I have been trying to achieve the below requirements to get them working.  Am I doing it the right way?

We have a table with customised Cell (say: firstViewController)
Customised Cell has a button, click event in this button, and carries row index value to another view controller.  In this view controller I will use this row index to access the data model from first view controller.

Annotation: Each row has values associated with unique Dictionary value in Array based on row Index.

Pseudo Code: (pasted only necessary code)

FirstViewController.h

 @interface firstViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>

 @property NSMutableArray *MasterRecords;   //  Each element in Array is dictionary.
 @property (weak, nonatomic) IBOutlet UITableView *tblMasterTable;
 @end

FirstViewController.m

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    static NSString *columnIdfer = @"items";
    StudentCell *cell = (StudentCell *)[tableView dequeueReusableCellWithIdentifier:columnIdfer];
    if ( cell == nil)
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"StudentCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }

    if (indexPath.row < [self.MasterRecords count])
    {

        cell.iRecordIndex = indexPath.row;
    }

    return cell;

}

In the above code I set the iRecordIndex to IndexPath.row

StudentCell.h

@interface StudentCell : UITableViewCell
@property NSInteger iRecordIndex;
@property (weak, nonatomic) IBOutlet UIButton *btnSubmit;  // It pushes viewController.
@end

StudentCell.m

- (IBAction)btnSubmitPressed:(id)sender {

     NextViewController *sVC = [[NextViewController alloc]     initWithRecIndex:@"NextViewController" bundle:nil Index:self.iRecordIndex];

  // Pushing NextViewController to NavigationViewController.
}

NextViewController.h

@interface NextViewController : UIViewController <MKMapViewDelegate>
- (id)initWithRecIndex:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil  Index:(NSInteger )iRecIndex;
@property NSInteger iRecordIndex;
@end

NextViewController.m

 - (id)initWithRecIndex:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil  Index:(NSInteger )iRecIndex
{
      self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.iRecordIndex = iRecIndex;
    }

    return self;
}

-(void) viewWillAppear:(BOOL)animated
{
    //Get FistViewController.   say  ==> fvc.

    NSMutableArray *mRec = [fvc MasterRecords];
    NSMutableDictionary *mDict = [mRec objectAtIndex:self.iRecordIndex];

    NSLog (@" value1 is %@ ", [mDict valueForKey:@"value1"]);
    NSLog (@" value2 is %@ ", [mDict valueForKey:@"value2"]);

   // Using value1, and value2 to display MKMapView.
}

Is this the right approach, or should I improve it?


texts:
I have an array of objects, each with a dimensions field for storing various metrics related to the object, e.g. length, width, weight, etc.  Each object may be different in terms of what metrics it has.

I have a solution but not sure if it's optimal.

let dimensions = [{ a: 1, b: 2, c: 3}, { a: 2, c: 1, d: 3 }, { b: 1, e: 8, f: 1 }]

// get all keys
let dimensionsFields = _.map(dimensions, Object.keys);
// => [[a, b, c], [a, c, d], [b, e, f]]

// flatten
dimensionsFields  = _.flatten(dimensionsFields );
// => [a, b, c, a, c, d, b, e, f]

// filter out duplicates
dimensionsFields  = _.uniq(dimensionsFields );
// => [a, b, c, d, e, f]

// init return data
let dimensionsData = {};

// loop through available metrics, add up the values
dimensionsFields.forEach(field => {
  dimensionsData[field] = _.reduce(dimensions, function(a, b) {
    return a + b[field];
  }, 0);
});
// => { a: 3, b: 3, c: 4, d: 3, e: 8, f: 1 }


texts:
I have written a Backbone View (javascript) for a component called "twist-panel".

A twist panel is basically a card flip, it has a front and back side, and can flip to the back and to the front.

Here is the code:

var TwistPanel = Backbone.View.extend({
  initialize: function() {
    this.$front = this.$el.find('.twist-panel-side-front');
    this.$back = this.$el.find('.twist-panel-side-back');

    this.atFront = true;
    this.isFlipping = false;

    // Fix the height of the twist panel container.
    this.$el.height(this.$front.outerHeight(true));
  },
  toBack: function() {
    var self = this;

    if (this.isFlipping || !this.atFront) return;

    // Fix height.
        this.$el.height(this.$back.outerHeight(true));

        this.$front.afterTransition(function() {
            self.atFront = false;
            self.isFlipping = false;
            self.trigger('twist', 'back');
        });

        this.isFlipping = true;
        this.$el.addClass('twist');
  },
    toFront: function(callback) {
            var self = this;

        if (this.isFlipping || this.atFront) return;

        // Fix height.
        this.$el.height(this.$front.outerHeight(true));

        this.$back.afterTransition(function() {
            self.atFront = true;
            self.isFlipping = false;
            self.trigger('twist', 'front');
        });

        this.isFlipping = true;
        this.$el.removeClass('twist');
    }
});

As you can see in the code above, there is a lot of code duplication.
I would really appreciate some help on getting the code DRY.


texts: Determine which range a character falls into

texts:
I am categorizing terms depending on what letter the term starts with.  What is the cleanest way to do so?

var parentGroup,
    startsWith = "H"; // Just simplifying and giving a static example here.

switch(startsWith) {
    case "A":
    case "B":
    case "C":
    case "D":
    case "E":
    case "F":
        parentGroup = "A-F";
        break;
    case "G":
    case "H":
    case "I":
    case "J":
    case "K":
    case "L":
    case "M":
        parentGroup = "G-M";
        break;
    case "N":
    case "O":
    case "P":
    case "Q":
    case "R":
        parentGroup = "N-R";
        break;
    case "S":
    case "T":
    case "U":
    case "V":
    case "W":
    case "X":
    case "Y":
    case "Z":
        parentGroup = "S-Z";
        break;
    default:
        parentGroup = "0-9";
}


texts: Shopping cart login and coupon code validation

texts:
I am figuring out how I could make the following query more secure:
I have already used mysqli_real_escape_string but I doubt that adds much to security.

I have looked into the using prepared statements but I also have to take into account the following line:

$check_customer = mysqli_num_rows($run_c);

My solution:

   $c_email = mysqli_real_escape_string($con,$_POST['email']);
        $c_pass = mysqli_real_escape_string($con,$_POST['pass']);
        $couponCodeLogin = mysqli_real_escape_string($con,$_POST['couponCodeLogin']);
$couponCodeLoginAmount = mysqli_real_escape_string($con,$_POST['couponCodeLoginAmount']);

        $sel_c = "select * from customers where customer_pass='$c_pass' AND customer_email='$c_email'";

        $run_c = mysqli_query($con, $sel_c);
        $check_customer = mysqli_num_rows($run_c);
        if($check_customer==0){

        echo "<script>
        document.getElementById('loginError').innerHTML = 'Password or email is incorrect, please try again.'
        </script>";
        exit();
        }

        if($check_customer>0){
                    $crs_id = $_GET['crs_id'];

     $insert_c = "insert into customers (customer_email,coupon_code_login,coupon_code_login_amount) values ('$c_email','$couponCodeLogin','$couponCodeLoginAmount')";
                $run_c = mysqli_query($con, $insert_c);

                $_SESSION['userCoupon'] = $_POST['couponCodeLoginAmount'];

        $_SESSION['customer_email']=$c_email;
                        $_SESSION['userCouponName'] = $_POST['couponCodeLogin'];

        echo "<script>window.open('coursePayment.php?crs_id=$crs_id','_self')</script>";

        }
        else {
        $_SESSION['customer_email']=$c_email;

        echo "<script>window.open('coursePayment.php?crs_id=$crs_id','_self')</script>";

        $_SESSION['userCoupon'] = $_POST['couponCodeLoginAmount'];
                $_SESSION['userCouponName'] = $_POST['couponCodeLogin'];

        }
    }

and

        $fname= mysqli_real_escape_string($con,$_POST['fname']);
        $lname = mysqli_real_escape_string($con,$_POST['lname']);
        $email = mysqli_real_escape_string($con,$_POST['email']);
        $pnumber = mysqli_real_escape_string($con,$_POST['pnumber']);
 $couponCodeRegister=mysqli_real_escape_string($con,$_POST['couponCodeRegister']);
$couponCodeRegisterAmount = mysqli_real_escape_string($con,$_POST['couponCodeRegisterAmount']);

        $pass = mysqli_real_escape_string($con,$_POST['pass']);
        $cname = mysqli_real_escape_string($con,$_POST['cname']);
        $cposition = mysqli_real_escape_string($con,$_POST['cposition']);

         $insert_c = "insert into customers (customer_fname,customer_lname,customer_email,customer_number,customer_pass,customer_cname,customer_cposition,coupon_code_register,coupon_code_register_amount) values ('$fname','$lname','$email','$pnumber','$pass','$cname','$cposition','$couponCodeRegister','$couponCodeRegisterAmount')";

        $run_c = mysqli_query($con, $insert_c);

        $insert_email = "select * from customers";
        $run_email = mysqli_query($con, $insert_email);

        $find_email = mysqli_fetch_array($run_email);
        $demail = $find_email['customer_email'];

        if($email!= $demail)
       {
         $crs_id = $_GET['crs_id'];

         $_SESSION['userCoupon'] = $_POST['couponCodeRegisterAmount'];
         $_SESSION['userCouponName'] = $_POST['couponCodeRegister'];
         $_SESSION['customer_email']=$email;

         echo "<script>
         document.getElementById('registerError').innerHTML = 'Account has been created successfully, Thanks!'
         </script>";
         echo "<script>window.open('coursePayment.php?crs_id=$crs_id','_self')</script>";

       }