texts: Calling a Luhn check function when a credit card field changes

texts:
I feel like I should not be duplicating the code to gather the credit card number, but I am not sure how best to do it. Any suggestions?

$('input[name="payment\[cc_number\]"]').keyup(function() {
    var ccNum = $(this).val();
    ccNum = ccNum.replace(/[^\d]/g, '');
    setSelectValue(ccNum);
});

$('input[name="payment\[cc_number\]"]').blur(function(ccNum) {
    var ccNum = $(this).val();
    ccNum = ccNum.replace(/[^\d]/g, '');
    if (!luhnCheck(ccNum)) {
        alert('Please enter a valid credit card number.');
    }
});


texts: Simple chart-viewing JavaFX example on Nashorn

texts:
I'm hacking together some first examples on JavaScript (Nashorn) for viewing a simple chart. Since my background is "Java programmer" I'm sure there are ways where I can have more benefit from JavaScript syntax than I'm using.

I'm open to criticism to get it more shorter, more elegant, more idiomatic than a Java coder writes it down in his first attempts.

load("fx:base.js");
load("fx:controls.js");

var Button = javafx.scene.control.Button;
var StackPane = javafx.scene.layout.StackPane;
var Scene = javafx.scene.Scene;

function start(primaryStage) {
    primaryStage.title = "Hello World!";

    var xAxis = new NumberAxis();
    xAxis.setLabel("Number of Month");
    var yAxis = new NumberAxis();

    var lineChart = new LineChart(xAxis, yAxis);
    lineChart.setTitle("Stock Monitoring 2010");

    var series1 = new XYChart.Series();
    series1.setName("Reference portfolio");

    [new XYChart.Data(1,2),
     new XYChart.Data(2,1),
     new XYChart.Data(3,9),
     new XYChart.Data(4,5),
     new XYChart.Data(5,7),
     new XYChart.Data(6,6)
    ].forEach(function(item){
        series1.data.add(item);
    });

    lineChart.data.add(series1);

    var series2 = new XYChart.Series();
    series2.setName("My portfolio");

    [new XYChart.Data(1,12),
    new XYChart.Data(2,11),
    new XYChart.Data(3,19),
    new XYChart.Data(4,15),
    new XYChart.Data(5,17),
    new XYChart.Data(6,16)].forEach(function(item){
        series2.data.add(item);
    })

    lineChart.data.add(series2);

    var scene = new Scene (lineChart, 800, 600);
    primaryStage.scene = scene;
    primaryStage.show();
}


texts: Boost Threads - Producer Consumer threads with synchronization

texts:
Please review this for concurrency  correctness:

#include <iostream>
#include <queue>

#include "boost\thread.hpp"
#include "boost\timer.hpp"

std::queue<int> itemQ;

boost::mutex m;
boost::condition_variable qFull, qEmpty;

const int max_size_q = 5;

void producer()
{
    int i = 0;
    while (1)
    {
        boost::this_thread::sleep(boost::posix_time::millisec(1000));
        boost::mutex::scoped_lock lock(m);
        if (itemQ.size() <= max_size_q)
        {
            itemQ.push(++i);
            qEmpty.notify_one();
        }
        else
        {
            std::cout << "Q Full.notify_one Producer Waiting" << std::endl;
            qFull.wait(lock);
            std::cout << "Producer Notified to Continue" << std::endl;
        }
    }

}

void consumer()
{
    while (1)
    {
        boost::this_thread::sleep(boost::posix_time::millisec(4000));

        boost::mutex::scoped_lock lock(m);

        if (itemQ.size() == 0)
        {
            std::cout << "Q Empty. Consumer " << boost::this_thread::get_id() <<" Waiting" << std::endl;
            qEmpty.wait(lock);
            std::cout << "Consumer Notified to Continue" << std::endl;
        }
        else
        {
            std::cout << itemQ.front() << std::endl;
            itemQ.pop();
            qFull.notify_one();
        }

    }
}

int main()
{
    boost::thread producerthread(producer);

    boost::thread consumerthread1(consumer);
    boost::thread consumerthread2(consumer);
    boost::thread consumerthread3(consumer);
    boost::thread consumerthread4(consumer);
    boost::thread consumerthread5(consumer);

    consumerthread1.join();
    consumerthread2.join();
    consumerthread3.join();
    consumerthread4.join();
    consumerthread5.join();
}


texts: Transmitting/Sending big packet safely using TcpClient/Socket

texts:
I am writing a TCP based client that need to send and receive data. I have used the Asynchronous Programming Model (APM) provided for Socket class by the .NET Framework.

After being connected to the socket, I start waiting for data on the socket using BeginReceive.

Now, while I am waiting for the data on the Socket, I may need to send data over the socket. And the send method can be called multiple times,

So I have make sure that

All the bytes from previous Send call is entirely sent.
The way I am sending the Data is safe considering that, while a data send is in progress, any call to send data can be made.

This is my first work on socket, So is my approach right to send data ?

    private readonly object writeLock = new object();
    public void Send(NetworkCommand cmd)
    {
        var data = cmd.ToBytesWithLengthPrefix();
        ThreadPool.QueueUserWorkItem(AsyncDataSent, data);
    }

    private int bytesSent;
    private void AsyncDataSent(object odata)
    {
        lock (writeLock)
        {
            var data = (byte[])odata;
            int total = data.Length;
            bytesSent = 0;
            int buf = Globals.BUFFER_SIZE;
            while (bytesSent < total)
            {
                if (total - bytesSent < Globals.BUFFER_SIZE)
                {
                    buf = total - bytesSent;
                }
                IAsyncResult ar = socket.BeginSend(data, bytesSent, buf, SocketFlags.None, DataSentCallback, data);
                ar.AsyncWaitHandle.WaitOne();
            }
        }
    }

How object is changed into byte[], sometimes the NetworkCommand can be as big as 0.5 MB

    public byte[] ToBytesWithLengthPrefix()
    {
        var stream = new MemoryStream();
        try
        {
            Serializer.SerializeWithLengthPrefix(stream, this, PrefixStyle.Fixed32);
            return stream.ToArray();
        }
        finally
        {
            stream.Close();
            stream.Dispose();
        }
    }


texts: Best way to manage a device information class

texts:
This is probably a really simple question.

An embedded device I'm working with will store the device information in an xml file.

In my code, I want to read this xml file and freely reference to it wherever I need to, so I made a simple helper class:

public class DeviceInformation {
    public static final String XML_DIRECTORY_ON_DEVICE = "/xml/";
    public static final String ROOT_DEVICE_XML_FILE = "rootdevice.xml";

    public static String DEVICE_ID;
    public static String DEVICE_TYPE;
    public static String HOME_ID;

    public DeviceInformation() {
        File xmlFile = new File(XML_DIRECTORY_ON_DEVICE + ROOT_DEVICE_XML_FILE);
        if (!xmlFile.exists())
            return;
        RootDeviceXMLReader rootDeviceXMLReader = new RootDeviceXMLReader(xmlFile);
        DeviceInfoStruct deviceInfoStruct = rootDeviceXMLReader.getDeviceInfoStruct();
        DEVICE_ID = deviceInfoStruct.getDeviceID();
        DEVICE_TYPE = deviceInfoStruct.getDeviceType();
        HOME_ID = deviceInfoStruct.getHomeID();
    }
}

And then I'd just get my device id by DeviceInformation.DEVICE_ID. Same goes for type and home_id.

But this approach just doesn't seem elegant. Turn the initializer into a static one? Still, I feel like there's something wrong with this whole approach and I just cannot articulate it. How can I improve this class?


texts: Generic memoize utility function for pure functions

texts:
Given the following generic memoize utility for pure functions with type hints:
function memoize(callable $fn, callable $serialize = null): callable {
    $serialize = $serialize ? $serialize : 'serialize';

    return function(...$args) use ($fn, $serialize) {
        static $cache = [];
        $k = $serialize($args);
        return isset($cache[$k]) ? $cache[$k] : ($cache[$k] = $fn(...$args));
    };
}

Is the callable type hint here preferred as opposed to closure? I'm also not sure if I'm being too pedantic with the type hints and whether my use of static here is recommended?
I'd appreciate any feedback on the code above.


texts:
I have the following code which reads data from a key/value data storage.
At some stage I want to go through everything in the storage and check expiry times and remove values - as done in the code below.

My problem here is that dataMapStorage.get(key) is called twice for keys which pass the filter and this can potentially be a heavy operation (I/O).

dataMapStorage.keys
  .filter { key =>
    val value = dataMapStorage.get(key)
    currentTime.getMillis - value.getMillis > timeout
  }
  .foreach { key =>
    val value = dataMapStorage.get(key) // Want to avid this double lookup
    // ... do some work with "value"
    dataMapStorage.remove(key)
  }

I presume the way around it is using collect (I do not want to map through the storage and extract all the values as this might be large), but am stuck here too with the 'get' method:

dataMapStorage.keys
  .collect {
    case key if {
      val value = dataMapStorage.get(key)
      currentTime.getMillis - value.getMillis > timeout
    } => (key, value) // How can I get the "value"???
  }
  .foreach { pair =>
    val value = pair._2
    // ... do some work with "value"
    dataMapStorage.remove(pair._1)
  }

How can I run this code getting the value from storage only once and not first creating a list of all the values?


texts:
Here is the code that I am using on a website's contact form:

HTML file:

    <form name="ajax-form" id="ajax-form" action="php-file.php" method="post">
        Name: *
            please enter name

        <input name="name" id="name" type="text" />
        E-Mail: *
            please enter e-mail
            e-mail is not a valid format

        <input name="email" id="email" type="text" />
        Message:
        <textarea name="message" id="message"></textarea>
        <button id="send">Submit</button>

There was a problem validating the form please check!

The connection to the server timed out!

    </form>

Successfully sent!!

PHP file (php-file.php):

<?php

$send_to = "contact@example.com";
$send_subject = "Ajax form ";

$f_name = cleanupentries($_POST["name"]);
$f_email = cleanupentries($_POST["email"]);
$f_message = cleanupentries($_POST["message"]);
$from_ip = $_SERVER['REMOTE_ADDR'];
$from_browser = $_SERVER['HTTP_USER_AGENT'];

function cleanupentries($entry) {
    $entry = trim($entry);
    $entry = stripslashes($entry);
    $entry = htmlspecialchars($entry);

    return $entry;
}

$message = "This email was submitted on " . date('m-d-Y') .
"\n\nName: " . $f_name .
"\n\nE-Mail: " . $f_email .
"\n\nMessage: \n" . $f_message .
"\n\n\nTechnical Details:\n" . $from_ip . "\n" . $from_browser;

$send_subject .= " - {$f_name}";

$headers = "From: " . $f_email . "\r\n" .
    "Reply-To: " . $f_email . "\r\n" .
    "X-Mailer: PHP/" . phpversion();

if (!$f_email) {
    echo "no email";
    exit;
}else if (!$f_name){
    echo "no name";
    exit;
}else{
    if (filter_var($f_email, FILTER_VALIDATE_EMAIL)) {
        mail($send_to, $send_subject, $message, $headers);
        echo "true";
    }else{
        echo "invalid email";
        exit;
    }
}

?>

Is this code safe? How secure is the email address from users? Am I using best practices in this implementation?


texts: Time limit exceeded in K-th symbol in Grammar (LeetCode)

