texts: in-nest-sequence: sequence generator in Racket

texts:
in-nest-sequence is a sequence generator that takes a function and an initial value, and the return value of invoking the function on the current value is used as the subsequent value. For example, (in-nest-sequence add1 0) returns the sequence (0 1 2 3 4 ...).

Recently, soegaard challenged me to write a define-sequence-syntax version of in-nest-sequence, that is, a macro-based version. I decided to give it a try:

#lang racket
(require (for-syntax unstable/syntax))
(provide (rename-out [*in-nest-sequence in-nest-sequence]))

(define in-nest-sequence
  (case-lambda
    [(func init)
     (make-do-sequence
      (thunk (values identity func init #f #f #f)))]
    [(func . inits)
     (make-do-sequence
      (thunk (values (curry apply values)
                     (lambda (args)
                       (call-with-values (thunk (apply func args)) list))
                     inits #f #f #f)))]))

(define-sequence-syntax *in-nest-sequence
  (lambda () #'in-nest-sequence)
  (lambda (stx)
    (syntax-case stx ()
      [[(x ...) (_ func init ...)]
       (unless (= (syntax-length #'(x ...)) (syntax-length #'(init ...)))
         (raise-syntax-error 'in-nest-sequence
                             (format "~a values required" (syntax-length #'(x ...)))
                             stx #'(init ...)))
       (with-syntax ([for-arity (syntax-length #'(init ...))]
                     [(value ...) (generate-temporaries #'(init ...))]
                     [(y ...) (generate-temporaries #'(init ...))])
         #'[(x ...) (:do-in ([(f) func])
                            (unless (procedure-arity-includes? f for-arity)
                              (raise-arity-error f (procedure-arity f) init ...))
                            ([value init] ...)
                            #t
                            ([(x ...) (values value ...)]
                             [(y ...) (f value ...)])
                            #t
                            #t
                            (y ...))])])))

I'm a complete noob at using define-sequence-syntax, so I appreciate any and all style, performance, and/or general feedback about my code. (See the original post for some usage examples.)


texts:
I need to pass an array of values in Url.Action.

Currently I'm doing:

var redirectUrl = Url.Action("search", new {
        q = criteria.Q,
        advanced = criteria.Advanced,
        salaryfrom = criteria.SalaryFrom,
        salaryto = criteria.SalaryTo,
    });

if (criteria.JobTypes != null)
    redirectUrl += criteria.JobTypes.Aggregate(string.Empty, (a, x) => a += "&jobTypes=" + x);

To give me something like:

/search?q=developer&advanced=false&salaryfrom=20000&salaryto=80000&jobTypes=Full%20Time&jobTypes=Contract

Is there a nicer/cleaner approach?


texts: Function that checks if array only contains elements of a specific type

texts:
The function checks whether an array is of a specific type (only contains elements of that type), the types the function accepts for checking is basically all the JavaScript types plus any types that the user may define manually (using a constructor).

What would you do to make the function more sophisticated? What would you remove or add? How would you improve or extend the function?

const checkArrayType = function checkArrayType(arr, type) {

  if (!Array.isArray(arr)) {
    throw new Error('The argument "arr" must be an array!');
  }
  else if (type !== null && type !== undefined && typeof type != 'function') {
    throw new Error('The argument "type" must be a function, "null", or "undefined"!');
  }

  // 'null' and 'undefined' require a different check than the main one
  if (type === null || type === undefined) {
    return arr.every(function(e){
      return e === type;
    });
  }

  return arr.every(function(e){
    /*
     * not using 'instanceof' because it would return 'true'
     * for cases like 'subObj instanceof Object'.
     * ---------------------------------
     * using 'Object(e)' so that the check works for primitives, see:
     * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object
     */
    return Object.getPrototypeOf(Object(e)) === type.prototype;
  });

};

console.log(checkArrayType([1,2,3,4], Number)); // true
console.log(checkArrayType(['hello', 10], String)); // false
console.log(checkArrayType([[1, 2.5], ['a', 'b']], Array)); // true
console.log(checkArrayType([null, null, null, null], null)); // true
console.log(checkArrayType([new String('hello'), new String('world')], Object)); // false

var Foo = function Foo(){};
console.log(checkArrayType([new Foo(), new Foo()], Foo)); // true

console.log(checkArrayType({a: null}, null)); // throws error
console.log(checkArrayType([], 'abc')); // throws error

One more thing, how am I supposed to deal with long comments like the one in this snippet ?


texts:
How can I optimize the following function? It checks whether two strings have a certain number of similar consecutive characters. As it is now, it is very slow, so how can it be improved in terms of speed/performance:

#include <stdio.h>

int overlap(char *str, const char *substr, int length);

int main(void)
{
    if (overlap("abcef01239", "abckef01798", 4))
    {
        puts("Match ...");
    }
    return 0;
}

int overlap(char *str, const char *substr, int length)
{
    const char *_sub = substr;
    while (*str)
    {
        int n = 0;
        int a = *str;
        int b = *substr;
        while (a && b)
        {
            if (a != b)
                break;

            n++;
            if (n == length)
                return 1;

            a = str[n];
            b = substr[n];
        }
        if (!*substr)
        {
            str++;
            substr = _sub;
        }
        else
        {
            substr++;
        }
    }
    return 0;
}


texts:
Following takes a range & copies, pastes, transposes & links.
There doesn't seem a way in vba to do this in 1 go that I've been able to find.
Questions are;

Is there a more efficient or safer way to do this. Keeping in mind;
-needing to do this for large ranges ie. over 100K cells.
-source & destination are in different worksheets or workbooks. So not the same worksheet.
What issues if any may exist & how to safeguard.

Thank you

Sub Foo()

    'Example1
    Call CopyPaste(Sheet1.Range("C10:D20"), Sheet2.Range("C1"))

    'Example2
    Dim wbNew As Workbook
    Set wbNew = Workbooks.Add
    Call CopyPaste(ThisWorkbook.Sheets(1).Range("C10:D20"), wbNew.Sheets(1).Range("C1"))

End Sub

Sub CopyPaste(rngSrc As Range, rngDest As Range)

    Application.ScreenUpdating = False
    ActiveWorkbook.Sheets.Add.Name = "_wsDummy_Temp_"
    Dim wsDummy As Worksheet
    Set wsDummy = ActiveWorkbook.Sheets("_wsDummy_Temp_")

    rngSrc.Copy
    wsDummy.Activate
    wsDummy.Range("A1").Select
    ActiveSheet.Paste Link:=True

    Dim vTransposed As Variant
    Dim rngSrcSrcRng As Range
    Dim vSrcSrc As Variant

    Dim rngDummy As Range
    Set rngDummy = wsDummy.Range("A1")
    Set rngDummy = rngDummy.Resize(rngSrc.Rows.Count, rngSrc.Columns.Count)
    rngDummy.Formula = Application.ConvertFormula(rngDummy.Formula, xlA1, xlA1, 1)

    Set rngSrcSrcRng = rngDummy
    vSrcSrc = rngSrcSrcRng.Formula
    vTransposed = Application.Transpose(vSrcSrc)

    Set rngDest = rngDest.Resize(rngDummy.Columns.Count, rngDummy.Rows.Count)
    rngDest.Formula = vTransposed

    rngDummy.ClearContents
    Application.DisplayAlerts = False
    wsDummy.Delete
    Application.DisplayAlerts = True
    Application.ScreenUpdating = True

End Sub

EDIT:
With the answer provided @TinMan I decided to fill over a 1M cells in a worksheet with numbers & do some benchmarking.
Original OP function: 33 to 39 seconds.
Refactored CopyPaste function: 20 to 26 seconds.
Alternate Approach TransposeLink function: 11 to 13 seconds.
It appears the last one is the fastest in the tests I did but also removes the need to use another temporary worksheet, removes need to use select or the clipboard.


texts: Layout of two different styles of event labels with CSS

texts:
I have two types of event labels. The HTML markup is:

    <time class="reg-day">Mo</time>
    <time class="reg-time">13:00-14:30 Uhr</time>

Regent Street

    <time class="work-month">Feb</time>
    <time class="work-day">24</time>

Chess Group

Moonshine Avenue

And the CSS the question is about is:

article {
    background-color: red;
    width: 20em;
    position:relative;
}

.reg-day {
   position: absolute;
   font-size:2.25em;
   font-weight:700;
   line-height:1.4;
   left:.5em;
}

.reg-time,
.reg-location {
   margin-left:5em;
   line-height: 1;
}

.work-month {
   -webkit-transform: rotate(270deg);
   width:3em;
   position: absolute;
   text-align:center;
   left:-1em;
   bottom:1em;
   font-weight:700;
}

.work-day {
   position: absolute;
   font-size:2.25em;
   font-weight:700;
   line-height:1.4;
   left:.75em;
}

.work-type,
.work-location {
   margin-left: 5em;
   line-height: 1;
}

I have two types of event labels and have created a CodePen here.

The first one has the day on the left, the time on the upper right, and the location on the lower right.

The second has the month upright on the left, the day and on the upper right the type of event, and the location on the lower right.

Basically I've managed to get the layout as I wanted.  Is the way I got there ok or is there a more robust and elegant one?

Especially the part of the day of week (of the first event type) and the day of month (of the second event type) covering more or less 2 height units of the two pieces of information on the right.

Day of week/day of month:

font-size: 3em;
line-height:1

Info:

font-size: 1em
line-height: 1.5;

would work.  That the info lines are the exact half of the day of week / day of month. Also i am unsure if using position absolute is the correct weapon of choice in that case. At least it prevents an misalignment of the margin-left: 5em elements. But over all the number of "magic numbers" feels a bit too high.


texts: Super simple templated memory pool in C++

texts:
I have a small program where I have a background thread that plays sound, so it needs to run really fast, but it also needs to do a small amount of memory management. I didn't want to use normal new and delete in a time critical area, so I threw this together, but set it up so I could reuse it elsewhere.

template <typename T, unsigned int capacity>
class MemoryPool
{
public:
    MemoryPool()
    {
        for (unsigned int i = 0; i < capacity; i++)
        {
            myUnusedMemory[i] = &myMemory[i];
        }
    }

    void* operator new(std::size_t size)
    {
        return myUnusedMemory[myUnusedIndex--];
    }

    void operator delete(void* ptr)
    {
        myUnusedMemory[++myUnusedIndex] = (T*)ptr;
    }

private:
    static int myUnusedIndex;
    static T myMemory[capacity];
    static T* myUnusedMemory[capacity];
};

template <typename T, unsigned int capacity> int MemoryPool<T, capacity>::myUnusedIndex = capacity-1;
template <typename T, unsigned int capacity> T MemoryPool<T, capacity>::myMemory[capacity];
template <typename T, unsigned int capacity> T* MemoryPool<T, capacity>::myUnusedMemory[capacity];

The intended usage is something like this:

struct Sound : public ag::util::MemoryPool<Sound, 100>
{
    // ...
};

Now when calling new Sound() I get one from my memory pool, which should be super fast. The only things that I can think of that could be improved are making operator new throw an exception when at capacity. I think I might be able to do away with typename T. The only  reason it's needed is so that myMemory knows the size of its elements, but I feel like there's another solution here.


texts:
This encryption class RSA encrypts an AES key and then when the encrypt method is called it decrypts the AES key and uses the key to encrypt the message and basically the same thing with the decryption.

However I am very very new to cryptography so I do not know if this is considered "good" or if this could be improved drastically.

--

What I would like to be reviewed:

Is this considered secure method to cipher messages
Is this efficient
Is this code "clean"

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class Cryptographer {
    // CIPHER NECESITIES:
    private KeyPairGenerator KEY_PAIR_GENERATOR;
    private KeyGenerator KEY_GENERATOR;
    private KeyPair RSA_KEYS;
    private byte[] AES_KEY_DATA;
    private Cipher AESKeyEncryptor;
    private Cipher MessageEncryptor;
    private IvParameterSpec Iv = new IvParameterSpec(SecureRandom.getSeed(16));

    // SETTINGS:
    final private int RSA_KEY_SIZE = 2048;
    final private int AES_KEY_SIZE = 256;
    final private String RSA_ALGORITHM = "RSA/ECB/OAEPWithSHA-256AndMGF1Padding";
    final private String AES_ALGORITHM = "AES/CBC/PKCS5PADDING";

    // CONSTRUCTOR:
    public Cryptographer() throws Exception {
        KEY_PAIR_GENERATOR = KeyPairGenerator.getInstance("RSA");
        KEY_GENERATOR = KeyGenerator.getInstance("AES");
        KEY_PAIR_GENERATOR.initialize(RSA_KEY_SIZE);
        KEY_GENERATOR.init(AES_KEY_SIZE);
        RSA_KEYS = KEY_PAIR_GENERATOR.generateKeyPair();

        MessageEncryptor = Cipher.getInstance(AES_ALGORITHM);
        AESKeyEncryptor = Cipher.getInstance(RSA_ALGORITHM);
        AES_KEY_DATA = EncryptAESKey(KEY_GENERATOR.generateKey());
    }

    // PRIVATE METHODS:
    private byte[] EncryptAESKey(SecretKey key) throws Exception {
        AESKeyEncryptor.init(Cipher.ENCRYPT_MODE, RSA_KEYS.getPublic());
        return AESKeyEncryptor.doFinal(
                key.getEncoded()
            );
    }

    private SecretKey DecryptAESKey(byte[] EncryptedAESKey) throws Exception {
        AESKeyEncryptor.init(Cipher.DECRYPT_MODE, RSA_KEYS.getPrivate());
        return new SecretKeySpec(
                AESKeyEncryptor.doFinal(EncryptedAESKey),
                "AES"
            );
    }

    // PUBLIC METHODS:
    public byte[] Encrypt(byte[] message) throws Exception {
        MessageEncryptor.init(Cipher.ENCRYPT_MODE, DecryptAESKey(AES_KEY_DATA), Iv);

        return MessageEncryptor.doFinal(message);
    }

    public byte[] Decrypt(byte[] message) throws Exception {
        MessageEncryptor.init(Cipher.DECRYPT_MODE, DecryptAESKey(AES_KEY_DATA), Iv);

        return MessageEncryptor.doFinal(message);
    }
}
```


texts: PHP code for blacklisting and rewriting/redirecting URLs

texts:
We faced an issue where URLs had a wrong "subfolder" in its URL, so e.g.

example.com/match1/randomgenerated

should have been

example.com/rewritewiththis/randomgenerated

We currently use this code for redirecting URLs that (maybe it could be that it only starts at urls that are "bad"):

$oldurl = JUri::getInstance();
$newurl = str_replace(['match1','match2','match3'], 'rewritewiththis', $oldurl);

$bad_urls = array('match1','match2','match3');

foreach($bad_urls as $bad_url){
    if(strpos($oldurl, $bad_url) !== false) {
        exit(header("Location: $newurl", true, 301));
    }
}

We use the $newurl also for things like this (this rewrites the generated URLs to use a correct URL and prevent duplicate content):

$oldurl = $this->getRoute($event->url_query . '&Itemid=' . $request->query->page_id)->toString();
$data['url'] = str_replace('match1', 'rewritewiththis', $oldurl);

Are there better options to do this are are is this already a good way to solve this issue?


texts: Find smallest number of squares that sum to a number

texts:
Leetcode problem 279 “Perfect Squares” is:

  Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...)

I wrote the following solution:

def numSquares(self, n):
        """
        :type n: int
        :rtype: int
        """
        sqs = [0]
        nums = {}
        for x in range(1,n+1):
            nums[x] = 1
        for i in nums:
            if (i * i) in nums:
                sqs.append(i * i)
        T = [x for x in range(n+1)]
        for i in range(1,len(sqs)):
            for j in range(1,n+1):
                if sqs[i] <= j:
                    T[j] = min(T[j],math.floor(j/sqs[i]) + T[j%sqs[i]])
        return T[n]

I wrote a dynamic-programming solution, storing results in a 1d array, but it seemed that due to the way I was originally calculating the perfect squares, the solution was timing out. I then modified the solution and came up with the one above, but the code is still causing a time out error when run against an input of 4635 for n.

How could this solution be optimized to avoid this timeout error?


texts:
I have simple class that I want to ask if is there any possible to improve it? I mean, for me it looks poor. Is there any way to use here try-with-resources, stream or optional?

package bookstore.scraper;

import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.IOException;

@Slf4j
public class JSoupConnector {

    public static Document prepareConnectionToURL(String URL) {
        Document document = null;
        try {
            document = Jsoup.connect(URL).get();
        } catch (IOException e) {
            log.warn("Cannot connect to URL!");
        }
        return document;
    }
}


texts:
The code below just senses when the network is available and enables/disables a button on the UI. If I am registered to the NetworkAvailability event for the life of the program, will it cause a memory leak? I heard it might but didn't understand why.

System.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged += new System.Net.NetworkInformation.NetworkAvailabilityChangedEventHandler(NetworkChange_NetworkAvailabilityChanged);

delegate void EnableCallback();

void NetworkChange_NetworkAvailabilityChanged(object sender, System.Net.NetworkInformation.NetworkAvailabilityEventArgs e)
{
    EnableSync();
    //throw new NotImplementedException();
}

private void EnableSync()
{
    if (this.btnSync.InvokeRequired)
    {
        EnableCallback methodCallback = new EnableCallback(EnableSync);
        this.Invoke(methodCallback, new object[] { });
    }
    else
    {
        if (btnSync.Enabled == true)
            btnSync.Enabled = false;
        else
            btnSync.Enabled = true;
    }
}


texts: Check bitstamp.net exchange rate, compare it with previous rate

texts:
I have written low quality php code, I'm not a good coder ;) Help me, please, to optimise it ;)

This simple code check bitstamp.net exchange rate, compare it with previous rate and print the result.

<?php
function getPrice($url) {
    $decode = @file_get_contents($url);
    return json_decode($decode, true);
}

$btc = getPrice('https://api.binance.com/api/v1/ticker/24hr?symbol=BTCUSDT');
$btcusdlast = round($btc["lastPrice"], 1);
$rbtc = ($btc["priceChange"]>0) ? 'up' : ' down';

$ltc = getPrice('https://api.binance.com/api/v1/ticker/24hr?symbol=LTCUSDT');
$ltcusdlast = round($ltc["lastPrice"], 1);
$rltc = ($ltc["priceChange"]>0) ? 'up' : ' down';

?>

BTC
    $ <?=$btcusdlast, ' ', $rbtc;?>

LTC
    $ <?=$ltcusdlast, ' ', $rltc;?>

But it's low quality and work very slowly.


texts: Editing Javascript and rendering HTML in one window

texts:
I've been trying to learn the basics of Javascript, so this afternoon I put together a small JavaFX application that has a raw text area on the left, and an HTML rendering on the right:

public class Fifty extends Application {
    private String filePath = null;
    private TextArea text;
    public void init() throws Exception {
        super.init();
        Parameters parameters = getParameters();
        List<String> unnamedParams = parameters.getUnnamed();
        if (unnamedParams.size() > 0) {
            filePath = unnamedParams.get(0);
        }
    }
    public void start(Stage stage) throws Exception {
        SplitPane splitPane = new SplitPane();
        text = new TextArea();
        final WebView web = new WebView();
        try {
            text.setText(readFile(filePath, Charset.defaultCharset()));
            web.getEngine().loadContent(text.getText());
        } catch (Exception e) {
            alertException(e);
        }
        text.setStyle("-fx-font-family: monospace");
        text.textProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(final ObservableValue<? extends String> observable,
                    final String oldValue, final String newValue) {
                web.getEngine().loadContent(text.getText());
            }
        });
        splitPane.getItems().addAll(text, web);
        Scene scene = new Scene(splitPane);
        scene.setFill(Color.RED);
        stage.setScene(scene);
        stage.setTitle("eleven-fifty: because i'm bad at naming things");
        stage.show();
    }
    public void stop() {
        try {
            saveFile(filePath, text.getText());
        } catch (Exception ex) {
            ex.printStackTrace();
            System.err.println("file not saved!");
        }
    }
    static String readFile(String path, Charset encoding) throws IOException {
        byte[] encoded = Files.readAllBytes(Paths.get(path));
        return new String(encoded, encoding);
    }
    static void saveFile(String path, String text) throws Exception {
        PrintWriter out = new PrintWriter(path);
        out.print(text);
        out.close();
    }
    static void alert(String title, String body) {
        Alert alert = new Alert(AlertType.INFORMATION);
    alert.setTitle(title);
    alert.setContentText(body);
    alert.show();
    }
    static void alertException(Exception e) {
        StackTraceElement[] trace = e.getStackTrace();
        int i = 0;
        StringBuilder traceRes = new StringBuilder();
        traceRes.append(String.format("%s\n", e.toString()));
        for (StackTraceElement element: trace) {
            traceRes.append(String.format("%s\n", element.toString()));
            if (++i > 10) break;
        }
        alert("Exception", traceRes.toString());
    }
}

Finally, a script to automatically launch the .jar file:

java -jar eleven-fifty.jar %1
pause

How can this simple application be improved?


texts: Reading genetic data in VCF and Tabix formats using an asynchronous library

texts:
I'm working with an open-source library for processing and parsing genetic data in VCF and Tabix formats. It contains functions and classes that make it easy to read an index file (a Tabix) and load corresponding data from a compressed VCF.

It works asynchronously (unsurprisingly), however, and I'm not sure of the best way to structure my code. I'm looking to make multiple calls to the getRecords() method—since I need to retrieve multiple discontinuous segments of data; because this is asynchronous, it seems like I also have to instantiate a new file reading object (here known as readBinaryVCF but roughly analogous to HTML's FileReader). Both the file reading object's constructor and the getRecords() function use callbacks.

I'm not really experienced in JavaScript or asynchronous design patterns; I'm hoping it doesn't have to be this convoluted. Other solutions that I tried, though, like recursing or making multiple calls  to getRecords() on the same object, were not as flexible or as robust—or just flat out didn't work.

The code sample below is the first iteration I've gotten to work. That being said, please tear it apart. I suspect there're many improvements to be made.

EDIT: I'll leave this code alone as my first draft, but please look at the minor changes I've made in an answer below. I'm still hoping for help, preferably on top of my revisions.

var regions = [
    [10, 10000, 100000],
    [12, 10000, 100000],
    [14, 10000, 100000],
    [18, 10000, 100000]
];

var d = [];
var readers = [];

for (var a = 0; a < regions.length; a++) {
    d.push([]);
    readers.push(new readBinaryVCF(tabix, vcf, function(x) {x = x;}));
    //Should I just initialize these to null instead?
}

regions.forEach(function(item, i) {

    readers[i] = new readBinaryVCF(tabix, vcf, function(tabixReader) {

        rbvcf = readers[i];

        var index = 0;
        for (key in tabixReader.idxContent.namehash) {
            if (key == regions[i][0]) {
                index = tabixReader.idxContent.namehash[key];
            }
        }

        rbvcf.getRecords(index, regions[i][1], regions[i][2], function(data) {
            d[i] = data;

            if (i == regions.length - 1) {
                var finalText = "";

                for (var j = 0; j < d.length; j++) {
                    for (var k = 0; k < d[j].length; k++) {
                        finalText = finalText + d[j][k] + "<br />";
                    }
                }

                $(".text").html(finalText);
            }
        });
    });
});


texts: Sudoku solver using backtracting and depth-first-search

texts:
I've recently finished my first ever C program. I implemented a Sudoku solver that uses backtracking.

Does my code look like a proper C-program? Are there any recommendations for improving my code?

#include <stdio.h>

int valid(int[][9], int, int, int);
int solve(int[][9]);
int find_empty_cell(int[][9], int *, int *);

int main() {
  int puzzle[9][9] = {{1, 7, 4, 0, 9, 0, 6, 0, 0},
                      {0, 0, 0, 0, 3, 8, 1, 5, 7},
                      {5, 3, 0, 7, 0, 1, 0, 0, 4},
                      {0, 0, 7, 3, 4, 9, 8, 0, 0},
                      {8, 4, 0, 5, 0, 0, 3, 6, 0},
                      {3, 0, 5, 0, 0, 6, 4, 7, 0},
                      {2, 8, 6, 9, 0, 0, 0, 0, 1},
                      {0, 0, 0, 6, 2, 7, 0, 3, 8},
                      {0, 5, 3, 0, 8, 0, 0, 9, 6}};
  int row = 0;
  int column = 0;

  if (solve(puzzle)) {
    printf("\n+-----+-----+-----+\n");
    for (int x = 0; x < 9; ++x) {
      for (int y = 0; y < 9; ++y) printf("|%d", puzzle[x][y]);
      printf("|\n");
      if (x % 3 == 2) printf("\n+-----+-----+-----+\n");
    }
  }
  else {
    printf("\n\nNO SOLUTION FOUND\n\n");
  }

  return 0;
}

int valid(int puzzle[][9], int row, int column, int guess) {
  int corner_x = row / 3 * 3;
  int corner_y = column / 3 * 3;

  for (int x = 0; x < 9; ++x) {
    if (puzzle[row][x] == guess) return 0;
    if (puzzle[x][column] == guess) return 0;
    if (puzzle[corner_x + (x % 3)][corner_y + (x / 3)] == guess) return 0;
  }
  return 1;
}

int find_empty_cell(int puzzle[][9], int *row, int *column) {
  for (int x = 0; x < 9; x++) {
    for (int y = 0; y < 9; y++) {
      if (!puzzle[x][y]) {
        *row = x;
        *column = y;

        return 1;
      }
    }
  }
  return 0;
}

int solve(int puzzle[][9]) {
  int row;
  int column;

  if(!find_empty_cell(puzzle, &row, &column)) return 1;

  for (int guess = 1; guess < 10; guess++) {
    if (valid(puzzle, row, column, guess)) {
      puzzle[row][column] = guess;

      if(solve(puzzle)) return 1;
      puzzle[row][column] = 0;
    }
  }
  return 0;
}


texts: Is this correct way to use cookies from a syntax point of view?

texts:
I'd like to know if this is the right syntax for using cookies. I haven't yet tested this code with cookies being used.

I'm using a jQuery Plugin called jPages to display pages on my (one page) website, it has a lot of options and it's very flexible.

The jPages plugin has an option to start from a different page per say, and a callback function to find what page you are currently on.

I'm using localStorage to store the last page that a visitor has been on so that it can be retrieved when they return. I've tested this method and it works perfectly.

I'm using Modernizr to test for localStorage support in browsers, and if localStorage is not supported I use cookies to try and achieve the same experience.

Here's the part of my code that does that:

var set_data = function(cluster) {
    if (!localStorage.getItem("Page")) {
        if (!localStorage.setItem("Page", JSON.stringify(cluster))) {
            log("Current Page: Stored");
        } else {
            log("Current Page: Store Failed");
        }
    } else {
        localStorage.removeItem("Page");
        if (!localStorage.setItem("Page", JSON.stringify(cluster))) {
            log("Current Page: Stored");
        } else {
            log("Current Page: Store Failed");
        }
    }
}

var get_data = function() {
    if (localStorage.getItem("Page")) {
        var last_page = JSON.parse(localStorage.getItem("Page"))
        log("Last Page: " + last_page);
        return last_page;
    } else {
        log("Last Page: Inexistent");
        return 1;
    }
}

var set_last_page = function(cluster) {
    if (Modernizr.localstorage) {
        var data = cluster;
        set_data(data);
    } else {
        var data = JSON.stringify(cluster);
        create_cookie("Page", data, 365);
    }
}

var get_current_page = function() {
    if (Modernizr.localstorage) {
        var data = get_data();
    } else {
        var data = JSON.parse(read_cookie("Page"));
    }
    return data;
}

var create_cookie = function(name, value, days) {
    var date;
    var expires;

    if (days) {
        date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    } else {
        expires = "";
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}

var read_cookie = function(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    var i;
    var c;

    for (i = 0; i < ca.length; i++) {
        c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1, c.length);
        }

        if (c.indexOf(nameEQ) == 0) {
            return c.substring(nameEQ.length, c.length);
        }
    }
    return null;
}

The localStorage part works, but I'm not sure if I'm doing the cookie part correctly.

If someone can tell me if this is the right syntax for using cookies, I would appreciate it.


texts: Created a basic User Profile List using an API (React)

texts:
I'm relatively new when it comes to programming in React and in JavaScript, but have a surface level understanding of what things do. I've created a basic program that fetches user data from an API that generates random users, and appends the users to a list when you click a button. I was wondering if what I'm writing is good enough to be considered for a Jr. React Dev position, and if there's anything I can improve upon the code such as implementation, name convention, readability, efficiency, etc. In particular, in the UserProfile component, I'm mapping through the state that holds the JSON object that was fetched from the API to output the profile picture and name. I'm not sure if there's anyway to do it better, but it doesn't feel quite right to me. Any feed back is much appreciated.
UserProfile.jsx
import React, { useState, useEffect } from "react";

const UserProfile = () => {
  const [userData, setUserData] = useState([]);

  const fetchUserData = () => {
    fetch("https://randomuser.me/api")
      .then((resp) => resp.json())
      .then((data) => setUserData(data.results));
  };

  //Creates userProfile with picture/full name
  const userProfile = (userMeta) => {
    const {
      name: { first, last },
      picture: { medium }
    } = userMeta;

    return (
      <>

          {first}, {last}

      </>
    );
  };

  //Fetch API data on component mount
  useEffect(() => {
    fetchUserData();
  }, []);

  return (
    <>
      {userData.map((userMeta, idx) => {
        return
{userProfile(userMeta)}
;
      })}
    </>
  );
};

export default UserProfile;

UserList.jsx
import React, { useState } from "react";
import UserProfile from "./UserProfile";

const UserList = () => {
  const [userList, setUserList] = useState([]);

  //Appends UserProfile to List
  const addUser = () => {
    setUserList((prevState) => {
      return [...prevState, <UserProfile />];
    });
  };

  return (

      <button onClick={addUser}>Add User</button>
      {userList.map((user, idx) => {
        return <React.Fragment key={idx}> {user} </React.Fragment>;
      })}

  );
};

export default UserList;

App.js
import React from "react";
import UserList from "./UserList";

export default function App() {
  return (

USER LIST COMPONENT

      <UserList />

  );
}


texts: Functionality for automatic retry after exception

texts:
I have made the following system to automatically retry network calls if some exception is thrown. (Earlier posted on stackOverFlow, solution inspired by what @Boris answered)

public static <T> Optional<T> autoRetry(@NonNull final DoWork<T> task, @NonNull final Optional<Predicate<T>> resultRejector) {

        for (int retry = 0; retry <= StaticData.NETWORK_RETRY; ++retry) {

            try {

                Thread.sleep(retry * StaticData.NETWORK_CALL_WAIT);
                final T resultAfterWork = task.doWork();
                /**
                 * If the result was not
                 * desirable we RETRY.
                  */
                if(resultRejector.isPresent() && resultRejector.get().apply(resultAfterWork))
                    continue;
                /**
                 * Else we return
                 */
                return Optional.fromNullable(resultAfterWork);
            } catch (InterruptedException | UnknownHostException e) {
                e.printStackTrace(); //To be replaced by proper logging
                return Optional.absent();
            } catch (IOException e) {
                e.printStackTrace(); //To be replaced by proper logging
            }
        }
        return Optional.absent();
    }

I take care to not retry after InterruptedException &
UnknownHostException.
I retry 5 times. After each failure I perform an exponential back
off, starting from 300ms going upto 1500ms.
The predicate is used to verify the validity of the expected result.

The DoWork class :

public abstract class DoWork<T> {
    protected abstract T doWork() throws IOException;
}

I did not use Supplier because I need to throw an IOException.

Here is an example of how I use it. (this example updates the GCM Id)

//Context is android specific stuff, basically if app dies, reference will return null.

public static boolean updateGCM(final long id, final WeakReference<Context> reference) {

final String regId = autoRetry(new DoWork<String>() {
    @Override
    protected String doWork() throws IOException {

        final Context context = reference.get();
        if(context == null)
            return "QUIT";
        return GoogleCloudMessaging.getInstance(context)
                .register("XXXXXXXXXX");
    }
}, Optional.<Predicate<String>>of(new Predicate<String>() {
    @Override
    public boolean apply(@Nullable String input) {
        return TextUtils.isEmpty(input); //I need to retry if the returned GCM ID was null/empty
    }
})).orNull();
//Context becomes null when the application is exited
//If retires failed or application exited, we return
if(TextUtils.isEmpty(regId) || regId.equals("QUIT"))
    return false;

Log.i("Ayush", "Uploading newGcmId to server");
final Boolean result = autoRetry(new DoWork<Boolean>() {
    @Override
    protected Boolean doWork() throws IOException {

        //if everything is fine, send id to server
        return true;
    }
}, Optional.<Predicate<Boolean>>absent()).orNull(); //No need of predicate hence send absent

return !(result == null || !result);
}

So on a scale of 1 to 10 how professional is this approach ? :)
Also I do not want to retry if the network is genuinely failing, like
UnknownHostException, or something bad happens which wont get
resolved with retrying. Any possibility of improving exception handling ?


texts: Program to move in a 2d array given instructions, array and starting position

texts:
Original problem (not in English): https://pokval21.kattis.com/problems/pokval21.robotdammsugaren
How can my code be optimized?
import sys
j = 0
instructions = []
room = []
for i in sys.stdin:
    inp = i.split()
    if(j == 0):
        r = int(inp[0])
        c = int(inp[1])
        k = int(inp[2])
    if(j==1):
        instructions = list(inp[0])
    if(j >= 2):
        room.append(list(inp[0]))
    if(len(room) == r):
        break
    j += 1
def findStartPos(c, room):
    for y, sublist in enumerate(room):
        pos = []
        if c in sublist:
            x = room[y].index(c)
            pos.append(x)
            pos.append(y)
            return pos
    return -1
botPos = findStartPos("O", room) # [x, y]
x = botPos[0]
y = botPos[1]
i = 0
visited = [botPos]
clean = 1
append = visited.append
for i in instructions:
    if(i == ">"):
        while room[y][x+1] != "#":
            if([x+1, y] in visited):
                pass
            else:
                append([x+1, y])
                botPos = [x+1, y]
                clean += 1
            x += 1
        botPos = [x, y]
    elif(i == "<"):
        while room[y][x-1] != "#":
            if([x-1, y] in visited):
                pass
            else:
                append([x-1, y])
                botPos = [x-1, y]
                clean += 1
            x -= 1
        botPos = [x, y]
    elif(i== "^"):
        while room[y-1][x] != "#":
            if([x, y-1] in visited):
                pass
            else:
                append([x, y-1])
                botPos = [x, y-1]
                clean += 1
            y -= 1
        botPos = [x, y]
    elif(i == "v"):
        while room[y+1][x] != "#":
            if([x, y+1] in visited):
                pass
            else:
                append([x, y+1])
                botPos = [x, y+1]
                clean += 1
            y += 1
        botPos = [x, y]
print(clean)

What I'm doing is taking an input where the first line is r c k.
r is the max y value in the 2d array starting from 1, c is the max x value starting from 1 arr[y][x] and k is the amount of instructions.
the second is a line of instructions eg. <>^v for left, right, up and down.
In the function findStartPos I am iterating though the 2d array of strings I created from the rest of the input eg,
[[#, #, #, #], [#, O, #, ., #], [#, . ., ., #], [#, #, ., ., #], [#, #, #, #]]
to find the starting cordinates of O.
In the rest of the code I go though the instructions and moving the O around to count how many unique points it has been on. It can't be on a #. eg.
###### instuction: <
#....#
#.#.O#
###### instuction: ^
#....#
#.#O.#
###### instuction: <
#..O.#
#.#..#
###### instuction: None
#O...#
#.#..#
been on 5 unique "squares"

Samples:
5 5 4
v>^v
#####
#O#.#
#...#
##..#
#####
returns: 6

8 10 14
<v>^<v>v<^^><>
##########
#.#......#
#....#...#
##......O#
#........#
#..#.....#
#....#...#
##########
returns: 33

Hope the code is readable enough to be understood.


texts:
I have a page with a few options that the owner of a site needs to be able to set. He's not a coder and I'm trying to make it as user-friendly as possible.

It works, but my implementation feels sloppy and I was wondering if there's a better way to do it.

This first part from my main javascript file will be minified and the site owner won't even need to look at it. The unminified source might be passed on to another developer in the future, though:

/* If this Squarespace page title isn't in the onlyShowOn list of pages,
 * stop now. */
var pageTitle = $('meta[property="og:title"]').attr('content');
if (pageTitle !== undefined && onlyShowOn.indexOf(pageTitle) == -1 ) {
    return true;
}

if (pageOptions.hasOwnProperty(pageTitle) && pageOptions[pageTitle] !== undefined) {
    var pageOption = pageOptions[pageTitle];
    if (pageOption.hasOwnProperty('skipHeadings') && pageOption.skipHeadings !== undefined) {
        skipHeadings = pageOption.skipHeadings;
    }

    if (pageOption.hasOwnProperty('headingSubstitution') && pageOption.headingSubstitution !== undefined) {
        headingSubstitution = pageOption.headingSubstitution;
    }
}

I don't like all the hasOwnProperty and checking for undefined, but I want to cover the cases where he doesn't set the options for all his pages or doesn't set all of the options.

Here's the options file that he will modify before injecting all of the code into the footer of his Squarespace site:

/* skipHeadings:
    This variable is used to exclude headings from the ToC. For example, a
    value of 2 will exclude the first 2 headings from the ToC.  */
var skipHeadings = 1;

/* headingSubstitution:
    This variable is used to provide substitutions which will show in the
    ToC. Any heading that matches exactly the quoted text before the colon
    will appear in the table of contents using the quoted text after the
    colon.
     - The values have to be quoted.
     - The heading and the substitution have to be separated by a colon.
     - The substitutions have to be separated by commas.  */
var headingSubstitution = {
    'A really long heading to test box size issues.': 'Long Heading ...',
    'Playing with Tocify': 'Playing ...' // You can add comments here, too.
};

/* onlyShowOn:
    This variable contains the list of pages on which the ToC will show.
     - The values have to be quoted, separated by commas, and match the name
       of your page in Squarespace exactly.
     - You can use either single- or double-quotes.
     - The entries can be on separate lines as long as they're separated by
       commas.  */
var onlyShowOn = [
    'Some Other Page',  // You can add comments after the page names like this.
    'Tocify Test Page', // The name of the page I'm using on my development server.
    'Tocify Page', // The name of the page I'm using on my Squarespace test site.
];

/* pageOptions:
    This variable contains per-page options for skipHeadings and
    headingSubstitution. The values above are used as defaults if a value is
    set here, it completely overrides the default value. As with the onlyShowOn
    option, the page name must match the name of your page in Squarespace
    exactly. The rules for the value definitions are the same as for the
    default options. */
var pageOptions = {
    'Some Other Page': {
        'skipHeadings': 2,
        'headingSubstitution': {
            'A really long heading to test box size issues.': 'Long Heading ...',
        }
    },
    'Tocify Test Page': {
    },
    'Tocify Page': {
    }
};


texts: Is it a good practice to put an exception handler in every method?

texts:
I always add an exception handler when a new method is created, and I don't know if it is a good or bad practice.  I thought it may be a bit of an annoyance when viewing the source code.

Is it a good practice to put logging functions in the exception block?

def insert_new_camera(self, camera, records, file_hdlr):
    try:
        pass
    except BaseException  as e:
        traceback.print_exc(file=sys.stdout)
        raise e


texts: Finding the perfect numbers between 1 - 1000

texts:
This code was made to find all the perfect numbers between 1 and 1000. A perfect number, is a number where all of it's divisors add up to that number.

For example:

6 is divisible by 3,2, and 1 and3+2+1 = 6. Therefore 6 is a perfect number.

public class Perfect {
    public static void main(String[] args) {
        final int LIMIT = 1000;
        boolean isPerfect = false;
        int i;
        for(i = 2; i < LIMIT; i++) {
            isPerfect = isNumPerfect(i);
            if(isPerfect) {
                System.out.println(i + " is a perfect number");
            }
        }
    }
    public static boolean isNumPerfect(int i) {
        boolean isPerfect = false;
        int sum = 1;
        int x;
        for(x = 2; x <= i / 2; x++) {
            if(i % x == 0) {
                sum += x;
            }
        }
        if(sum == i) {
            isPerfect = true;
        }
        return isPerfect;
    }
}

What are some ways that I can improve on this code? More specifically, ways to shorten it.


texts: Best data Structure for storing a phone keypad format

texts:
I was trying to code the phone keypad characters with its numbers. The first idea which came to my mind is using a HashMap. After trying various options I came up with the below Code. I want to know if the data structure and methodology which I implemented is good or does it need some more improvements.
Things which I know and don't want to implement:

I do not want to hardcode the keypad. I know that there are various ways of implementing a hardcoded keypad. I visited this and this link to learn about other ways.
I would really be thankful if the solution is given in java 7 syntax. I don't have much idea about java 8 syntax, but it'll be helpful to know the solution in that too, if possible.

Keypad feature according to my problem statement:

0 and 1 buttons are not functional.
7 and 9 buttons contain 4 letters each and others contain 3 letters each.

public static void keypadDemo(){
        int ax = 97; // I need to store lower-case letters so took this
        Map<Integer, ArrayList<Character>> hm = new HashMap<>(); // This is my data-structure
        for(int i = 0; i < 10; i++){
            if(i == 0 || i == 1){
                hm.put(i, null); // 0 and 1 keys are not functional as per my problem statement.
            }else if(i == 7 || i == 9){
                hm.put(i, new ArrayList<>(Arrays.asList((char) ax, (char) ++ax, (char) ++ax, (char) ++ax)));
                ax++;
            }else{
                hm.put(i, new ArrayList<>(Arrays.asList((char) ax, (char) ++ax, (char) ++ax)));
                ax++;
            }
        }
       System.out.println(hm);
    }

Any help will be welcomed. Thanks
EDIT:
Keypad format:

The problem statement:

We are given two inputs:

A phone number in string format.
A list of strings.

The output is the list containing only those strings which correspond to any substring of the given phone number when converted to the corresponding letters on the phone keypad.

Example test case:

Input:
3662277
words = ["foo", "bar", "baz", "emo", "foobar", "cap", "car", "cat"]

Output:
outputList = ["foo", "bar", "foobar", "emo", "cap", "car"]

I coded the solution and it got accepted too by online judge. But since, I'm learning about Collections in java so wanted to know whether my choice of the data structure is good or not.


texts:
I've to do a generic method Classify<T> that, given a sequence of elements of type T and an arbitrary number of predicates, returns an array of n+1 lists (where n is the number of the predicates). More precisely, if the element satisfies the first predicate then it is added to the first list. If not, then if the element satisfies the second predicate it is added to the second list, etc. If none of the predicates can be applied to one element, then that element is added to the last list (the n+1 th).

I managed to do that with the following code. Is there any way to do it better, maybe with Linq?

public List<T>[] Classify<T>(IEnumerable<T> sequence, params Predicate<T>[] predicates)
{
    var result = new List<T>[predicates.Length+1];
    var counter = 0;
    foreach (var elem in sequence)
    {
        var valid = false;
        foreach (var predicate in predicates)
        {
            if(result[counter]==null)
                result[counter] = new List<T>();
            if (predicate(elem) && valid==false)
            {
                var partition = result[counter];
                partition.Add(elem);
                valid = true;
            }
            counter++;
        }
        if (!valid)
        {
            if (result[counter] == null)
                result[counter] = new List<T>();
            result[counter].Add(elem);
        }
        counter=0;
    }
    return result;
}


texts: How to read a complete Unicode code point as String?

texts:
I tried this so far:

public String readchar (Reader input) throws java.io.IOException
{
  int i16 = input.read(); // UTF-16 as int
  if (i16 == -1) return null;
  char c16 = (char)i16; // UTF-16
  if (Character.isHighSurrogate(c16)) {
    int low_i16 = input.read(); // low surrogate UTF-16 as int
    if (low_i16 == -1)
      throw new java.io.IOException ("Can not read low surrogate");
    char low_c16 = (char)low_i16;
    int codepoint = Character.toCodePoint(c16, low_c16);
    return new String (Character.toChars(codepoint));
  }
  else
    return Character.toString(c16);
}

But it contains unsafe casts. I have no idea how to avoid them. Is it possible?


texts: Reversing the "words" of a container with a bidirectional iterator

texts:
I posted another snippet of code a few weeks back when I started learning C++. Here's my second try now that I have some time to play with this again. The goal is to write a generic algorithm for reversing the "words" of a container with a bidirectional iterator. Separators of words are any values that a functor parameter deems as a separator.

#include <iostream>
#include <utility>
#include <string>
#include <cctype>

template<typename BidirIt>
void my_reverse(BidirIt first, BidirIt last)
{
  for(--last; first < last; ++first, --last)
    std::swap(*first, *last);
}

template<typename BidirIt, typename IsSeparatorTester>
void reverse_words(BidirIt first, BidirIt last, IsSeparatorTester issep)
{
  my_reverse(first, last);

  for(auto it = first; it != last; ++it) {
    if(issep(*it)) {
      my_reverse(first, it);
      first = it;
      ++first;
    }
  }

  // we bail out of the loop before inverting last word
  my_reverse(first, last);
}

int main()
{
  std::string test { " this   is a   test   " };
  std::cout << test << std::endl;
  reverse_words(test.begin(), test.end(), isspace);
  std::cout << test << std::endl;
  return 0;
}

As a comment, I know that STL has a reverse procedure, but I wanted to try to implement something similar myself.


texts: Improving time it takes to insert thousands of records using Entity Framework

texts:
I have a task in my program that is inserting thousands (94,953 in one instance and 6,930 in another) of records into my database using Entity Framework.

Right now I am doing this and calling the .Add() method for each record but it takes about 1 minute to insert the smaller batch and over 20 minutes for the larger batch. I have tried the .AddRange() method but that jumped the smaller batch to over 4 minutes.

Is there another approach with Entity Framework 6 or is this a limitation I have to live with? If it makes any difference, the data is going into a SQL Server 2012 R2 instance.

        var taskCodes = DynamicsHelper.GetTaskCodes(dynamicsSession, "01-01-1990");
        Console.WriteLine("Adding task codes to database.");

        using (var db = new JobSightDbContext())
        {
            foreach (var taskCode in taskCodes)
            {
                var projectID = db.ProjectCodes.Where(project => project.Code == taskCode.Item4).Select(project => project.ID).FirstOrDefault();

                if (projectID != 0)
                {
                    var newTaskCode = new TaskCode()
                    {
                        Code = taskCode.Item1,
                        Description = taskCode.Item2,
                        IsActive = taskCode.Item3,
                        ProjectID = projectID
                    };

                    db.TaskCodes.Add(newTaskCode);
                    db.SaveChanges();
                }
            }

            Console.WriteLine("{0} tasks added to the database.", db.TaskCodes.Count());
        }


texts: Disable reboot on control-alt-delete for RedHat/CentOS 5/6/7

texts:
As root, run:

#!/bin/sh
if cat /etc/redhat-release | grep -q 'release 5'; then
  cp /etc/inittab /etc/inittab.install
  sed -i 's/ca::ctrlaltdel/#ca::ctrlaltdel/' /etc/inittab
  init q
elif cat /etc/redhat-release | grep -q 'release 6'; then
  cat << EOF > /etc/init/control-alt-delete.conf
exec false
EOF
elif cat /etc/redhat-release | grep -q 'release 7'; then
  systemctl mask ctrl-alt-del.target
  systemctl daemon-reload
else
  cat /etc/redhat-release 2>&1 | mailx -s "ctrl-alt-delete disable failure" some.user@company.com
fi


texts:
So here is my next creation, a circular checkbox. This is my third custom control, so I'm still learning, but have the basics just about down. Tips and suggestions are most appreciated:

class CircularCheckbox : Control
{
    private Color borderColor;
    public Color BorderColor
    {
        get { return borderColor; }
        set { borderColor = value; }
    }

    private Color background;
    public Color Background
    {
        get { return background; }
        set { background = value; }
    }

    private Color tickColor;
    public Color TickColor
    {
        get { return tickColor; }
        set { tickColor = value; }
    }

    private bool isChecked;
    public bool IsChecked
    {
        get { return isChecked; }
        set { isChecked = value; }
    }

    public CircularCheckbox(bool IsChecked)
    {
        DoubleBuffered = true;
        SetStyle(ControlStyles.SupportsTransparentBackColor, true);
        this.BackColor = Color.Transparent;

        this.IsChecked = IsChecked;
        Background = Color.White;
        BorderColor = Color.Black;
        TickColor = Color.Green;
    }

    public CircularCheckbox()
        : this(false)
    { }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);

        e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
        Rectangle rc = this.ClientRectangle;
        Graphics g = e.Graphics;
        StringFormat sf = new StringFormat();
        Font f = new Font("Arial", (float)rc.Height * 0.5f, FontStyle.Bold, GraphicsUnit.Pixel);

        sf.Alignment = StringAlignment.Center;
        sf.LineAlignment = StringAlignment.Center;

        g.FillEllipse(new SolidBrush(Background), rc.Left + 1.5f, rc.Top + 1.5f, rc.Width - 4.0f, rc.Height - 4.0f);
        g.DrawEllipse(new Pen(new SolidBrush(BorderColor), 3.0f), rc.Left + 1.5f, rc.Top + 1.5f, rc.Width - 4.0f, rc.Height - 4.0f);

        if (IsChecked)
            g.DrawString("\u2713", f, new SolidBrush(tickColor) , rc, sf);

    }

    protected override void OnClick(EventArgs e)
    {
        base.OnClick(e);

        IsChecked = IsChecked ? false : true;

        Invalidate();
    }
}


texts: Finding the value 'n' in an array that has 'n' or more larger values

texts:
Given an unsorted array of integers, you need to return maximum possible \$n\$
  such that the array consists at least \$n\$ values greater than or equals
  to \$n\$. Array can contain duplicate values.

  Sample 1

input : [1, 2, 3, 4]
output: 2

  Sample 2

input : [900, 2, 901, 3, 1000]
output: 3

What do you folks think of my code to this problem?

      public static Integer findN(Integer[] values) {
        Comparator comparator = new Comparator<Integer>() {
          @Override
            public int compare(Integer o1, Integer o2) {
              return o2.compareTo(o1);
            }
        };
        Arrays.sort(values, comparator);
        for (int i = 0 ; i < values.length; i++) {
            if (i >= values[i]) {
                return values[i];
            }
        }
        return Integer.MIN_VALUE;
      }


texts: Python script to update an existing column values in a csv from another two tables

texts:
I need to update two columns: feedID and OperatID of table#1.csv with 'feed description', 'Operate description' from other CSV files. I don't have the pandas module available.

import csv
table1 = r'N:\Extracts\table1.csv'
table2 = r'N:\Extracts\table2.csv'
with open(table1,'r+')as f1:
    f1reader = csv.reader(f1)
    f1reader.next()
    f1writer = csv.writer(f1)
    for row in f1reader:
        in_fdrid = row[2]
        def get_fdrname(in_fdrid):
            with open(table2,'rU')as f2:
                f2reader = csv.reader(f2)
                for f2row in f2reader:
                    if in_fdrid == f2row[1]:
                        fdrnm = f2row[2]
                        return fdrnm
            f2.close()
        row[2].replace(in_fdrid,get_fdrname(in_fdrid))


texts:
I was wondering if there is a smarter way of doing the following code. Basically what is does is that it opens a data file with a lot of rows and columns. The columns are then sorted so each column is a vector with all the data inside.

"3.2.2 - Declare variables"
lineData    = list()

for line in File:
  splittedLine = line.split() # split
  lineData.append(splittedLine) #collect

And here the fun begins

"3.2.3 - define desired variables from file"
col1    = "ElemNo"
col2    = "Node1"
col3    = "Node2"
col4    = "Length"
col5    = "Area"
col6    = "Inertia"
col7    = "Fnode1"
col8    = "Fnode2"
col9    = "SigmaMin"
col10   = "SigmaMax"

"3.2.3 - make each variable as a list/vector"
var ={col1:[], col2:[], col3:[], col4:[], col5:[], col6:[], col7:[], col8:[]
     ,col9:[],col10:[]}

"3.2.3 - take the values from each row in lineData and collect them into the correct variable"
for row in lineData:
  var[col1] .append(float(row[0])      )    #[-]    ElemNo
  var[col2] .append(float(row[1])      )    #[-]    Node1
  var[col3] .append(float(row[2])      )    #[-]    Node2
  var[col4] .append(float(row[3])      )    #[mm]   Length
  var[col5] .append(float(row[4])      )    #[mm^2] Area
  var[col6] .append(float(row[5])*10**6)    #[mm^4] Inertia
  var[col7] .append(float(row[6])      )    #[N]    Fnode1
  var[col8] .append(float(row[7])      )    #[N]    Fnode2
  var[col9] .append(float(row[8])      )    #[MPa]  SigmaMin
  var[col10].append(float(row[9])      )    #[MPa]  SigmaMax

As you see this is a rather annoying way of making each row into a variable. Any suggestions?


texts: Check if a file exists in a directory or parent

texts:
I want to check if a file exists in a given directory or in the parent one, so I wrote this code:

if (File.Exists(fileName) ||
    File.Exists(Directory.GetParent(Path.GetDirectoryName(fileName)).FullName +
        Path.DirectorySeperatorChar +
        Path.GetFileName(fileName)))

However, this seems quite odd to me and I wonder if there is a smarter approach to making this check. I'm not necessarily looking for a shorter approach, but a more understandable one.


texts: Safe pointer casting : static_cast or dynamic_cast

texts:
Context: I'm using the clone pattern for creating copies of polymorphic classes which may use virtual inheritance (I hope to get rid of the latter). So when calling foo.clone() I'm guaranteed to get the same type as foo even though the clone function might return only the base class (say ICloneable)

So I wrapped the clone call into a freestanding clone function which casts the pointer to the class passed and additionally puts it into a unique_ptr.

However the cast is a problem. dynamic_cast has too much overhead as I already know what type I'll get and static_cast doesn't work with base to derived casts on virtual bases.

So this is what I came up with:

template<typename T, typename U, typename = void>
struct is_static_castable : std::false_type
{};

template<typename T, typename U>
struct is_static_castable<T, U, decltype(void(static_cast<U>(std::declval<T>())))> : std::true_type
{};

template<typename To, typename From>
std::enable_if_t<is_static_castable<From*, To*>::value, To*>
safePtrCast(From* from)
{
    return static_cast<To*>(from);
}

template<typename To, typename From>
std::enable_if_t<!is_static_castable<From*, To*>::value, To*>
safePtrCast(From* from)
{
    return dynamic_cast<To*>(from);
}

template<class T>
auto clone(const T* obj)
{
    return std::unique_ptr<T>(safePtrCast<T>(obj->clone()));
}

Some notes:

C++14
void conversion in is_static_castable is required so MSVC 2015 does not fail for is_static_castable<int, int>, no idea why
safePtrCast can be enhanced with an assert(dynamic_cast... if wanted
return type enable_if used due to a bug in GCC 8: https://godbolt.org/z/6-C6CS

Any remarks on potential issues?
Possible cases I missed?
Improvements to make it more readable?

Otherwise feel free to use the code for own projects :)

The non-MSVC version of is_static_castable is slightly clearer:

template<typename T, typename U, typename = U>
struct is_static_castable : std::false_type
{};

template<typename T, typename U>
struct is_static_castable<T, U, decltype(static_cast<U>(std::declval<T>()))> : std::true_type
{};

Example for not using covariant return types:

struct ICloneable{ virtual ICloneable* clone() = 0; };
struct Middle: ICloneable{...};
struct Final: Middle{ Final* clone(); };

void foo(Middle* bar){
  auto barCloned = clone(bar); // Should be a unique_ptr<Middle>
}


texts: Optimizing large file reads with a custom line terminator in Python

texts:
I asked for help accomplishing this on StackExchange.
How to efficiently read a large file with a custom newline character using Python?

And ended up providing my own answer which is duplicated here.

class ChunkedFile(object):
    """
    Yields file in 100 megabyte chunks (by default).
    If lineterminator is provided reads through file in chunks but yields lines.
    """

    def __init__(self, file_to_process, lineterminator=None):
        self._file = file_to_process
        self._lineterminator = lineterminator

    def read(self, encoding="utf-8", chunk_size=None):
        one_hundred_megabytes = 100 * 1024
        chunk_size = chunk_size or one_hundred_megabytes

        with self._file.open(encoding=encoding) as f:
            chunk = ""
            while True:
                data = f.read(chunk_size)
                if not data:  # EOF
                    break

                chunk += data
                if self._lineterminator is None:
                    yield chunk
                    chunk = ""

                elif self._lineterminator in chunk:
                    lines = chunk.split(self._lineterminator)
                    chunk = "" if chunk.endswith(self._lineterminator) else lines.pop()
                    for line in lines:
                        if line:  # Don't return empty lines.
                            yield line

if __name__ == "__main__":
    longabstract_file = Path(__file__).parent / "longabstract_en.csv"
    file_chunk_reader = ChunkedFile(longabstract_file, lineterminator="\tl\n")
    for line in file_chunk_reader.read():
        print(line)

The code works but I'm interested in further optimizations and proper error handling. Nothing broke when I ran it on a few 1GB+ files so it's a start!

PS - I prefer pure Python 3 code (if relevant). Thanks.


texts: Generate Black and White confidence map masks for joints, same as OpenPose/Convolutional Pose Machines

texts:
Attached below is my code for generating the confidence maps for the joint locations, it is in the same vein as the maps generated for the paper Convolutional Pose Machines and OpenPose. I am wondering if anyone has input on how to speed up the process, as when I try to train my own variant of OpenPose or Convolutional Pose machines, my generator times out for batch sizes larger than one.... Just as a note so everyone knows the structure of the keypoint data, as I am training on MS COCO: for each image there can be N people and each person has 18 keypoints associated with them, and each keypoint comes with a list [y,x,o] where the x,y are self explanatory and o is an inclusion/occlusion indicator.

import numpy as np
import cv2
import os
def GeneratorMaskFiller(ImgPath,keys,string_ids,bs,mode="train",aug=None):
    os.chdir(ImgPath)
    while True:
        loop_count=0
        imgs=[]
        masks=[]
        for i in range(loop_count * bs,bs+loop_count * bs):
            img=cv2.imread(string_ids[i]+'.jpg')
            resized_img = cv2.resize(img,(224,224))
            imgs.append(resized_img)

            length = len(keys[i])
            num_people=int(length/18)
            sigma=7
            zeros=np.zeros((img.shape[0],img.shape[1],18,num_people))
            for part in range(18):
                for x in range(img.shape[0]):
                    for y in range(img.shape[1]):
                        for people in range(num_people):
                            zeros[x][y][part][people]=np.exp((-(pow(x-keys[loop_count][part+people*18][1],2)+pow(y-keys[loop_count][part+people*18][0],2)))/sigma)

            mask=np.zeros((img.shape[0],img.shape[1],18))
            for x in range(img.shape[0]):
                for y in range(img.shape[1]):
                    for part in range(18):
                        mask[x][y][part]=max(zeros[x,y,part,:])
            mask=cv2.resize(mask,(224,224))
            masks.append(mask)
        imgs = np.asarray(imgs)
        masks=np.asarray(masks)
        loop_count+=1
        if loop_count == len(keys):
            loop_count=0

        yield (imgs,masks)

Edits**:
For clarification the the argument keys is the a list of lists, where each element of the list corresponds to the keypoints for each image, so say there are three individuals in one image then there are 54 elements in that list where each element is a list of three elements. Out of the 18 masks each mask corresponds to a specific joint and will have disks centered at the true joint location for dependent on the number of people in the image and if the joints are visible. I am curious if there is a way for me to remove the multiple for loops I currently have in my code to generate these ground truth confident maps.


texts: Number of capture groups in a regular expression in php

texts:
I am trying to find the number of capture groups for a regular expression using this PHP function.

/**
 * Finds the number of groups in a regular expression
 * @param $regexPatten string The regular expression
 * @return int Returns the number of groups inside the regular expression
 */
public static function numOfGroups($regexPatten)
{
    $regexPatten = str_replace('\\\\', "", $regexPatten); // remove all escaped backslashes
    $regexPatten = str_replace('\\(', "", $regexPatten); // remove all escaped open parentheses
    $regexPatten = str_replace('(?:', "", $regexPatten); // remove all none capture groups

    return substr_count($regexPatten, "("); // count the remaining opening parentheses
}

And here is my test:

var_dump(Parser::numOfGroups("(test)")); // 1  --  will match: test
var_dump(Parser::numOfGroups("\((test)\)")); // 1  --  will match: (test)
var_dump(Parser::numOfGroups("\\\\\((test)\\\\(\d+)\)")); // 2  --  plain regex: \\\((test)\\(\d+)\)  --  will match: \(test\343)
var_dump(Parser::numOfGroups("((?:test(?: )?)+)")); // 1  --  will match: test test

Is there any use cases I have forgotten?


texts:
I want to know about smart pointers in C++11, so I started to write my own linked list implementation:

#include <iostream>
#include <memory>

template<typename T>
struct link
{
    T data;
    std::shared_ptr<link> next;

    link(T value) : data(value) {}
    void add_to_end(T value)
    {
        if (next)
            next->add_to_end(value);
        else
            next.reset(new link(value));
    }

};

template<typename T>
class linked_list
{
public:
    linked_list() : head(nullptr) {};
    ~linked_list() {};

    void push(T elem);
    void show(void);
    void reverse(void);
private:
    std::shared_ptr<link<T>> head;
};

template<typename T>
void linked_list<T>::push(T elem)
{
    if (head == nullptr)
        head.reset(new link<T>(elem));
    else
        head->add_to_end(elem);
}

template<typename T>
void linked_list<T>::reverse(void)
{
    std::shared_ptr<link<T>> prev;
    std::shared_ptr<link<T>> next;

    if (head == nullptr) return;

    while (head->next)
    {
        next = head->next;
        head->next = prev;
        prev = head;
        head = next;
    }
    head->next = prev;
}

template<typename T>
void linked_list<T>::show(void)
{
    std::shared_ptr<link<T>> current(head);
    while (current)
    {
        std::cout << current->data << std::endl;
        current = current->next;
    }
}

int main(int argc, char *argv[])
{
    linked_list<int> list;

    list.push(1);
    list.push(2);
    list.push(3);

    list.show();
    list.reverse();
    list.show();

    return 0;
}

I don't like to use shared pointers because they are used when multiple ownership is possible. But in linked list every node owns only the next one node. So I want to use unique_ptr. How can I use them? Unique pointers don't allow assignment which I use in my code.
I perform adding element into the end of list using link::add_to_end call. It looks not very good. How can I improve this code? What changes should I do if I want to write my push_front method to add into the head?
How else can I improve my code? What other problems does it have?


texts:
This is a class called Board which handles the tracking and checking of the state of the game. self.board is a dict of coordinate: state pairs, for e.g. (0,1): 'x'.

I could have hardcoded the checking lists in but decided to be adventurous and learn a bit of itertools.

The complete program is about 130 lines of code and I somehow managed to cram an ASCII board using a coordinate printer thingamajig in there (not included in this sample).

This is the code of a Pythoner 4 months into learning his first language. I seem to be very concerned about documentation, though I may just be in love with doctests.

class Board(object):
    """
    A tictactoe board using coordinates.

    Coordinates start at (0,0) in the top left.

    >>> myboard = Board()

    >>> myboard.set((0,1), 'x')
    >>> myboard.set((0,1), 'foo')
    Traceback (most recent call last):
        ...
    ValueError: state must be one of 'x', 'o', or ' '
    >>> myboard.set((7,1), 'o')
    Traceback (most recent call last):
        ...
    ValueError: coord does not exist

    >>> myboard.get((0,1))
    'x'
    >>> myboard.get('banana')
    Traceback (most recent call last):
        ...
    ValueError: coord does not exist

    >>> myboard.set((0,0), 'x')
    >>> myboard.has_row()
    []
    >>> myboard.set((0,2), 'x')
    >>> myboard.has_row()
    ['x']
    """

    def __init__(self):
        self.board = {i: " " for i in itertools.product((0,1,2), repeat=2)}

    def set(self, coord, state):
        """
        Set a space on the board to `state`.

        For e.g.: set((0,1), 'x')
        """
        if state not in ('x', 'o', ' '):
            raise ValueError("state must be one of 'x', 'o', or ' '")
        elif coord not in self.board.keys():
            raise ValueError("coord does not exist")
        else:
            self.board[coord] = state

    def get(self, coord):
        """
        Get the state of the space at `coord`.
        """
        try:
            return self.board[coord]
        except KeyError:
            raise ValueError("coord does not exist")

    def filled(self):
        """
        Return amount of spaces filled.
        """
        f = 0

        for v in self.board.itervalues():
            if v != ' ':
                f += 1

        return f

    def has_row(self):
        """
        Return a list of players who have a row of three.
        """
        across = [[i for i in itertools.product([0,1,2], [n])] for n in xrange(3)]
        down = [[(b, a) for a, b in i] for i in across]
        diag = [
            [(0,0), (1,1), (2,2)],
            [(0,2), (1,1), (2,0)],
        ]

        results = []

        for row in itertools.chain(across, down, diag):
            values = [self.board[c] for c in row]

            if values == ['x', 'x', 'x']:
                results.append('x')
            if values == ['o', 'o', 'o']:
                results.append('o')

        return results


texts:
I work with an embedded target that contains a list of commands and registers that may change from one device to another. So I need to build my commands list from metadata received from that particular target.

Unfortunately, the communication with the target is slow and the amount of commands is high. So I cannot build the full command's list at the beginning, but only when somebody requests it.

Of course, the list of commands should not be modifiable (by mistake), by the user which I assume is dumb. So I would like to prevent the instance to be easily modifiable in IPython.

For example:

device = Device()
device.commands.<tab>               # the user see all the available commands
device.commands.execute = 'oops'    # I want to prevent this to happen
device.commands['execute'] = 'oops' # Neither this.

So I wrote this design pattern:

import time

# The two following functions are the ones I use to communicate
# with my target.
def get_item_names():
    return ['item%d' % i for i in range(100000)]

def fetch_item(item): # Time consuming function
    time.sleep(0.1)
    return item

# The dictionary that is populated on demand.
class Foo(dict):
    __locked = False
    def __init__(self):
        # Populate elements with None elements.
        # This is required to be able to see the available commands
        # in IPython with the auto-completion turned on.
        for item in get_item_names():
            default = None
            self[item] = default

        # This is a very ugly workaround. With cProfiler, I can see
        # the addition of __setattr__ is very costy.
        self.__locked = True

    # The item is fetched only on demand
    def __getitem__(self, item):
        if item in self and super(Foo, self).__getitem__(item) == None:
            fetched = fetch_item(item)
            super(Foo, self).__setitem__(item, fetched)
            return fetched
        else:
            return super(Foo, self).__getitem__(item)

    @property
    def __members__(self):
        return self.keys()

    def __getattr__(self, item):
        return self[item]

    def __setattr__(self, key, value):
        if self.__locked:
            print('Not possible')
        else:
            super(Foo, self).__setattr__(key, value)

    def __setitem__(self, key, value):
        if self.__locked:
            print('Not possible')
        else:
            super(Foo, self).__setitem__(key, value)

Is that pattern good and what can I do to improve the bad performances with the lock mechanism? I naively tried to add setattr(self, '__setattr__', newsetattr) to __init__ but it does not work.


texts: Method for parsing floats and adding totals

texts:
My intention is to create a nice DRY method (add) which will take care of parsing floats and adding totals internally and will be called by other methods.

I feel like I'm jumping through unnecessary complex hoops here. Can anyone help me out?

PS: the intention is to be able to specify different objects with add, so if I had a label object called 'food' with a credit property I could create a function called addFoodCredit(amount) which would call add( amount, 'credit', 'labels', 'food').

The full code can be seen here.

var dateObject = function() {
    var totals = {
        totalDebit: 0,
        totalCredit: 0,
        labels: {}
   }

    var add = function add( amount ) {
        var args = Array.prototype.slice.call(arguments)
        var objectReference = totals;
        var floatAmount = parseFloat (args.shift());
        var objectKey = args.shift();
        while(args.length > 0) {
          objectReference = objectReference[args.shift()];
        }
        var currentTotal = parseFloat( objectReference[objectKey] );
        objectReference[objectKey] = currentTotal + floatAmount;
        console.log(objectReference, objectKey);
        console.log(totals.totalDebit)
    };

    this.addCredit = function addCredit( amount ) {
        add( amount, 'totalCredit' );
    };

    this.addDebit = function addDebit ( amount ) {
        add( amount, 'totalDebit');
    };

    this.addLabel = function ( label, amount, type ) {
        var labelName = label + '-' + type;
        if ( ! totals.labels.labelName ) {
            totals.labels[labelName] = 0;
        }

        add(amount, labelName, 'labels')
    }

  this.print = function() {console.log(totals)};

};

var x = new dateObject();
x.addCredit(15);
x.addCredit(21);
x.addDebit(12.42);
x.addDebit(122);
x.addLabel('food', 20, 'dr')
x.print();


texts:
I've written a generic data adapter that can make use of a cache, for use in a data access layer. It presents an interface allowing CRUD operations, as well as retrieving all objects of a certain type.

IEntity.cs:

using System;

namespace GenericDataAdapter
{
    public interface IEntity
    {
        Guid Id { get; set; }
    }
}

IDataAdapter.cs:

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

namespace GenericDataAdapter
{
    public interface IDataAdapter<T> where T : IEntity
    {
        Task<IEnumerable<T>> ReadAllAsync();
        Task<(bool, T)> ReadAsync(Guid id);    // bool indicates whether entity was present in data source
        Task SaveAsync(T newData);  // update if present, create if not present
        Task DeleteAsync(Guid id);
    }
}

CacheDataAdapter.cs:

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

namespace GenericDataAdapter
{
    public class CacheDataAdapter<T> : IDataAdapter<T> where T : IEntity
    {
        private IDataAdapter<T> PrimaryDataSource;
        private IDataAdapter<T> Cache;

        public CacheDataAdapter(IDataAdapter<T> primaryDataSource, IDataAdapter<T> cache)
        {
            PrimaryDataSource = primaryDataSource;
            Cache = cache;
        }

        public Task<IEnumerable<T>> ReadAllAsync()
        {
            return PrimaryDataSource.ReadAllAsync();
        }

        // can potentially return stale data, due to SaveAsync()/DeleteAsync() not being atomic
        public async Task<(bool, T)> ReadAsync(Guid id)
        {
            var (presentInCache, cacheData) = await Cache.ReadAsync(id);
            if (presentInCache)
            {
                return (true, cacheData);
            }

            var (presentInPrimary, primaryData) = await PrimaryDataSource.ReadAsync(id);
            if (presentInPrimary)
            {
                await Cache.SaveAsync(primaryData);
                return (true, primaryData);
            }
            else
            {
                return (false, default(T));
            }
        }

        public async Task SaveAsync(T newData)
        {
            await Cache.SaveAsync(newData);
            await PrimaryDataSource.SaveAsync(newData);
        }

        public async Task DeleteAsync(Guid id)
        {
            await Cache.DeleteAsync(id);
            await PrimaryDataSource.DeleteAsync(id);
        }
    }
}

There are two points I'd like feedback on, though all comments are welcome:

In CacheDataAdapter.ReadAllAsync(), should I use await? It doesn't seem like I should, since I'm just passing through the return value of PrimaryDataSource.ReadAllAsync(), but I'm not sure.
I'm not sure whether unifying the create and update operations into SaveAsync() is a good idea; it puts the responsibility for fully initializing objects on the application. That's why I'm using GUIDs as the identifier, so the application can generate unique IDs without having to consult the database first.


texts:
What I want to do:

Let users add data to an array through an input field and add button.

HTML:

<input type="text" id="input">
<button type="button" id="btnAdd">Add Number</button>

JS:

var arrayList = [];

$(document).ready(function() {

    $('#btnAdd').on('click', mkArray);

    $('#outputBox').on('click', 'span', deleteNum);

});

Display the array to the user.

function mkArray(event) {

    event.preventDefault();

    var numberAdd = $('#input').val();

    arrayList.push(numberAdd);

    $('#outputBox').append(' ' + numberAdd + '');

}

If the user clicks on the data, confirm deletion and then delete the item and refresh the array and display.

function deleteNum() {

    var confirmation = confirm('Are you sure you want to delete?');

    var numberIndex = $(this).index();

        if (numberIndex > -1) {

        arrayList.splice(numberIndex, 1);

        };

    $(this).remove();

};

JS FIDDLE

Question

Any potential pitfalls with this way of modifying an array?


texts:
I'm using this class so that objects can find other objects that are near them.  Each object has a position and radius. Objects are added to the Grid. If they move then they call update with their new position.  An object can call retrieve to find which objects are around it. How can I optimize it, specifically the retrieve function?

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.Arrays;

public class Grid {

    private Map<Integer, Set<Obj>> objects = new HashMap<>();
    private Set<Obj> retrievedObjects = new HashSet<>();
    float size;
    int divisions;

    public Grid(float size, int divisions) {
        this.size = size;
        this.divisions = divisions;
    }

    public void update(Obj obj) {
        if (!obj.grids.equals(getGridsObjIsIn(obj.position, obj.radius))) {
            remove(obj);
            insert(obj);
        }
    }

    public void insert(Obj obj) {
        obj.grids = getGridsObjIsIn(obj.position, obj.radius);

        for (Integer grid : obj.grids) {
            if (objects.containsKey(grid)) {
                objects.get(grid).add(obj);
            } else {
                objects.put(grid, new HashSet<Obj>(Arrays.asList(obj)));
            }
        }
    }

    public void remove(Obj obj) {
        for (Integer grid : obj.grids) {
            objects.get(grid).remove(obj);
        }
        obj.grids.clear();
    }

    public Set<Obj> retrieve(Vector2 pos, float radius) {
        retrievedObjects.clear();
        Set<Integer> grids = getGridsObjIsIn(pos, radius);

        for (Integer grid : grids) {
            if (objects.containsKey(grid)) {
                retrievedObjects.addAll(objects.get(grid));
            }
        }

        return retrievedObjects;
    }

    private Set<Integer> getGridsObjIsIn(Vector2 pos, float radius) {
        Set<Integer> grids = new HashSet<>();

        int[] min = positionToGrid(pos.x - radius, pos.y - radius);
        int[] max = positionToGrid(pos.x + radius, pos.y + radius);

        for (int x = min[0]; x <= max[0]; x++) {
            for (int y = min[1]; y <= max[1]; y++) {
                grids.add(x + y * divisions * divisions);
            }
        }

        return grids;
    }

    private int[] positionToGrid(float x, float y) {
        return new int[]{Math.round(divisions / size * x), Math.round(divisions / size * y)};
    }
}


texts:
I'm going to start small here because I actually have several questions but I'll go one at a time.

In the app I am making to better learn Java/Android/SQL/OOP, I have a page where a user can define Places (e.g. "New York City", "Seattle", etc). You could add made-up stuff if you wanted, too, doesn't matter. The user can perform basic CRUD operations on these Places.

Each Place also has a PlaceCategory, which is also user-defined elsewhere in the app in a separate list. So maybe I associate NYC and Boston with "The Northeast" and so if I click the filter dropdown and select "The Northeast," then NYC and Boston remain and the rest disappear (until I remove the filter again).

This is my SQL for the PlaceCategory table:

private static final String STRING_CREATE_TABLE_PLACE_CATEGORIES =
        "CREATE TABLE PLACE_CATEGORIES ("
                + "ID INTEGER PRIMARY KEY AUTOINCREMENT, "
                + "CATEGORY_NAME TEXT UNIQUE NOT NULL)";

And for the object:

public class PlaceCategory implements Comparable<PlaceCategory> {
    private long mId;
    private String mName;

    public PlaceCategory() {
        mId = -1;
        mName = "";
    }

    public PlaceCategory(long id, String name) {
        mId = id;
        mName = name;
    }

    public long getId() {
        return mId;
    }

    public void setId(long id) {
        mId = id;
    }

    public String getName() {
        return mName;
    }

    public void setName(String name) {
        mName = name;
    }

    @Override
    public int compareTo(PlaceCategory another) {
        return mName.compareTo(another.getName());
    }
}

And now for Places:

private static final String STRING_CREATE_TABLE_PLACES =
        "CREATE TABLE PLACES ("
                + "ID INTEGER PRIMARY KEY AUTOINCREMENT, "
                + "PLACE_CATEGORY_ID INTEGER NOT NULL, "
                + "PLACE_NAME TEXT NOT NULL, "
                + "PLACE_DESC TEXT NOT NULL, "
                + "FOREIGN KEY("
                    + "PLACE_CATEGORY_ID) REFERENCES "
                    + "PLACE_CATEGORIES(ID) ON DELETE CASCADE, "
                + "UNIQUE("
                    + "PLACE_CATEGORY_ID,"
                    + "PLACE_NAME))";

And the object:

public class Place implements Comparable<Place>{
    private long mId;
    private long mCategoryId;
    private String mName;
    private String mDesc;

    public Place() {
        mId = -1;
        mCategoryId = -1;
        mName = "";
        mDesc = "";
    }

    public Place(long id, long categoryId, String name, String desc) {
        mId = id;
        mCategoryId = categoryId;
        mName = name;
        mDesc = desc;
    }

    public long getId() {
        return mId;
    }

    public void setId(long id) {
        mId = id;
    }

    public long getCategoryId() {
        return mCategoryId;
    }

    public void setCategoryId(long categoryId) {
        mCategoryId = categoryId;
    }

    public String getName() {
        return mName;
    }

    public void setName(String name) {
        mName = name;
    }

    public String getDesc() {
        return mDesc;
    }

    public void setDesc(String desc) {
        mDesc = desc;
    }

    @Override
    public int compareTo(Place another) {
        return mName.compareTo(another.getName());
    }
}

My questions:

Should I be using long or Long for the ids in general? I used long because I don't think I need the null-ability of Long but I am unsure what the accepted practice is here.
Should I be storing the Category as an object in the Place, as opposed to an id like I am currently doing? My concern with storing only the id is that I would have to query the database for the category details whenever I wanted more detail. I don't know if this is considered a good idea. On the other hand, it is easier to query/generate Places when their members are primitive datatypes that can be ripped straight out of the table.
Are the ways my tables set up normalized properly? Do they make sense?
Anything else that stands out?


texts:
Any suggestions on improvement are welcome.

(ns cina.prime-circular)

(declare least-prime-divisor-from-primes
         least-prime-divisor
         prime
         primes)

(defn least-prime-divisor-from-primes
  "Find the least prime divisor of an integer n. Instead of checking every integer less than n,
  use the pool of known primes instead."
  [primes n]
  (loop [[p & ps] primes
         n n]
    (cond
      (= 0 (mod n p)) p
      (> (Math/pow p 2) n) n
      :else (recur ps n))))

(defn least-prime-divisor
  [n]
  (least-prime-divisor-from-primes primes n))

(defn prime
  "If n's least prime divisor is itself, then it must be a prime."
  [n]
  (cond
    (< n 1) (throw (Exception. "Positive integer required."))
    (= n 1) false
    :else (= n (least-prime-divisor n))))

;; A lazy sequence of primes
#_(time (last (take-while #(< % 100000) primes)))
(def primes (lazy-seq
              (cons 2 (filter prime (iterate inc 3)))))


texts: Regex to parse horizontal rules in Markdown

texts:
I'm the current maintainer of Showdownjs, a markdown parser off which PageDown (stackexchange's markdown parser) is based on.

Showdown uses the following regex to parse horizontal rules:

/^( ?(-|\*|_) ?){3,}[ \t]*$/gm

This works fine for most cases. However, the following input:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - abc

makes the library painfully slow (takes about 10 seconds on nodeJS and longer in browsers). The more dashes you add, the slower it gets.

In fact, if you copy the input above and paste it here on stackexchange, the page will freeze. (stackexchange uses a similar regex to parse <hr>)

How can I make it faster?


texts: Generalized Project Euler #4: Largest palindrome from product of two n-digit numbers in Python

texts:
This solves Project Euler 4: Largest palindrome product using Python (not limited to 3 digit numbers). I need suggestions for improvements to either the Python code or the math/algorithm since time of execution increases exponentially as number of digits in multipliers increase.

A palindromic number reads the same both ways. The largest palindrome made from >the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.

Here, I am trying to generalise the problem for n-digit numbers:
import sys
print(sys.version)

'''
A palindromic number reads the same both ways.
The largest palindrome made from the product of two 2-digit numbers is 9009    = 91 × 99.
This program intends to find the largest palindrome made from the product of    two n-digit numbers.
'''

digits_str = input("Enter no. of digits in multipliers : ")
digits = int(digits_str)

min_plier = (10 ** (digits-1))   # Minimum n-digit   number for eg. if digits = 3, min_plier = 100
max_plier = int(("9" * (digits+1))[:digits]);   # Maximum n-digit number for eg. if digits = 3, max_plier = 999

# Calculate product and get palindrome
pallindromes = []
for z in range (max_plier, min_plier , -1):
    max_plier = z          # To avoide repetitive calcualtions.

    for x in range(max_plier, min_plier, -1):
        global pallindromes
        product = z * x

        # Check if product obtained is palindrome and is greater than previously obtained palindrome.
        if (str(product) == str(product)[::-1]) :
            pallindromes.append(product)

print("Largest palindrome is : " + str(max(pallindromes)))

Here's the time required for execution as the number of digits increase:

No. of digits : 2, Largest palindrome : 9009, Time required for execution : 1.403140s
No. of digits : 3, Largest palindrome : 906609, Time required for execution : 1.649165s
No. of digits : 4, Largest palindrome : 99000099, Time required for execution : 39.202920s
No. of digits : 5, Largest palindrome : 9966006699, Time required for execution :  1hr 3min 54.552400s


texts:
I wrote code for determining the push button state whether it is long pressed or not. This function is called by timer interrupt routine every 1ms.

But it seems really dumb. How can I make it shorter and more efficient according to both readability and professional rules? What should I add or change to get double Tap pressing information with this  code?

void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
    /*button pressed and count*/
    if(!HAL_GPIO_ReadPin(GPIOC, GPIO_PIN_13))
    {
        usTick++;
    }
    /*not pressed*/
    else
    {
        if( usTick > 1000){
            ButtonState.PressedState = LongPressed;
            HAL_GPIO_TogglePin(GPIOA,GPIO_PIN_5);
            usTick = 0;
        }
        else if( usTick >350){
            ButtonState.PressedState = ShortPressed;
            HAL_GPIO_TogglePin(GPIOA,GPIO_PIN_5);
            usTick = 0;
        }
        usTick = 0;
    }
}


texts:
Define a procedure square-tree analogous to the
  square-list procedure of exercise
  2.21. That is, square-list should behave as follows:

(square-tree  (list 1
        (list 2 (list 3 4) 5)
        (list 6 7))) (1 (4 (9 16) 25) (36 49))

  Define square-tree both directly
  (i.e., without using any higher-order
  procedures) and also by using map and
  recursion.

I wrote this solution.  What do you think?

(define (square x) (* x x))

(define (square-tree tree)
  (cond ((null? tree) null)
        ((pair? tree)
         (cons (square-tree (car tree))
               (square-tree (cdr tree))))
        (else (square tree))))

(define (map-square-tree tree)
  (map (lambda (subtree)
         (if (pair? subtree)
             (cons (square-tree (car subtree))
                   (square-tree (cdr subtree)))
             (square subtree)))
       tree))

(define a (list 1 1 (list (list 2 3) 1 2)))

EDIT: This is a much better solution for map-square-tree.

(define (square x) (* x x))

(define (square-tree tree)
  (cond ((null? tree) null)
        ((pair? tree)
         (cons (square-tree (car tree))
               (square-tree (cdr tree))))
        (else (square tree))))

(define (map-square-tree tree)
  (map (lambda (subtree)
         ((if (pair? subtree) map-square-tree square) subtree))
       tree))

(define a (list 1 1 (list (list 2 3) 1 2)))


texts:
I've decided to try and start programming using Object-Oriented-Programming, so I built a small terrain generator that could be done using something as simple as this:

import random
for _ in range(1000):
    print random.choice('*#~o'),

Instead, I decided to have a go at OOP and made it like this instead:

# Terrain generator
from random import choice
from time import sleep

# Class containg world attr.
class Attr(object):
    def __init__(self):
        self.TILES = '#*~o'
        self.WORLD_SIZE = 1000
        self.Y_LENGTH = 1000
        self.X_LENGTH = 1000

# Generator class
class Generator(object):
    def __init__(self):
        self.world = []
        self.attr = Attr()

    # Create an empty row
    def create_row(self):
        for _ in range(self.attr.X_LENGTH):
            self.world.append(choice(self.attr.TILES))

# Main generator class
class MainGen(object):
    def __init__(self):
        self.gen = Generator()
        self.attr = Attr()

    # Create the world
    def create_world(self):
        for _ in range(self.attr.WORLD_SIZE):
            self.gen.create_row()

    # Render the world
    def render_world(self):
        for tile in self.gen.world:
            print tile,
            sleep(0.05)

# Main game class
class Game(object):
    def __init__(self):
        self.main_gen = MainGen()

    # Run the functions
    def run(self):
        self.main_gen.create_world()
        self.main_gen.render_world()

# Start the program
if __name__ == "__main__":
    game = Game()
    game.run()

All I'm really looking for are these things:

What OOP mistakes did I make?
What general mistakes did I make?
How can I improve in general?


texts:
"""
Provides a way to caculate the area of an arbitrary
n-sided irregular polygon.
"""
import doctest
import math

def heron(a,b,c):
    """
    Uses the heron formula to calculate the area
    of the triangle where `a`,`b` and `c` are the side
    lengths.

    >>> heron(3, 4, 5)
    6.0
    >>> heron(7, 10, 5).__round__(2)
    16.25
    """
    s = (a + b + c) / 2
    return math.sqrt(s * (s - a) * (s - b) * (s - c))

def pytagoras(a, b):
    """
    Given the cathets finds the hypotenusas.

    >>> pytagoras(3, 4)
    5.0
    """
    return math.sqrt(a**2 + b**2)

def distance(point_1, point_2):
    """
    Computes the cartesian distance between two points.

    >>> distance((0,0), (5,0))
    5.0
    """
    delta_x = point_1[0] - point_2[0]
    delta_y = point_1[1] - point_2[1]
    return pytagoras(delta_x, delta_y)

def triangle_area(triangle):
    """
    Wraps `heron` by allowing points inputs instead
    of sides lengths inputs.

    >>> triangle_area([(0,0), (0,3), (4,0)])
    6.0
    """
    side_1 = distance(triangle[0], triangle[1])
    side_2 = distance(triangle[1], triangle[2])
    side_3 = distance(triangle[2], triangle[0])
    return heron(side_1, side_2, side_3)

def triplets(list_):
    """
    Yields items from a list in groups of 3.

    >>> list(triplets(range(6)))
    [(0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5)]
    """
    for index, item in enumerate(list_[:-2]):
        yield item, list_[index + 1], list_[index + 2]

def polygon_area(polygon):
    """
    Calculates the area of an n-sided polygon by
    decomposing it into triangles. Input must be
    a list of points.

    >>> polygon_area([(0,0), (0,5), (3,0), (3, 5)])
    15.0
    """
    return sum(triangle_area(triangle)
                   for triangle in triplets(polygon))

def _main():
    doctest.testmod()

if __name__ == "__main__":
    _main()


texts: Copy Cell on Worksheet_Change event if some criteria is met

texts:
This code is working fine, but it looks awful (yes, I am a rookie on this thing). How can I improve it to look better?

Private Sub Worksheet_Change(ByVal Target As Range)

'Conditional Formatting
Application.ScreenUpdating = False

If Target.Column > 6 And Target.Column < 8 And (Target.Value = "G" Or Target.Value = "Y" Or Target.Value = "R" Or Target.Value = "g" Or Target.Value = "y" Or Target.Value = "r") Then
Sheets("Pending").Cells(1, 1).Copy

Call ChangeG
End If

If Target.Column > 4 And Target.Column < 6 And (Target.Value = "High" Or Target.Value = "Medium" Or Target.Value = "Low" Or Target.Value = "high" Or Target.Value = "medium" Or Target.Value = "low") Then
Sheets("Pending").Cells(1, 1).Copy

Call ChangeE
End If

Application.ScreenUpdating = True

End Sub