texts:
I am taking efforts to solve problem K-th Symbol in Grammar - LeetCode

  K-th Symbol in Grammar

  On the first row, we write a 0. Now in every subsequent row, we look at the previous row and replace each occurrence of 0 with 01, and each occurrence of 1 with 10.

  Given row N and index K, return the K-th indexed symbol in row N. (The values of K are 1-indexed.) (1 indexed).

Examples:
Input: N = 1, K = 1
Output: 0

Input: N = 2, K = 1
Output: 0

Input: N = 2, K = 2
Output: 1

Input: N = 4, K = 5
Output: 1

Explanation:
row 1: 0
row 2: 01
row 3: 0110
row 4: 01101001

  Note:

  N will be an integer in the range [1, 30].
  K will be an integer in the range [1, 2^(N-1)].

My solution

class Solution:
    def kthGrammar(self, N: int, K: int) -> int:
        #replace function
        def replace(row: "List[int]") -> "List[int]":
            """
            rtype: row
            """
            for i in range(len(row)):
                print(row[i])
                if row[i] == 0: #0 -> 01
                    row.insert(2*i+1, 1)
                elif row[i] == 1: #1 -> 10
                    row.insert(2*i+1, 0)
            return row

        #helper function
        def helper(N: int) -> "List(int)":
            """
            rtype:the last row
            """
            #error case
            if N < 1: return []
            #base case
            if N == 1:
                res = [0]
                return res
            elif N > 1:
                return replace(helper(N-1))

        #error cases
        if N < 1 or K < 1 or K > 2**(N-1) : return None
        #recur
        row = helper(N)
        #logging.debug(f"row: {row}")
        return row[K-1]

Unfortunately it  reported Time Limit Exceeded

  Last executed input:
  30
  434991989

Review my solution:

employed tail recursion return replace(helper(N-1))
did not create a new row

It's a relatively fine solution,

What might be the reason of TLE?


texts: A simple jQuery function that removes empty or tags containing just ' '

texts:
I've made a simple function, this time in jQuery rather than JS, that just removes empty

, span and strong tags. I'm curious to see what everyone thinks about my solution as I'm relatively new to jQuery, and whether it could be improved. My original solution is as follows:

$('p').filter(function() {
 return ($(this).html().trim() == '&nbsp;');
}).remove();
$('span').filter(function() {
 return ($(this).html().trim() == '&nbsp;');
}).remove();
$('span').filter(function() {
 return ($(this).html().trim() == '');
}).remove();
$('strong').filter(function() {
 return ($(this).html().trim() == '');
}).remove();
$('p').filter(function() {
 return ($(this).html().trim() == '');
}).remove();

This isn't exactly dry... So I made a couple of other solutions:

/* MY DRIER SOLUTION 1 */
$.fn.jCleaner = function() {
    return $(this).filter(function() {
        return ($(this).text().trim() === '&nbsp;' || $(this).text().trim() === '');
        }).remove();
}
$('p, span, strong').jCleaner();

/* MY DRIER SOLUTION 2 */
function jCleaner() {
    return $(this).filter(function() {
        return ($(this).text().trim() == '&nbsp;' || $(this).text().trim() === '');
        }).remove();
}
$('p, span, strong').each(jCleaner);

And the original HTML is:

/* ORIGINAL HTML */

text

&nbsp;

text

text

text

text

&nbsp;

text

&nbsp;

text

&nbsp;

text

&nbsp;

text

So my questions are essentially how can my solutions be improved (if at all)? I had to write an entire function and then call it on each element. Thanks for any advice here.

Note: here's the solution in JS:

document.querySelectorAll("span, p, strong")
    .forEach(el => el.textContent.trim() === "" && el.parentNode.removeChild(el))


texts: Largest common multiple equal or lower than max

texts:
I made this small and easy function that returns the largest common multiple of the elements of ms that is equal to or lower than max:

LCMLthan = function(ms,max) {
    ms = sort(ms, decreasing =TRUE)
    max2 = c()
    for (m in ms)
    {
        max2=append(max2,m*floor(max/m))
    }
    max2=min(max2)
    while (T)
    {
        maxOld = max2
        for (m in ms)
        {
            if(max2%%m!=0){
                max2 = max2 - 1
                break
            }
        }
        if (maxOld==max2){
            return (max2)
        }
    }
}

### Examples
LCMLthan(c(3,5),52)
[1] 45
LCMLthan(c(178,124,17),520000)
[1] 375224

Looking at my code, it feels like there must have a cleaner and more efficient way to code this function. There is also probably a better way to name it too.


texts:
The following description is taken from CodeChef.com's Lapindrome problem.

  Lapindrome is defined as a string which when split in the middle, gives two halves having the same characters and same frequency of each character. If there are odd number of characters in the string, we ignore the middle character and check for lapindrome. For example gaga is a lapindrome, since the two halves ga and ga have the same characters with same frequency. Also, abccab, rotor and xyzxy are a few examples of lapindromes. Note that abbaab is NOT a lapindrome. The two halves contain the same characters but their frequencies do not match.
  Your task is simple. Given a string, you need to tell if it is a lapindrome.

  Input:

  First line of input contains a single integer T, the number of test cases.

  Each test is a single line containing a string S composed of only lowercase English alphabet.

  Output:

  For each test case, output on a separate line: "YES" if the string is a lapindrome and "NO" if it is not.

  Constraints:

  \$1 ≤ T ≤ 100\$
  2 \$≤ |S| ≤ 1000\$, where |S| denotes the length of S.

  Example:

  Input:

6
gaga
abcde
rotor
xyzxy
abbaab
ababc

  Output:

YES
NO
YES
YES
NO
NO

#include<stdio.h>
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        char s[1005];
        scanf("%s",s);
         int len,b[strlen(s)],z;
         int i,j,count =0;
         len=strlen(s);
         for(z=0;z<len;z++)
         {
                b[z] =1;
         }
        if(len%2 !=0)
        {
            for(i=0;i<len/2;i++)
            {
                for(j=(len/2)+1;j<len;j++)
                {
                    if(s[i] == s[j])
                    {
                        if(b[i] && b[j] )
                        {
                            b[i]=0;
                            b[j]=0;
                            count+=1;
                        }
                    }
                }
            }
        }
         else if(len%2 ==0)
        {
            for(i=0;i<len/2;i++)
            {
                for(j=(len/2);j<len;j++)
                {
                    if(s[i] == s[j])
                    {
                        if(b[i] && b[j] )
                        {
                            b[i]=0;
                            b[j]=0;
                            count+=1;
                        }
                    }
                }
            }
        }
        if(count==len/2)
            {
                printf("YES\n");
            }
            else
            {
                printf("NO\n");
            }
    }
}


texts: Modification of the headline line-height in the Compass vertical rhythm module

texts:
One thing nagged me about the compass vertical rhythm module; in the case the headline is too long and it occupies more than one line the line-height between the two lines looks way too massive and off.

Based on the following article, I've taken the adjust-font-size-to mixin source and modified and simplified things a bit (e.g. stripped out the relative font sizing part). I just wanted to get a basic working alternative take to get the possibility to get a smaller and tighter line-height for headlines with two or more lines.

@mixin adjust-headline-size-to($to-size, $from-size: $base-font-size, $magic-number: $base-line-height) {
  font-size: $font-unit * $to-size / $from-size;
  line-height: $magic-number / $to-size;
}

The question is on the code side.  Are things laid out in a clean way and on the line-height side is the math behind correct, or would there be a more reasonable and reliable way to keep the rhythm while minimizing the line-height in contrast to the regular one from adjust-font-size-to?

To illustrate what I tried to accomplish, here's a sample HTML snippet:

Mr. Worf, you sound like a man who's asking his friend if he can start dating his sister. A lot of things can change in twelve years, Admiral. How long can two people talk about nothing?

Short Headline

Mr. Worf, you sound like a man who's asking his friend if he can start dating his sister. A lot of things can change in twelve years, Admiral. How long can two people talk about nothing?

This one is a bit longer headline to show of the effect with the regular mixin

Mr. Worf, you sound like a man who's asking his friend if he can start dating his sister. A lot of things can change in twelve years, Admiral. How long can two people talk about nothing?

This one is a bit longer headline to show of the effect with the regular mixin

Mr. Worf, you sound like a man who's asking his friend if he can start dating his sister. A lot of things can change in twelve years, Admiral. How long can two people talk about nothing?

The used Scss is:

.testheadshort,
.testheadshortregular {
    @include adjust-font-size-to(29px);
}

.testheadlongmod {
    @include adjust-headline-size-to(29px);
}

The first two h2 use the regular adjust-font-size-to mixin while the last uses the mixin i wrote in my initial question. The resulting CSS for .testheadlongmod is plain simple:

.testheadlongmod {
  font-size: 1.38095em;
  line-height: 1.06897;
}

And to illustrate the difference in visual representation a screenshot in the end:

As you can see the line-height for the second headline, where the regular adjust-font-size-to mixin is used, is way off.


texts:
The following extension method is being used in our code base:

public static bool ToBool(this object src)
{
    return src != null && ((string) src).ToBool(false);
}

It leverages off another extension method:

public static bool ToBool(this string src, bool defaultValue)
{
    if (src.IsEmpty())
        return defaultValue;

    if (src.IsNumeric())
        return src.ToInt() != 0;

    var ret = false;
    if (bool.TryParse(src, out ret))
        return ret;
    return defaultValue;
}

(where the ToInt and all the Is* methods are wrappers around the appropriate objects IsNullEmpty / Parse method)

This does not 'feel' right but I cannot explain it to the author. Besides for the obvious problem of passing an object that cannot be cast to a string what other reasons are there to justify this as bad code?

Are there any other concrete reasons why this code may be good or bad?


texts: Using polymorphic objects to represent parts of a deconstructed sentence

texts:
I am trying to make a chatbot using javascript by deconstructing a sentence into its intent by separating the Noun's Verb's, Adjectives, Durations's, Numbers etc... to construct a data query to try to answer the user's question.

I have built the parser and believe I have a good handle on that, but I would like to employ polymorphism in my callback function so I can use common patterns in the sentence structure to execute different functions.

I initially thought to use an object that had keys set by joining an array of the types names

{'TypeA,TypeB,TypeC': fn }

This would be the fastest to find the callback function, but then I cannot use inheritance to determine if the given argument is an instance or a descendent of the type in the function signature.

My Idea was to use the native Map object to store arrays that contain references to the constructors of the types I am expecting, then before executing the callback checking the given arguments types with the stored functions, using inheritance

// set a callback to be called if arguments are of TypeA and TypeB
polymorphic.set(
  [TypeA, TypeB],
  function first(arg1, arg2) {
    // do something
  }
)

// set a callback to be called if arguments are of TypeA and TypeC
polymorphic.set(
  [TypeA, TypeC],
  function second(arg1, arg2) {
    // do something
  }
)
// running this would call the second polymorphic function as the
// types match
parse(TypeA('string'), TypeC('string'))

This seems like it's going to introduce unwanted complexity, so I'm looking for a better way if anyone has any suggestions.

Here is a quick working prototype that shows the logic in determing the correct function signature based on the arguments provided to the parse function.

const data = {
  javascript: 10,
  php: 8,
  html: 6
}

function Intent() {}

function Noun(val) {
  if (this instanceof Noun === false)
    return new Noun(val)
  this.desc = val
  this.val = data[val]
}

Noun.prototype = new Intent

function Adjective(val) {
  if (this instanceof Adjective === false)
    return new Adjective(val)
  this.val = val
}

Adjective.prototype = new Intent

Adjective.prototype.exec = function(...args) {
  return this[this.val](...args)
}

Adjective.prototype.better = function(left, right) {
  this.opposite = 'worse'
  return left.val > right.val
}

const polymorphic = new Map

// add a new function definition
polymorphic.set(
  [Noun, Adjective, Noun],
  function compare(left, operator, right) {
    if (operator.exec(left, right)) {
      return `${left.desc} is ${operator.val} than ${right.desc}`
    }
    return `${left.desc} is ${operator.opposite} than ${right.desc}`
  }
)

// check if the left and right array of types are the same
function sameTypes(types, args) {
  if (types.length !== args.length) {
    return false
  }
  // iterate through the types and args to check that
  // they are related
  for (let ii = 0, ll = types.length; ii < ll; ii++) {
    if (args[ii] instanceof types[ii] === false) {
      return false
    }
  }
  return true
}

function parse(...instructions) {
  // iterate through all the polymorphic types
  for ([types, fn] of polymorphic) {
    // check if we have a match
    if (sameTypes(types, instructions)) {
      // run the callbackk function with the arguments
      console.log(fn(...instructions))
    }
  }
}

parse(Noun('javascript'), Adjective('better'), Noun('php'))
parse(Noun('html'), Adjective('better'), Noun('php'))


texts:
Is there any way I can make this function more inline?

def nDimensionalArray(n, s):
    x = 0
    for i in range(n):
        x = [x for j in range(s[i])]
    return x


texts:
I'm writing some table.tools to make table handling a little easier for me. But I'm a beginner with Lua, so you might help me a bit, to make the code better.

First of all I would like to get the best usability, but performance is a factor as well.

-- is compare equal to AT_LEASE one entry of list_to_search_in?
-- the idea was to make syntax like
--" if value == var1 or value == var2 or value == var(n) "
--- a little shorter

function table.contains(list_to_search_in, compare)

     for k,v in pairs(list_to_search_in) do
        if compare == v then
            return true
        end
      end

      return false
end

    -- is compare equal to EVERY entry of list_to_search_in ?

function table.equalsAll(list_to_search_in, compare)
    local counter = 0
    local truth_counter = 0

    for k,v in pairs(list_to_search_in) do
        if compare == v then
            truth_counter = truth_counter + 1
        end
        counter = counter + 1
    end

    return (truth_counter == counter)
end

    -- compare is equal to HOW_MANY entrys of list_to_search_in?
    -- returns how many entrys are the same

function table.count(list_to_search_in, compare)
    local counter = 0

    for k,v in pairs(list_to_search_in) do
        if compare == v then
            counter = counter + 1
        end
    end
    return counter
end

    -- compare is equal to WHICH entrys of list_to_search_in?
    -- returns a map of equality

function table.truthmap(list_to_search_in, compare)
    local map = { }

    for k,v in pairs(list_to_search_in) do
        table.insert(map, { k , compare == v})
    end
    return map
end

    -- deletes all entys in list, wich equals(or not[,invert]) to compare value
    -- returns a table with all entrys wich have not been equal

function table.removePerValue(list_to_search_in, compare, invert)
    local counter = 0
    local return_table = {}

    for k,v in pairs(list_to_search_in) do

        if invert and (v == compare) then
            table.insert(return_table, v)
        elseif not invert and (v ~= compare) then
            table.insert(return_table, v)
        end
    end

    return return_table
end

(Feel free to use, I'm happy if the code helps someone)


texts:
After much trial and error, I finally came up with this code to call on other classes to perform their function.  This code works and does what I want it to do, so I am looking for some comments on the code efficiency.

What I want to happen is have the user input which calculator they would like to use and have that calculator come up presenting its own variables and calculations.  The code for the calculators works just fine, so I don't need help with that.  Just the efficiency of my calling from other classes.

My first iteration of this was to have the other calculators inside methods within the class.  When I tried to call them up, it was nothing but problems, but this way seems to work. (I only mention this because my last question got knocked out because the code didn't work, so I found a way that worked, albeit not how I intended.)

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    System.out.println("Enter 1 for Quadratic Calculator");
    System.out.println("Enter 2 for Compound Interest Calculator");
    int ans = sc.nextInt();

    if (ans == 1) {
        Quadratic.CalcQuad();
    } else if (ans == 2){
        CompInt.CalcInt();
    } else {
        System.out.println("That was not an option.");
    }

    sc.close();
}


texts: Manage input values from file according to number of elements per line

texts:
I was given the a test file with the following kind of content, an arbitrary number of integer pairs divided by a newline and a final line with one integer:

1 2
3 4
5

I had to use the couples as values for two data members of a series of objects and I had to put the last integer in a separate variable.

I eventually wrote a working code, but the second inner while loop is very wasteful (it is the one loading the last value).

Also, I had to include <fstream>, <sstream> and <string> just to manage this input file.

What is a simpler and more elegant way to solve this problem?

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

class anObject
{
public:
    int one;
    int two;
};
int main()
{
    std::ifstream inFile;
    inFile.open("myFile.txt", std::ios::in);

    int myVar=0;
    std::string inLine;

    while (getline(inFile, inLine))
    {
        int inputA, inputB;
        std::stringstream inStream(inLine);
        std::stringstream inStreamAlt(inLine);

        while (inStream >> inputA >> inputB)
        {
            anObject inObj;
            inObj.one = inputA;
            inObj.two = inputB;
            objList.push_back(inObj);
        }

        while (inStreamAlt >> inputA)
        {
            myVar = inputA;
        }
    }
}


texts: Building a set of all subsets recursively in C++

texts:
Here is my recursive implementation of a power set function in C++.  One thing that concerns me is that I am iterating over the set of sets while modifying its size. The code nevertheless functions as desired. Any feedback would be highly appreciated.

#include <iostream>
#include <set>
#include <vector>

template <typename T>
void power_set(int i, const std::vector<T>& set, std::set<std::set<T>>& set_of_sets)
{
    if (i == set.size())
    {
        set_of_sets.emplace(std::set<T>());  // empty set
        return;
    }

    power_set(i + 1, set, set_of_sets);

    for (auto& subset : set_of_sets)
    {
        auto augmented_subset = subset;
        augmented_subset.insert(set[i]);
        set_of_sets.insert(augmented_subset);
    }

}

int main()
{
    std::vector<std::string> set = {"a", "b", "c"};
    std::set<std::set<std::string>> set_of_sets;
    power_set(0, set, set_of_sets);

    for (auto& subset : set_of_sets)
    {
        std::cout << "{";
        for (auto& i : subset) std::cout << i << ",";
        std::cout << "}\n";
    }
    std::cout << set_of_sets.size() << "\n";
}


texts:
I have just written my first git hook script.  It is very simple that simply finds any URLs in the commit message and uses the Google URL shortener to rewrite the URL nicely.

it is located here.

I feel it could be improved immensely (as it is my first) and would love to have your input.

#! /bin/bash
message=`cat $1`
shorten=`sed -ne 's/.*\(http[^"]*\).*/\1/p' $1`
echo "Shortening Url $shorten ...."
new_url=`curl -s https://www.googleapis.com/urlshortener/v1/url \-H 'Content-Type: application/json' \-d "{'longUrl': '$shorten'}"`
latest=`echo $new_url | python -c 'import json,sys;obj=json.load(sys.stdin);print obj["id"]';`
final=${message/$shorten/$latest}
echo $final > $1


texts:
Problem Statement

  You are given N sticks, where the length of each stick is a positive integer. A cut operation is performed on the sticks such that all of them are reduced by the length of the smallest stick.

  Suppose we have six sticks of the following lengths:

  \$5, 4, 4, 2, 2, 8\$

  Then, in one cut operation we make a cut of length 2 from each of the six sticks. For the next cut operation four sticks are left (of non-zero length), whose lengths are the following:

  \$3, 2, 2, 6\$

  The above step is repeated until no sticks are left.

  Given the length of N sticks, print the number of sticks that are left before each subsequent cut operations.

  Note: For each cut operation, you have to recalcuate the length of smallest sticks (excluding zero-length sticks).

  Input Format

  The first line contains a single integer N.
  The next line contains N integers: \$ a_0, a_1,...a_{N-1}\$ separated by space, where \$a_i\$ represents the length of \$i^\textrm{th}\$ stick.

  Output Format

  For each operation, print the number of sticks that are cut, on separate lines.

  Constraints

  $$\begin{align}
1&≤N ≤ 1000,\\
1&≤a_i ≤ 1000,\\
\end{align}$$

  Sample Input #00

6
5 4 4 2 2 8

  Sample Output #00

6
4
2
1

Solution

def cut_stick(stick, cut_size):
    return stick - cut_size if stick > 0 else stick

def read_ints():
    return map(int, raw_input().strip().split())

def read_int():
    return int(raw_input().strip())

def main(sticks):
    while not all(x == 0 for x in sticks):
        min_cut_size = min(i for i in sticks if i > 0)
        sticks_cut = len(filter(lambda x: x >= min_cut_size, sticks))
        sticks = map(lambda x: cut_stick(x, min_cut_size), sticks)
        print sticks_cut

if __name__ == '__main__':
    _ = read_int()
    k = read_ints()
    main(k)

The problem seems too simple I wanted to come up with the solution containing readable code yet efficient at the same time. I am really not satisfied with the given solution (current solution seems \$O(n^2)\$). My basic concern is how to proceed with the proper Data structure and again write some readable code with efficiency at the same time since problems like these appear in the coding competitions most.


texts: Parse File or String input in a uniform way: Is it possible with Generics?

texts:
I have a Parser class which creates a collection of String pairs, parsed in the format key=value.

public class Parser{
    private final HashMap<String, String> val;
    private final File source;

    public Parser(final File path){
        /*initialise stuff*/
        val=new HashMap<>();
        source=path; //throws exception if null but omitted for brevity
        /* and finally parse the file */
        parse();
    }

parse() reads source line-by-line using Scanner and populates the collection:

public void parse() {
    final Scanner sc=new Scanner(source);
    while(sc.hasNextLine()){
        //do stuff
    }
    sc.close();
}

The problem is, there are other parsers that utilise this class, and sometimes the parser needs to parse a String instead of a File. This leads to duplication of effort. Basically the code snippet above, with its signature changed to public void parse(final String raw). This led me to the following abomination:

private void parseDecision(final String possibleStr){
    final Scanner sc;

    if(possibleStr==null) //use File
        sc=new Scanner(source); //remember source is a field
    else
        sc=new Scanner(possibleStr);
    /*...*/
}

The abomination is being called from both parse (with argument null) and parse(String), and thus avoids code duplication. But when I look at it I can't help thinking there's a better way to do this.

I thought about using Generics. I've never written a Generic class before and I can't coerce Scanner into accepting T as either String or File, which would have been nice.

Which leads me to my question(s):

Is the use of parseDecision a code smell or am I seeing ghosts?
Can this be done in a better way?
If yes, can it be done with Generics?


texts:
I am trying to implement a function groupWeeks(dates) using reduce that allows me to group an array of objects { date: '2019-03-11', count: 8 } by weeks.

The following code works fine. Is there a way to refactor it? It seems to me that my solution is unnecessarily complex. Please ignore Date.prototype.getWeekNumber and getWeekStart(date).

const dates = [
  { date: '2019-02-24', count: 10 },
  { date: '2019-02-25', count: 11 },
  { date: '2019-02-26', count: 12 },
  { date: '2019-03-09', count: 8 },
  { date: '2019-03-10', count: 7 },
  { date: '2019-03-11', count: 6 },
  { date: '2019-04-14', count: 3 },
  { date: '2019-04-15', count: 2 },
  { date: '2019-04-16', count: 4 },
  { date: '2019-04-22', count: 5 }
];

/**
 * Returns the week number for this date.  dowOffset is the day of week the week
 * "starts" on for your locale - it can be from 0 to 6. If dowOffset is 1 (Monday),
 * the week returned is the ISO 8601 week number.
 * @param int dowOffset
 * @return int
 */
Date.prototype.getWeek = function(dowOffset) {
  /*getWeek() was developed by Nick Baicoianu at MeanFreePath: http://www.epoch-calendar.com */

  dowOffset = typeof dowOffset == 'int' ? dowOffset : 0; //default dowOffset to zero
  var newYear = new Date(this.getFullYear(), 0, 1);
  var day = newYear.getDay() - dowOffset; //the day of week the year begins on
  day = day >= 0 ? day : day + 7;
  var daynum =
    Math.floor(
      (this.getTime() -
        newYear.getTime() -
        (this.getTimezoneOffset() - newYear.getTimezoneOffset()) * 60000) /
        86400000
    ) + 1;
  var weeknum;
  //if the year starts before the middle of a week
  if (day < 4) {
    weeknum = Math.floor((daynum + day - 1) / 7) + 1;
    if (weeknum > 52) {
      nYear = new Date(this.getFullYear() + 1, 0, 1);
      nday = nYear.getDay() - dowOffset;
      nday = nday >= 0 ? nday : nday + 7;
      /*if the next year starts before the middle of
           the week, it is week #1 of that year*/
      weeknum = nday < 4 ? 1 : 53;
    }
  } else {
    weeknum = Math.floor((daynum + day - 1) / 7);
  }
  return weeknum;
};

function getWeekStart(date) {
  var offset = new Date(date).getDay();
  return new Date(new Date(date) - offset * 24 * 60 * 60 * 1000)
    .toISOString()
    .slice(0, 10);
}

function groupWeeks(dates) {
  const groupsByWeekNumber = dates.reduce(function(acc, item) {
    const today = new Date(item.date);
    const weekNumber = today.getWeek();

    // check if the week number exists
    if (typeof acc[weekNumber] === 'undefined') {
      acc[weekNumber] = [];
    }

    acc[weekNumber].push(item);

    return acc;
  }, []);

  return groupsByWeekNumber.map(function(group) {
    return {
      weekStart: getWeekStart(group[0].date),
      count: group.reduce(function(acc, item) {
        return acc + item.count;
      }, 0)
    };
  });
}

console.log(groupWeeks(dates));


texts: Knapsack algorithm in JavaScript - Integer weights and values

texts:
My version of Knapsack works only when the weights or values of items are whole numbers.

Restrictions

You are given an array of objects each of which contains a weight and value.
You are also given a bag which has a maximum capacity.
Both the values and weights for every item are integers. This example will not cover cases where the weights/values contain decimals
The maximum capacity will also be a whole number, again no decimals.

Here is my code with commentary

var result = document.getElementById("result");

function knapsack(items, capacity) {
    var totalWeight = 0;
    var totalValue = 0;

Here I initialized the total weight and value of our bag, which is empty at first, so both are zero.

    var sorted = items.sort(function(a,b) {
        return (b.value / b.weight) - (a.value / a.weight);
    });

To get the most bang for the buck, I'm taking a greedy algorithm and first choosing the item with the highest value to weight ratio. I have to sort the array based on the item's value per cost. I will then set the index to zero, to start at the best value.

    var index = 0;
    while (totalWeight < capacity) {
        var ratio = sorted[index].value / sorted[index].weight;
        totalValue += ratio;
        totalWeight++;
        if (totalWeight === sorted[index].weight) {
            index++;
        }
    }

The loop is run until the weight is equal to the capacity. For every item, I will get the value per 1 unit of weight. This will be added to the value of the bag, whereas the weight of the bag will increase by one unit.

If the weight of the bag equals the weight of the item, I will move on to the next item and continue the while loop.

    return totalValue.toFixed(2);
}

var array = [
                {"value": 15, "weight": 10},
                {"value": 24, "weight": 15},
                {"value": 25, "weight": 18}
            ];

result.innerHTML = knapsack(array, 20);

This will not work if the item weights or values have decimals, but that's beyond the scope of this problem. This problem assumes that all are whole numbers.

What would the complexity be of this algorithm? Also, which type of knapsack does my algorithm solve?


texts:
Following my previous unbounded prime generator and a followup by Martin R, I've tested the waters in Kotlin by making an unbounded sieve.

To quote Martin R's wonderful explanation of the base algorithm,

  The interesting thing about that algorithm is that the prime generator needs a list of "base primes" which are created using another instance of itself. This works because

  the base prime generator is created "delayed", after producing some fixed primes, and
  in order to generate primes up to \$ N \$, base primes are needed only up to \$ \sqrt N \$

  so that the creation of nested prime generators terminates eventually.

  The sieving is done using a dictionary which holds the "next composite numbers" which are divisible by any prime less than the current base prime. As explained [on SO], the required memory to produce \$ n \$ primes is \$ O(\sqrt n). \$

class PostponedPrimeSequence() : AbstractIterator<Int>(), Sequence<Int> {
    override fun iterator() = this

    private var basePrimes: PostponedPrimeSequence? = null
    private var basePrime = 0

    private var sieve = mutableMapOf<Int, Int>()
    private var initialPrimes = mutableListOf(2, 3, 5, 7)
    private var candidate = 9

    override fun computeNext() {
        if (!initialPrimes.isEmpty()) {
            setNext(initialPrimes.removeAt(0))
        } else {
            if (candidate == 9) {
                basePrimes = PostponedPrimeSequence()
                basePrimes!!.next()
                basePrime = basePrimes!!.next()
                assert(candidate == basePrime * basePrime)
            }

            while (candidate > 0) {
                val factor = sieve.remove(candidate) ?:
                        if (candidate == basePrime * basePrime) {
                            val temp = basePrime
                            basePrime = basePrimes!!.next()
                            temp
                        } else {
                            assert(candidate < basePrime * basePrime)
                            setNext(candidate)
                            break
                        }
                var j = candidate + 2 * factor
                while (sieve.containsKey(j)) {
                    j += 2 * factor
                }
                sieve[j] = factor
                candidate += 2
            }
            candidate += 2
        }
    }
}

Usage:

PostponedPrimeSequence().take(20).forEach(::println)

All feedback welcome, though reviews are encouraged to look at:

Naming: As I'm new to Kotlin, I don't know the naming conventions yet
Performance: If there are simple, provable improvements without drastically changing the algorithm (such as adding a large wheel)
Iteration organization: As Kotlin lacks a true yielding generator and I wanted a true Iterator/Sequence, rather than a callback based "poor man's yield", the iteration isn't exactly the prettiest matter. The candidate += 2 } candidate += 2 bit especially feels like there should be a better way to do this, and the break (which is related) breaks ha simple control flow, which is not ideal.
!!: Even on the line immediately following assignment to basePrimes, I have to use !! to potentially fail on accessing the next method (Smart cast to 'PostponedPrimeSequence' is impossible, because 'basePrimes' is a mutable property that could have been changed by this time). I know that, due to reflection, any variable on the JVM could change at any time, but this seems like a smelly smell that smells smelly. basePrimes has to be mutable and start out null, though, because otherwise the class would recursively take infinite space. In this case, though, I want to initialize it once, late, and from then on it should act as an immutable (non-nullable) val reference. If this is possible in Kotlin, I don't know how to do so yet.


texts:
I have a float in the String strFloat.  I wanted to convert it to a rounded integer also stored in a String.  This looks awful to me, so please offer some suggestions for improvement.

String strInteger = new Integer(Float.valueOf(strFloat).intValue()).toString()


texts:
I'm relatively new to programming and I was trying to work a project.
I would like recommendations of how to annotate or comment my project and any improvement I could make to it, any suggestion is welcome,
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;

public class Util {

    /*/
    DOC Generation -> XML with ArrayList String elements
     */
    public Document docBuilder(ArrayList<String[]> elements) throws ParserConfigurationException {
        DocumentBuilderFactory xmlFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder xmlBuilder = xmlFactory.newDocumentBuilder();
        Document xmlDoc = xmlBuilder.newDocument();

        Element rootElement = xmlDoc.createElement("root");
        xmlDoc.appendChild(rootElement);

        Element mainElement = xmlDoc.createElement("elements");
        rootElement.appendChild(mainElement);

        boolean headerDefined = false; //First while will be to define header
        String[] header = new String[elements.size()]; //Header initialization

        /*/
        DOC Generation -> XML Generation of every ELEMENT
        */
        for (String[] node : elements) { //FOR every ArrayString
            if (headerDefined) {
                Element nodesElements = xmlDoc.createElement("element");
                mainElement.appendChild(nodesElements);

                for (int j = 0; j < node.length; j++) {
                    node[j] = node[j].replaceAll("\"", "").trim();
                    Element nodesValues = xmlDoc.createElement(header[j]);
                    nodesElements.appendChild(nodesValues);
                    Text nodeTxt = xmlDoc.createTextNode(node[j]);
                    nodesValues.appendChild(nodeTxt);
                }
            }
            /*/
            DOC Generation -> Array Generation of every COL Name for NODES
            */
            else {
                header = node;
                for (int k = 0; k < node.length; k++) {
                    header[k] = header[k].replaceAll("[^a-zA-Z0-9]", "");
                    //We want to make sure NODE isn't NUMERIC. If it is, we make a patch
                    try {
                        Integer.parseInt(header[k]);
                        header[k] = "node" + header[k];
                    } catch (NumberFormatException e) {
                    }
                }
                headerDefined = true;
            }
        }
        return (xmlDoc);
    }

    /*/
    XML Generation -> Transform DOC Data to XML Format
     */
    public static void transformDocToFile(Document xmlDoc, String xmlFile) throws TransformerException {
        TransformerFactory xmlTransformerFactory = TransformerFactory.newInstance();
        Transformer xmlTransformer = xmlTransformerFactory.newTransformer();
        xmlTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
        xmlTransformer.setOutputProperty(OutputKeys.METHOD, "xml");
        xmlTransformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        xmlTransformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        FileOutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream((new File(xmlFile)));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        xmlTransformer.transform(new DOMSource(xmlDoc), new StreamResult(outputStream));
    }

}

https://github.com/codepressed/JAVACSVtoXMLConverter


texts:
I have created an Insertion Sort code that sorts numbers (obviously).

#include <iostream>
#include <cstdlib>

void insertion_sort(int arr[], int length);
void print_array(int array[],int size);

int main()
{
    int array[] = {4,6,3,7,5,9,2,8,1,10};
    insertion_sort(array,10);
    print_array(array,10);
    return 0;
}

void insertion_sort(int arr[], int length)
{
    int i,j,tmp;
    for (i = 1; i < length; i++) {
        j = i;
        while (j > 0 && arr[j - 1] > arr[j]) {
            tmp = arr[j];
            arr[j] = arr[j - 1];
            arr[j - 1] = tmp;
            j--;
        }
    }
}

void print_array(int array[], int size)
{
    int j;
    for (j = 0; j < size; j++)
    {
        std::cout << array[j] << std::endl;
    }
}

Is there a way to make it shorter or better?


texts:
I'm writing three functions which iterate over lists, I want do this recursively, but I think this code is not as efficient as it could be.

def flatten(lst):

    if type(lst)==int:
        return [lst]
    elif lst==[]:
        return lst
    else:
        return sum([flatten(sub) for sub in lst], [])

def size(lst): #counts how many numbers and pairs of parentheses in the list
    global cnt
    cnt=0
    if type(lst)==int:
        cnt+=1
        return 1

    if lst==[]:
        cnt+=1
        return 1
    else:
        return (sum([size(sub) for sub in lst])+cnt)

def transform(f, lst):
    if lst==[]:
        return []
    if isinstance(lst,(int,float)):
        return f(lst)
    else:
        return [transform(f,sub) for sub in lst]


texts:
I know there are probably thousands of INI parser implementations in C.

Nevertheless I want to implement one to learn the art of parsing grammar.

I just wrote a small piece of the INI parser and wanted to ask if I am on the right track:

void parse_line(const char *str, char **name) {
    size_t length = strlen(str);
    bool found_section = false;

    for (size_t pos = 0; pos < length; ++pos) {
        char current = str[pos];
        bool is_last_ch = (pos + 1) >= length;

        //dbg("Processing %c", current);

        if (current == '[') {
            size_t updated_pos = pos + 1;
            ssize_t match_pos = -1;

            if (is_last_ch) {
                dbg("Reached end of line without closing ] (1)!");

                return;
            }

            if (found_section) {
                dbg("Already found a section!");

                return;
            }

            //dbg("Found a [ at position %zu, looking for ] now", pos);

            for (size_t x = updated_pos; x < length; ++x) {
                if (str[x] == ';') {
                    break;
                } else if (str[x] == ']') {
                    match_pos = x;

                    break;
                }
            }

            if (match_pos == -1) {
                dbg("Reached end of line without closing ] (2)!");

                return;
            }

            //dbg("Found matching ] at position %zd", match_pos);

            assert(match_pos >= updated_pos);

            size_t length_of_section = match_pos - updated_pos;

            //dbg("Length of name is %zu", length_of_section);

            char *section_name = malloc(length_of_section + 1);
            assert(section_name);

            for (size_t x = 0; x < length_of_section; ++x) {
                size_t i = x + updated_pos;

                section_name[x] = str[i];
            }

            section_name[length_of_section] = 0;

            // utilize `section_name` in some way...
            //dbg("Section name is: %s", section_name);
            *name = section_name;
            // and then free() it somewhere

            pos += length_of_section + 1;

            assert(pos < length);

            found_section = true;
        } else if (current == ']') {
            dbg("Found unmatched ] at position %zu", pos);

            return;
        } else if (current == ';') {
            //dbg("End of line, bye!");

            return;
        } else {
            dbg("Unexpected character %c", current);

            return;
        }
    }
}

At the moment it only parses name of sections (like [name]).

I want to focus on detecting malformed grammar:

[section] comment -> invalid
comment [section] -> invalid

etc.

Example:

parse_line("[name]", ...); // gives "name"
parse_line("[name];Comment", ...); // gives "name"
parse_line(";[name];Comment", ...); // gives (null)
parse_line("[name[]", ...); // works... but should not (i already have a fix for this in mind -> check for "[" in section name fetching ; but is this good?)

Is the approach to ''wait'' for a character and then process from there on a robust way to parse things like INI files?


texts: Add headers to colums and rows in Python - 2D array (list of lists)

texts:
I have a 2D Python array (list of lists). I treat this as a 'table'. Now I want to replace the first row and the top row with a header row and column. The row and the header are exactly the same.
I try this using list comprehension. It works out for the 'row' part, but the column part is not very Pythonic yet.
# The header that i want to add
headers = ['foo', 'bar', 'baz', 'other']
l = len(headers) + 1  # The final matrix is one element bigger

# square matrix of random size, filled with data
array = [['xxx' for i in range(l)] for j in range(l)]

# The concise one - add headers to top row
array[0] = ['Title'] + [category for category in headers]

# The ugly one - add headers for the rows
for i in range(l):
    array[i][0] = array[0][i]

The final output should look like this (which it does):
[['Title', 'foo', 'bar', 'baz', 'other'],
 ['foo', 'xxx', 'xxx', 'xxx', 'xxx'],
 ['bar', 'xxx', 'xxx', 'xxx', 'xxx'],
 ['baz', 'xxx', 'xxx', 'xxx', 'xxx'],
 ['other', 'xxx', 'xxx', 'xxx', 'xxx']]

I'm just not so happy with the 'for' loop. How can this be done more Pythonic?


texts:
I am creating a connect 4 game in python and I have managed to write the code so that it runs. However I have a lot of duplicated data in it and was just wondering if anyone could help me to refine it to minimise this?

Here is my code so far:

def CreateBoard(r, c, b, n):

  for i in range(1,(r+1)):
    n.append(str(i))
  b.append(n)

  for i in range(c):
    b.append(['*']*(r))
  return(b)

"""The Following PrintBoard function takes the parameter board(b), prints
the board and then returns the board."""

def printBoard(b):
  for lst in b:
    print(" ".join(lst))
  return b

"""The following Check function takes the parameter board. Within this  """
def check(board, n):
  n = []
  for i in range(1,len(board[1])+1):
    if board[1][i-1] == '*':
      n.append(i)
  print(n)

  user = (input('Enter column: '))

  if(user.isdigit() == True):
    user = int(user)
    if (user in n):
      return(user)
  print('Invalid input')
  return check(board, n)

def WinningCon(b, r, u, c):
  loop1 = True
  rowCon = ""
  colCon = ""
  for i in range(0,len(b[1])):
    rowCon += b[r][i]
    if('X'*4 in rowCon) or('O'*4 in rowCon):
      return(True)
  for i in range(1,c+1):
    colCon += b[i][u-1]
    if('X'*4 in colCon) or('O'*4 in colCon):
      return(True)

def Diag2(u, r, b, column, row):
  utemp1 = u-1
  utemp2 = u-1
  rtemp1 = r
  rtemp2 = r
  end = ""
  beg = ""
  while(True):

    beg += b[rtemp1][utemp1]
    rtemp1 -= 1
    utemp1 += 1
    if(rtemp1 == 1):
      break
    elif(utemp1 >= column - 1):
      break
  while(True):
    end += b[rtemp2][utemp2]
    rtemp2 +=1
    utemp2 -=1
    if(rtemp2 >= row):
      break
    elif(utemp2 == 0):
      break
  beg = beg[::-1]
  fullstring = beg+end
  if('X'*4 in fullstring) or('O'*4 in fullstring):
    return(True)

def Diag1(u, r, b, column, row):
  utemp1 = u-1
  utemp2 = u-1
  rtemp1 = r
  rtemp2 = r
  end = ""
  beg = ""
  while(True):
    beg += b[rtemp1][utemp1]
    rtemp1 -= 1
    utemp1 -= 1
    if(rtemp1 == 1):
      break
    elif(utemp1 == 0):
      break
  while(True):
    end += b[rtemp2][utemp2]
    rtemp2 +=1
    utemp2 +=1
    if(rtemp2 >= row):
      break
    elif(utemp2 >= column-1):
      break
  beg = beg[::-1]
  fullstring = beg+end
  if('X'*4 in fullstring) or('O'*4 in fullstring):
    return(True)

def ProcessInput(u, s, b, r):
  rowNum = r
  u = u-1
  while(not b[rowNum][u] == '*'):
    rowNum -= 1
  b[rowNum][u] = s
  return(rowNum)

def EndGame(g, b, p):
  printBoard(b)
  print("Congrats %s, you've won!" %p)
  replayGame = input('Would you like to play again? Yes or No?\n').lower()
  if replayGame == 'yes':
    MainGame()
  else:
    g = False
    return(g)

def MainGame():
  column = int(input('Enter number of columns'))
  row = int(input('Enter number of rows'))
  board = []
  nums = []
  board = CreateBoard(column, row, board, nums)
  player1 = 'K'#input('Enter name: ')
  player2 = 'A'#input('Enter name: ')
  turn = 1
  GameOn = True
  while(GameOn):
    board = printBoard(board)
    user = check(board, nums)
    if(turn%2 != 0):
      print("It's %s's turn" %player1)
      rc = ProcessInput(user, "X", board, row)
    else:
      print("It's %s's turn" %player2)
      rc = ProcessInput(user, "O", board, row)

    if(WinningCon(board, rc , user, row) == True):
      GameOn = EndGame(GameOn, board, player1)
    elif(Diag1(user, rc, board, column, row) == True):
      GameOn = EndGame(GameOn, board, player1)
    elif(Diag2(user, rc, board, column, row) == True):
      GameOn = EndGame(GameOn, board, player1)

    turn +=1

MainGame()


texts: Iterating through every permutation of every subset

texts:
I have this code which I use to iterate through every permutation of every subset in an array witch holds integers.

One big problem is the efficiency of course, another problem is the fact that if I have some similar values it holds only one of them (Ex. [100,5,3,5] is held as [100,5,3]).

Any help in improving this is appreciated :D

public int findSolution(){

    for(int i = 1; i <= values.length; i++){
        orders.add(values[i-1]);
    }
    for(int i = 1; i <= values.length; i++){
        List<Set<Integer>> listSet = getSubsets(orders, i);
        for(Set<Integer> set : listSet){
            int[] currSetAsArray = new int[i];
            int index = 0;
            for(Integer x : set){
                currSetAsArray[index++] = x;
            }
            System.out.println("Current Set: ");
            System.out.println(set);
            System.out.println("All Permutations: ");
            permute(currSetAsArray, 0);
        }
        System.out.println(i);
        //System.out.println(listSet.get(0));
    }

    System.out.println("Total permutations: " + permutations);
    return 0;
}

//Function that finds every subset
private static void getSubsets(List<Integer> superSet, int k, int idx, Set<Integer> current,List<Set<Integer>> solution) {
    //successful stop clause
    if (current.size() == k) {
        solution.add(new HashSet<>(current));
        return;
    }
    //unseccessful stop clause
    if (idx == superSet.size()) return;
    Integer x = superSet.get(idx);
    current.add(x);
    //"guess" x is in the subset
    getSubsets(superSet, k, idx+1, current, solution);
    current.remove(x);
    //"guess" x is not in the subset
    getSubsets(superSet, k, idx+1, current, solution);
}

public static List<Set<Integer>> getSubsets(List<Integer> superSet, int k) {
    List<Set<Integer>> res = new ArrayList<>();
    getSubsets(superSet, k, 0, new HashSet<Integer>(), res);
    return res;
}

//Function that finds every permutation
private void permute(int[] a, int k)
{
    if (k == a.length)
    {
        for (int i = 0; i < a.length; i++)
        {
            System.out.print(" [" + a[i] + "] ");
        }
        System.out.println();
        permutations++;
    }
    else
    {
        for (int i = k; i < a.length; i++)
        {
            int temp = a[k];
            a[k] = a[i];
            a[i] = temp;

            permute(a, k + 1);

            temp = a[k];
            a[k] = a[i];
            a[i] = temp;
        }
    }
}


texts:
I want to filter directories and files by what they start with.

var result =  DirectoryList(arguments.path, false, "query",
   arguments.filter & "*|" & arguments.filter & "*.*");

I am thinking this covers all scenarios because file sometimes don't have extensions and directories sometimes do. I don't think it can be simplier


texts:
Suppose we have the following program:

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

int main()
{
        char *user = getenv("USER");
        char buffer[4096];

        if (user) {
                snprintf(buffer, sizeof buffer, "/bin/echo %s", user);
                system(buffer);
        }

        return 0;
}

Is it possible for a user to cause this program to execute arbitrary commands?


texts:
I'm a beginner coder, doing it solely for fun, having started coding about two months ago with Python. I have a working piece of code for calculating area and volume of different geometric shapes, using user input of "radius".

As I have said, the code works but I would like to know how I can improve it to be shorter, faster and more efficient. Essentially, I think it would be instructive to compare my rank amateur code to the code that an experienced software developer would produce to accomplish the same result.

from tkinter import *
from tkinter import ttk
import sys

root = Tk()

pi = 3.141

# Option Box

var = StringVar(root)
var.set("Functions")

lbl_title = Label(root, text = "GEOMETRIC SHAPES AND VOLUMES")
lbl_title.grid(row = 0, column = 0, columnspan = 2, padx =5, pady = 10)

lbl_choose = Label(root, text = "Choose a function and hit OK:")
lbl_choose.grid(row = 1, column = 0, padx = 5, pady = 0, sticky = W)

box = ttk.OptionMenu(root, var, "Circle Circumference", "Circle Area", "Sphere Volume",
               "Rectangle Area", "Rectangle Prism Volume", "Cone Volume")
box.grid(row = 2, column = 0, padx=5, pady=5, sticky= W)

# Separator

line1 = ttk.Separator(root, orient = HORIZONTAL)
line1.grid(row = 4, column = 0, columnspan = 3, sticky = EW) # Note separator sticky EW!

#txt_data_in = Text(root, height = 1, width = 30, bg = "Light Grey")
#txt_data_in.grid(row = 5, column = 0, padx = 5, sticky = W)

# Functions

def circ_circumf(r):
    print("\nThe circumference of the circle is: " + str(2*pi*r) + " units.")

def circ_area(r):
    print("\nThe area of the circle is: " + str(pi*r**2) + " units.")

def sphere_vol(r):
    print("\nThe volume of the sphere is: " +str(4/3 * pi * r**3) + " units.")

def rect_area(l,w):
    pass

def rect_prism_vol(l, w, h):
    pass

def cone_vol(r, h):
    pass

def exit():
    sys.exit()

# Main Function

def main():
    if var.get() == "Circle Circumference":
        r = int(input("Enter the radius of the circle in the units of your choice: "))
        circ_circumf(r)

    elif var.get() == "Circle Area":
        r = int(input("Enter the radius of the circle in the units of your choice: "))
        circ_area(r)

    elif var.get() == "Sphere Volume":
        r = int(input("Enter the radius of the sphere in the units of your choice: "))
        sphere_vol(r)

# Function Button

butt1 = ttk.Button(root, text = "OK", command = main)
butt1.grid(row = 2, column = 1, padx = 5, sticky = W)

# Exit Button

butt2 = ttk.Button(root, text = "Exit", command = exit)
butt2.grid(row = 6, column = 0, padx = 5, pady = 5,  sticky = W)

root.mainloop()


texts:
What can make this code better?
And how could I improve this code?
Oh and what I would love is if someone has a project that is not that
challenging but I could learn a lot from it :)

import java.util.Scanner;

public class RockPaperScissors {
    final static int ROCK = 1;
    final static int PAPER = 2;
    final static int SCISSORS = 3;

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Start By Entering A number");
        int human = input.nextInt();
        System.out.println("ROCK IS 1 :: PAPER IS 2 :: SCISSORS 3");
        int computerScore = 0, humanScore = 0, computer;
        while (human != -1) {
            human = input.nextInt();
            computer = (int) (Math.random() * 3 + 1);
            String h = human == 1 ? "ROCK" : human == 2 ? "PAPER" : "SCISSORS";
            String c = computer == 1 ? "ROCK" : computer == 2 ? "PAPER" : "SCISSORS";
            if ((human == ROCK && computer == SCISSORS) || (human == PAPER && computer == ROCK) || (human == SCISSORS && computer == PAPER)) {
                humanScore++;
                System.out.println("Human Won : " + humanScore);
                System.out.println("Human Chose " + h + " and Computer Chose " + c);
            } else if ((computer == ROCK && human == SCISSORS) || (computer == PAPER && human == ROCK) || (computer == SCISSORS && human == PAPER)) {
                computerScore++;
                System.out.println("Computer Won : " + computerScore);
                System.out.println("Human Chose " + h + " and Computer Chose " + c);
            } else if (human == computer) {
                System.out.println("HAH YOU BOTH THINK THE SAME! ");
                System.out.println("DRAW!");
            } else {
                System.out.println("Something Went Wrong Try Again:( ");
            }
        }
        System.out.println("\n\nThe Scores Are *DRUM NOISES* ");
        for (int i = 0; i < 4; i++) {
            System.out.println("------------------------------");
        }
        System.out.println("Human score : " + humanScore);
        System.out.println("Computer score : " + computerScore);
        if (humanScore > computerScore) {
            System.out.println("Human Race Is saved! We Won!");
        } else if (computerScore > humanScore) {
            System.out.println("Sadly We Lost. Better Luck Next Time:)");
        } else {
            System.out.println("Scores are Tied");
        }
    }
}


texts: How can I make placing JButtons from an array more elegant?

texts:
I am trying to place JButtons from an array onto a JFrame. The way I'm doing it is having it test how many more buttons are left, and if buttons have been placed at the edge of the frame. The end result is an ugly piece of code.

JButton[] grid = new JButton[2501];

JFrame MapFrame = new JFrame();

public void makeMap() {

    MapFrame.setBounds(40, 0, 750, 773);

    int x = 0;
    int y = 0;
    for (int i = 0; i < grid.length; i++) {
   // grid is the JButton Array

        if (x > 749) {
            x = 0;
            y = y + 15;
        }
        grid[i] = new JButton();
        grid[i].setBounds(x, y, 15, 15);
        MapFrame.add(grid[i]);

        x = x + 15;
    }
    MapFrame.setVisible(true);
    MapFrame.repaint();
}

The code just looks so bulky with variables being changed in different braces, and with so many braces. How could I make this more elegant? (Please don't recommend layouts, as, none of them fit my requirements.)


texts:
I just heard of prepared statement in PHP and decided to prevent SQL injection with it and wrote a script testing it.

I would like to know what security threats this script can prevent, what security threats this script is vulnerable to, and how these threats are blocked.

<?php
require_once ("db.php");
$db = new MyDB();
session_start();

if (isset($_POST['userMsgField']) && !empty($_POST['userMsgField']) || isset($_POST['hash']) && !empty($_POST['hash']))
{
$my_id = $_SESSION['log_id'];
$rep_msg = $_POST['userMsgField'];
$hash = $_SESSION['hash'];
$flag = 0;

$sql =<<<EOF
SELECT * FROM connect WHERE (user_one = '$my_id' AND hash = '$hash') OR (user_two = '$my_id' AND hash = '$hash');
EOF;

$ret = $db->query($sql);

while ($row = $ret->fetchArray(SQLITE3_ASSOC))
{
    $user_one = $row['user_one'];
    $user_two = $row['user_two'];

    if ($user_one == $my_id)
    {
        $to_id = $user_two;
    }
    else
    {
        $to_id = $user_one;
    }

    $isql =<<<EOF
    INSERT INTO messager (message, group_hash, from_id, flag, to_id) VALUES (:message, :group_hash, :from_id, :flag, :to_id);
EOF;
    $bsql =<<<EOF
    INSERT INTO chatportal (message, group_hash, from_id, flag, to_id)
VALUES (:message, :group_hash, :from_id, :flag, :to_id);
EOF;

    $stmt = $db->prepare($isql);
    $bstmt = $db->prepare($bsql);

    $stmt->bindValue(':message', $rep_msg, SQLITE3_TEXT);
    $stmt->bindValue(':group_hash', $hash, SQLITE3_INTEGER);
    $stmt->bindValue(':from_id', $my_id, SQLITE3_INTEGER);
    $stmt->bindValue(':flag', $flag, SQLITE3_INTEGER);
    $stmt->bindValue(':to_id', $to_id, SQLITE3_TEXT);

    $bstmt->bindValue(':message', $rep_msg, SQLITE3_TEXT);
    $bstmt->bindValue(':group_hash', $hash, SQLITE3_INTEGER);
    $bstmt->bindValue(':from_id', $my_id, SQLITE3_INTEGER);
    $bstmt->bindValue(':flag', $flag, SQLITE3_INTEGER);
    $bstmt->bindValue(':to_id', $to_id, SQLITE3_TEXT);

    $result = $stmt->execute();
    $bresult = $bstmt->execute();

    if ($reuslt && $bresult)
    {

    }
}
}


texts:
I've been reading Bjarne's Principles in Programming and was given some code to demonstrate the usage of vectors and how we can return specific values for certain functionality such as mean and median. However, in the chapter I noticed that the code he provided was purposely made so that it doesn't always calculate the median correctly which was correct, he had purposely made it so we had to go back and alter the code as follows:

#include "../../std_lib_facilities.h"

int main()
{
  vector<double> temps;
  for (double temp; cin >> temp;)
      temps.push_back(temp);

  sort(temps);
  cout << "Median temperature: " << temps[temps.size() / 2] << '\n';
}

However, when asked in a question format it states:

  If we define the median of a sequence as “a number so that exactly as many elements come before it in the sequence as come after it,” fix the program in 4.6.3 so that it always prints out a median. Hint: A median need not be an element of a sequence.

I assumed he meant that we want equal values on both sides of our median as the previous algorithm only divides the vector size by 2 and returns, if odd the middle index + 1, therefore I'm assuming that he wanted the exact median value of the range rather than a specific element within the array? Regardless, the code I had created follows:

//Program to compute the median of a temperature vector
#include "../../std_lib_facilities.h"

int main()
{
    //Define variables and Read in values
    double median_value;
    vector<double> temps;
    for (double temp; cin >> temp;)
        temps.push_back(temp);

    //Compute Median Temperatures
    sort(temps);

    if (temps.size() % 2 == 0)
        median_value = (temps[temps.size() / 2] + temps[temps.size() / 2 - 1]) / 2;
    else
        median_value = temps[temps.size() / 2];

    cout << "Median Temperature of input values: " << median_value << '\n';
    for (int i = 0; i < temps.size(); ++i) cout << temps[i] << ", ";
}

I'm assuming this is what he meant by “a number so that exactly as many elements come before it in the sequence as come after it". I've probably missed the point of this exercise hence the post for some verification that I completed the exercise correctly.


texts: Reservoir Sampling of an enumerable collection of unknown size

texts:
I have an enumerable source for which I do not know how big it is. I want to select a random element from it, without having to hold the whole collection in memory and with uniform distribution. I read about the reservoir sampling algorithm, and created a simple implementation for the very basic case where the reservoir size is 1, which is what I want.
Basically the idea is that if an item appears in position n starting by 1, if a random roll returns less than 1/n I pick that value as the current selected value.
static T Random<T>(IEnumerable<T> source, Random random)
{
    using var e = source.GetEnumerator();
    if(!e.MoveNext())
        return default;
    var result = e.Current;
    var count = 1;
    while(e.MoveNext())
    {
        if(random.NextDouble() < 1.0 / ++count)
            result = e.Current;
    }

    return result;
}

I created a demo project and the results seems to add up.
https://dotnetfiddle.net/0iXEck
public static void Main()
{
    var size = 1000;
    var tries = size * 100;
    var random = new Random();
    var array = Enumerable.Range(0, size).ToArray();
    var histogram = array.ToDictionary(k => k, v => 0);
    for(var i=0; i<tries; i++)
        histogram[Random(array, random)]++;
    foreach(var kv in histogram.OrderBy(kv => kv.Key))
        Console.WriteLine($"{kv.Key,5}: {kv.Value}");
}

I wonder if am I missing anything because probability knowledge is not my strongest point. Is this still "reservoir sampling algorithm" or does it have another name?


texts: PHP Class code that allow developers to register taxonomies in a CMS

texts:
Building complex applications can sometimes be a pain when extending or editing later on; I read online about the S.O.L.I.D principles of OOD, I want to understand if I am following a good approach that I can follow when developing the rest of the app.

I need answers to the following questions

Is the code well-documented?
The use of namespaces, Was it necessary ?
Does the class violates any of the SOLID principles ?
$ic = new static; Is it wrong to use this approach for inline usage?
Using static methods for easy access in a single line of code to creating and getting taxonomies, Are there better ideas ?
App\Taxonomy::register("categories")->isHierarchical()->produce() The usage, Is it developer friendly to you ? Or are there other approaches developers would rather ?

Some of the ideas I had in mind when writing down the Class:

I used namespaces because the project will have many classes and sub packages that would need categorizing for better usage by developers when they develop mini apps (plugins).
I used static methods for single line usage to make it easier for developers to register new taxonomies and set options into one line of code.

Here is the class

namespace App;

/**
 * Class Taxonomy
 *
 * @package App
 */

class Taxonomy {

    /**
     * Store all the taxonomies
     *
     * @since 0.5
     *
     * @var array
     */
    protected static $taxonomies = array();

    /**
     * Default settings for creating taxonomies
     *
     * @since 0.5
     *
     * @var array
     */
    protected static $tax_defaults = array(
        'key' => null,
        'hierarchical' => false
    );

    /**
     * A Temporary variable that holds the taxonomy
     * settings until the taxonomy is being produced
     * then the temporary variable is being reset
     * to an empty array
     *
     * @since 0.5
     *
     * @var array
     */
    protected static $tax = array();

    /**
     * Temporarily holds an error because
     * in some cases errors occurs when for example
     * using a duplicate taxonomy key
     *
     * @since 0.5
     *
     * @var bool
     */
    protected static $error = false;

    /**
     * Register a new taxonomy to be later on
     * added to a data set
     *
     * @since 0.5
     *
     * @param $taxonomy_key String Unique key used for the taxonomy as an identifier
     * @return static
     */
    public static function register( $taxonomy_key ){
        $ic = new static;
        self::reset();

        if( isset( self::$taxonomies[ $taxonomy_key ] ) )
            self::$error = "taxonomy-already-registered";

        self::$tax = self::$tax_defaults;
        self::$tax['key'] = $taxonomy_key;

        return $ic;
    }

    /**
     * Set the taxonomy to hierarchical
     *
     * @since 0.5
     *
     * @return static
     */
    static function isHierarchical(){
        $ic = new static;
        self::$tax['hierarchical'] = true;
        return $ic;
    }

    /**
     * Final step, This method is used to store
     * the taxonomy to App global taxonomies variable
     *
     * @since 0.5
     *
     * @return bool
     */
    static function produce(){
        if( self::$error !== false )
            return self::$error;

        $key = self::$tax['key'];
        self::$taxonomies[$key] = self::$tax;
        self::reset();
    }

    /**
     * Return the object of the Taxonomy
     *
     * @since 0.5
     *
     * @param $taxonomy_key
     * @return bool
     */
    static function get( $taxonomy_key ){
        return isset( self::$taxonomies[$taxonomy_key] ) ? self::$taxonomies[$taxonomy_key] : false;
    }

    /**
     * Reset temporary variables
     *
     * @since 0.5
     */
    protected static function reset(){
        self::$tax = array();
    }
}

Usage example

// Register Taxonomies
App\Taxonomy::register("categories")->isHierarchical()->produce();
App\Taxonomy::register("tags")->produce();

// Get Taxonomies
App\Taxonomy::get("tags"); // Will return an array of the information registered


texts: Changing the view based on these if/else statements

texts:
If the user has not responded = edit mode.
If there are responses present but the overall status is 'Completed' = lock everything into display mode.
If the stage is less than or equal to 'editable in stage', it is considered editable and if also the response given has a code of 0 or 2 (standardized responses via "coding" them).
Otherwise set it to display.

This code works as desired but it's hard to read/maintain.

    if (typeof response !== 'string') {
        mode = edit;
    } else {
        if (status.indexOf('Completed') !== -1) {
            mode = display;
        } else {
            if ((stage <= isEditable) && (code == 0 || code == 2)) {
                mode = edit;
            } else {
                mode = display;
            }
        }
    }


texts: Recursively searching the Windows Registry

texts:
This function is part of a the Registry class that can be found on Google Drive. The class was originally written by Steve McMahon for VB6, but I ported it to VBA and added the function below.

I would like to know if I have made any mistakes in my logic and (if possible) how I could change this to keep searching after it has found the first instance.

Public Function findSectionKey(sectToFind As String, Optional sectToLookIn As String = vbNullString) As String
'*****************************************************************************
' Christopher J. McClellan 4-16-14
'
' Returns:
'   Full section key as string
'       ex: "software\wow6432Node\ODBC\ODBCINST.INI\Oracle in OraClient11g_home1"
'   If a matching section key is not found, returns an empty string.
'   Only returns first matching section key.
'
' Params:
'       sectToFind - string representing the keynode you're searching for.
'           ex: "ODBCINST.INI"
'       sectToLookIn - String representing the keynode to start the search in.
'           If omitted, use parent reg object's sectionKey value.
'*****************************************************************************
On Error GoTo ErrHandler:
Const PROC_NAME As String = "findSectionKey"

    Dim sSect() As String   ' string array of subnodes
    Dim iSectCount As Long  ' length of sSect array
    Dim reg As Registry     ' use a clone reg so we don't damage current object

    ' Test for optional sectToLookIn param
    If sectToLookIn = vbNullString Then
        sectToLookIn = Me.sectionKey
    End If
    ' create clone
    Set reg = New Registry
    With reg
        .ClassKey = Me.ClassKey
        .sectionKey = sectToLookIn
        ' create array of sections to search
        .EnumerateSections sSect, iSectCount
        ' search each section in array
        Dim i As Long
        For i = 1 To iSectCount
            'Debug.Print .sectionKey & "\" & sSect(i)
            If findSectionKey = vbNullString Then
                If sSect(i) = sectToFind Then
                    ' found node
                    findSectionKey = .sectionKey & "\" & sSect(i)
                    Exit For
                Else
                    'search subnodes via recursion
                    findSectionKey = findSectionKey(sectToFind, .sectionKey & "\" & sSect(i))
                End If
            Else
                Exit For
            End If
        Next i
    End With

ExitFunction:
    If Not (reg Is Nothing) Then
        Set reg = Nothing
    End If
    Exit Function
ErrHandler:
    'errBox TypeName(Me), PROC_NAME
    Resume ExitFunction
End Function


texts:
I have (tab-separated) input files:

id1    id2    ....

id1    id3    ....

id3    id4    ....

id2    id1    ....

id3    id4    ....

.....

I need to

rearrange col1 and col2 by numerical sort.  For now I do this in a python script.
sort by col1 then col2. For now I am doing this by taking the output of the python script and using GNU sort.

My question is the following: is there a way to merge step 1 and step 2 (using GNU sort or any other GNU/Linux command-line tools)?

Is there an efficient alternative GNU/Linux command for step 1?

result:

id1    id2    ....

id1    id2    ....

id1    id3    ....

id3    id4    ....

id3    id4    ....

.....

My code actually works, I am looking to improve its speed.

Here's the Python program:

import argparse
import subprocess
import os

parser = argparse.ArgumentParser(description='')
parser.add_argument('-blast', help='input', required=True)
parser.add_argument('-out', help='output', required=True)
args = parser.parse_args()

def get_tmp():
# return a name for temporary file.

    dir = os.listdir(".")
    cpt = 0

    name = "tmp_{}".format(cpt)

    while name in dir:
        cpt += 1
        name = "tmp_{}".format(cpt)

   return name

# get a temporary name
tmp_name = get_tmp()

# open inputfile in reading and output in writing
with open(args.blast) as input_blast, open(tmp_name, 'w') as tmp_file:

    for line in input_blast:

        spt = line.strip().split()
        tmp_file.write('\t'.join(sorted(spt[0:2]) + spt[2:]) + '\n')

# sort by field one and two
child = subprocess.Popen("sort -k1 -k2 {} > temps_sort && mv temps_sort {}".format(os.path.abspath(tmp_name), args.out),shell=True)
child.wait()


texts: Count occurrence of words in a .txt file

texts:
I'm taking an intro to programming class and although I've learned some things I didn't know before (I've been using Python for about 1.5 years) I feel like I've not progressed much in writing "beautiful" code. My professor is committed to keeping this as a general intro class, and chose Python for its "friendliness" as an initial language. I can't really tell how much I'm improving (or not) as the grades at this point seem really inflated, so I wanted to get some input from here.

We were assigned an exercise in class to take a .txt file (in our case a .txt of the Gettysburg Address) and count the number of times words occur. We were then to output our results in a neatly formatted fashion. We've been getting drilled in writing functions and are starting to work with dictionaries, so I came up with this solution with those things in mind. I want to know how I can improve my code (i.e make it more efficient, Pythonic, and embrace what Python brings to the table as a language).

from re import split

def process_line(words, word_dict):
    for word in words:
        if word in word_dict:
            word_dict[word] += 1
        else:
            word_dict[word] = 1

def process_dict(word_dict):
    temp_list = []
    for key, value in word_dict.items():
        temp_list.append((value, key))

    temp_list.sort()
    return temp_list

def format_print(input_list, reverse, word_num):
    if reverse:
        input_list.sort(reverse=True)

    print "\n", ("[Unique Words: " + str(word_num) + "]").center(35, "=")
    print "-"*35 + "\n", "%-16s %s %16s" % ("Word", "|", "Count"), "\n", "-"*35
    for count, word in input_list:
        print "%-16s %s %16d" % (word, "|", count)

def word_count(_file, max_to_min=False):
    txt = open(_file, "rU")
    word_dict = {}
    for line in txt:
        if line.replace(" ", "") != ("\n" or None):
            process_line(filter(None, split("[^a-zA-Z']+", line.lower())), word_dict)

    txt.close()
    final_list = process_dict(word_dict)
    format_print(final_list, max_to_min, len(word_dict))

word_count("Gettysburg.txt", True)


texts: Dynamic IP Notification Using Google App Engine

texts:
This script is very basic: it does one thing. Connect to it's root and it will log your IP if it has never seen it before. Connect to /logs, and it will show a list of unique IPs within the server storage. I can't take 100 percent credit for it. I grabbed it off of Stack Overflow, modified it to actually run on App Engine, and changed the save mechanism to prevent duplicate entries. This thing is so simple it's shocking; considering how many different super-elaborate ways I can waste money and time doing the same thing. I use it to keep track of my ssh IP. I run wget on my App Engine address every ten minutes. Can this be improved? Are there any flaws which may compromise its efficiency?

helloworld.py

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

class Log(db.Model):
    access_time = db.DateTimeProperty(auto_now_add=True)
    ip_address = db.StringProperty()
class MainPage(webapp.RequestHandler):
    def get(self):
        ip = self.request.remote_addr
        log = Log()
        logs = Log.all()
        is_new = True
        for log in logs:
                if ip == log: is_new = False
        if is_new:
                log.ip_address = ip
                log.put()
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write('Logged your visit from ip address %s' % ip)
class LogPage(webapp.RequestHandler):
    def get(self):
        logs = Log.all()

        self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write('Ip addresses: ')
        for log in logs:
            self.response.out.write(log.ip_address + ',')
app = webapp.WSGIApplication([('/', MainPage), ('/logs', LogPage)],
                                     debug=True)

app.yaml

runtime: python27
api_version: 1
threadsafe: true

handlers:
- url: /.*
  script: helloworld.app

P.S. I'm pretty sure this isn't violating any contracts or agreements. Tell me if I'm wrong about that.

Credit: Get IP address in Google App Engine + Python


texts: Simultaneously searching listings by attributes such as category, title, postcode

texts:
Is the code below safe from SQL injection?

<?

mysql_connect ("localhost", "db","pass")  or die (mysql_error());
mysql_select_db ("db");

$term = mysql_real_escape_string($_POST['term']);

$sql = mysql_query("select * from tblListings where category like '%$term%' or title like '%$term%' or postcode like '%$term%' or info like '%$term%' ");

function highlight($needle, $haystack)
{
    return preg_replace('/(' . preg_quote($needle, '/') . ')/i', '$1', $haystack);
}

while ($row = mysql_fetch_array($sql)){

    echo '
 Category: ' . highlight($term, $row['category']);
    echo '
 Title: ' . highlight($term, $row['title']);
    echo '
 Address: ' . highlight($term, $row['add1']);
    echo '
 Street: ' . highlight($term, $row['street']);
    echo '
 City: ' . highlight($term, $row['city']);
    echo '
 Postcode: ' . highlight($term, $row['postcode']);
    echo '
 Phone: ' . highlight($term, $row['phone']);
    echo '
 E-Mail: ' . highlight($term, $row['email']);
    echo '
 Website: ' . highlight($term, $row['website']);
    echo '
 Info: ' . highlight($term, $row['info']);
    echo '

';
    //echo '
 E-Mail:   '.$row['email']; use this for the fields that you dont want to search

}

?>


texts:
I'm trying to get table header name in excel. I tried it using index, IF and MATCH. It works but I am not sure whether my formula is the best or not.

This is how my sheet looks:

And here is my formula to get produk name (E19:E22):

=INDEX(
   $C$10:$H$10,0,
      IF(IFERROR(MATCH(D19,$C$12:$C$14,0),0),1,
      IF(IFERROR(MATCH(D19,$E$12:$E$14,0),0),3,
      IF(IFERROR(MATCH(D19,$G$12:$G$14,0),0),5,0
))))


texts: Asking for optimizing part of a hog-based object detection using C++

texts:
Since Matlab implementation of HOG+SVM object detection algorithm was too slow, I decided to make use of the speed of C++ and re-implemented the algorithm in it. However, I'm more or less unfamiliar with this powerful programming language.

Anyway, at the first stage I'm going to extract the features from a set of images, each of which is of size 40*40 pixels. These images are cropped from a larger image (which I call it the base image) through a for-loop. This  loop is very fast in Matlab, and I expected it to be much faster in C++, but  it is too slow and takes 30 seconds to be finished.

The following code shows the part that is very slow and I would be grateful if you first tell me where I have made a mistake (why it is too slow), and then please make your suggestions to run this part as fast as possible.

  Mat img = imread("BaseImage.jpg");  // The base image

  HOGDescriptor hog;
  vector<float> hogvect;
  vector<Point> locs;
  Mat features;
  vector<Mat> StoreFeatures;

    for (int i = 0; i < img.rows - 40; ++i)
        {
        for (int j = 0; j < img.cols - 40; ++j)
            {

                hog.cellSize = Size(2, 2);
                hog.blockSize = Size(2,2);
                hog.blockStride = Size(1, 1);
                hog.winSize = Size (40, 40);
                hog.compute(img(Rect(j, i, 40, 40)), hogvect, Size(4, 4), Size(0, 0), locs); // Here, at each loop, a 40 * 40 pixels image is cropped from the base image, and its features are extracted through HOG.

                features.create(hogvect.size(), 1, CV_32FC1);
                for (int c = 0; c < hogvect.size(); ++c)
                {
                    *features.ptr<float>(c) = hogvect.at(c);
                 }

                 StoringFeatures.push_back(features); // A vector to store the features

            }
        }

I'm using CV 3.0.

Edit:

There are two main reasons causing the slowness of the code:

1: The hog.compute function.
2: The following for-loop:

for (int c = 0; c < hogvect.size(); ++c)
     {
       *features.ptr<float>(c) = hogvect.at(c);
     }


texts: Temperature converter using "switch" statement

texts:
I wrote a program to convert temperature into different units, where the users have to put a space between temperature and unit:

  23 f, 34 c, 45 k

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

namespace PracticeSet1
{

    class Program
    {
        public static float temp;
        public static char tempUnit;

        static void Main(string[] args)
        {
            //Getting user input
            Console.WriteLine("Enter Temprature in to convert it into other i.e  30 k, 45 f, 50 c *Put space between value and unit* ");
            string[] tempInput = Console.ReadLine().Split();

            //parse element 0
            temp = float.Parse(tempInput[0]);
            //assinging tempUnit
            tempUnit = char.Parse(tempInput[1]);

            switch (tempUnit)
            {
                //Converting temp to F and K if tempUnit == c
                case 'c':
                    Console.WriteLine("Celsius To Farhenheit and Kelvin");
                    convertCelsiusToFarhenheit();
                    convertCelsiusToKelvin();
                    break;
                //Converting temp to C and F if tempUnit == K

                case 'k':
                    Console.WriteLine("Kelvin");
                    convertKelvinToCelsius();
                    convertKelvinToFarhenheit();
                    break;
                //Converting temp to C and K if tempUnit == F

                case 'f':
                    Console.WriteLine("Farhenheit to Celsius and kelvin");
                    convertFarhenheitToCelsius();
                    convertFarhenheitToKelvin();
                    break;

            }

        }
        static void convertFarhenheitToCelsius()
        {
            Console.WriteLine((temp - 32) * 0.5556 + "°C");
        }
        static void convertFarhenheitToKelvin()
        {
            Console.WriteLine((temp + 459.67) * 5 / 9 + "°K");
        }
        static void convertCelsiusToFarhenheit()
        {
            Console.WriteLine((temp * 1.8) + 32 + "°F");
        }
        static void convertCelsiusToKelvin()
        {
            Console.WriteLine(temp + 273.15 + "°K");

        }
        static void convertKelvinToCelsius()
        {
            Console.WriteLine(temp - 273.15 + "°C");
        }
        static void convertKelvinToFarhenheit()
        {
            Console.WriteLine(temp - 459.67 + "°F");
        }
    }
}


texts:
The code below is used to download a JSON data from the web and use the data to fill a spinner. I would like to know if there is better way. Is it wise to move everything from onGetPriceType to the AsyncTask?

Interface

public interface GetBuildTypeInterface {
    public void onGetBuildType(HashMap<String,String> result);
}

AsyncTask

public class GetBuildType extends AsyncTask<Void, Void, JSONArray> {
    private GetBuildTypeInterface callback;

    public GetBuildType(GetBuildTypeInterface callback) {
        this.callback = callback;
    }

    @Override
    protected JSONArray doInBackground(Void... params) {
        UserFunctions u = new UserFunctions();
        return u.getBt();
    }

    @Override
    protected void onPostExecute(JSONArray result) {
        super.onPostExecute(result);
        HashMap<String, String> map = new HashMap<String, String>();

        if (result != null) {
            map = result.parse();
            callback.onGetBuildType(map);

        } else {
            callback.onGetBuildType(null);
        }
    }
}

Activity

public class AddFillActivityApp extends ErrorActivity implements
        GetBuildTypeInterface

{
    ArrayAdapter<String> adapterBuild;
    Spinner spinBuildType;

@Override
    public void onGetPriceType(final HashMap<String, String> result) {
        if (result != null) {
            List<String> fields = new ArrayList<String>();
            fields.addAll(result.keySet());
            adapterPrice = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item, fields);
            adapterPrice
                    .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinPriceType.setAdapter(adapterPrice);

            spinPriceType
                    .setOnItemSelectedListener(new OnItemSelectedListener() {
                        @Override
                        public void onItemSelected(AdapterView<?> parent,
                                View view, int position, long id) {

                            if (position > -1) {
                                String selection = spinPriceType
                                        .getSelectedItem().toString();
                                a.setNot_priceFor(result.get(selection));
                            }
                        }

                        @Override
                        public void onNothingSelected(AdapterView<?> arg0) {
                        }
                    });
        }else error();
    }
}


texts: Count digits in a given number using recursion

texts:
Here is my code that finds the number of digits in a given integer (either positive or negative). The code works and results in expected output.

'''
Program that returns number of digits in a given integer (either positive or negative)
'''
def ndigits(x):
    # Assume for the input 0 the output is 0
    if(x == 0):
        return 0
    if(abs(x) / 10 == 0):
        return 1
    else:
        return 1 + ndigits(x / 10)


texts:
I needed a way to find the number of arguments a function or operation in Rebol accepts (the functions arity). I could not find any direct support for this in the language, so I made my own arity function:

arity: func [
    "Returns the arity of a function, disregarding refinements."
    :f [function! op! native! action!]
    /local spec result
] [
    result: 0
    spec: copy third :f
    loop length? spec [
        switch type?/word first spec [
            word! [ result: result + 1 ]
            refinement! [ break ]
        ]
        spec: next spec
    ]
    result
]

Let's take it for a spin:

REBOL/Core 2.7.8.4.2 (2-Jan-2011)
>> do load %arity.reb
>> help arity
USAGE:
    ARITY :f

DESCRIPTION:
     Returns the arity of a function, disregarding refinements.
     ARITY is a function value.

ARGUMENTS:
     f -- (Type: function op native action)
>> arity print
== 1
>> arity +
== 2
>> arity either
== 3
>> arity quit
== 0

Questions I have:

Are there really no easier, built in way of getting the arity?
Am I covering everything (all function types) by specifying [function! op! native! action!]?
Are there any corner cases where this function will give the wrong answer?
Does it make sense to copy the parameter block from f like I do here?
Finally: Can you suggest any improvements to my code?