texts: A text-templating system similar to PHP...but with Clojure

texts:
I wrote a simple text-templating/processing system which resembles PHP, except that it works with Clojure. The main goal was to provide an easy way to use Clojure PHP-style for small files.

This is a usage example, the following file

<?clj
        (def theName "Soonog")

        (defn replaceAs
                [input]
                (clojure.string/replace input "a" "X")
        )
?>

Hello <% theName %>, this is a simple template which should allow
you to <% (replaceAs "see the basics how this might work some day") %>.

should output (here are two newlines at the start missing)

Hello Soonog, this is a simple template which should allow
you to see the bXsics how this might work some dXy.

A short info on how it works:

Accepts files as arguments

If no arguments are provided or the argument is "-" it will read from stdin

Outputs to stdout
Uses regular expressions to split/process the text
Everything in <?clj ... ?> is evaluated with load-string
Everything in <% ... %> is wrapped in (echo ... ) and then treated like above

A few things I'm unsure about:

The treatment of static variables (f.e. tag-start)
The style itself
Using regular expressions to parse files
load-strings will load it into the current context, so all files passed in share the same context...this is by design (for now) so that you can "include" files. Though, having a function that uses a separate context might be interesting if this is used as library.

And here's the code:

(ns closeddoor.core
    (:gen-class :main true))

(require 'clojure.string)

(def tag-start
    "The long/normal start tag."
    "<\\?clj")
(def tag-end
    "The long/normal end tag."
    "(\\?>|\\Z)")

(def echo-start
    "The short/echo start tag."
    "<%")
(def echo-end
    "The short/echo end tag."
    "%>")

(def tag-pattern
    "The compiled pattern for the long/normal tags."
    (re-pattern (str tag-start "((?s:.+?))" tag-end)))
(def echo-pattern
    "The compiled pattern for the short/echo tags."
    (re-pattern (str echo-start "((?s:.+?))" echo-end)))

(defn- process-match
    "Processes the given match, and returns the output of
    the given match."
    [[match group]]

    ; Create a StringBuilder which we'll use for our content.
    (def buffer (StringBuilder.))

    (defn echo
        "A small helper function to allow to echo things."
        [string]
        (.append buffer string))

    ; Now load what the regex delivered to use.
    (load-string (str "(use 'closeddoor.core)" group))

    ; Return the buffer.
    ; We're replacing the $ with an escaped version because this output
    ; is directly passed into string/replace.
    (clojure.string/replace (.toString buffer) "$" "\\$"))

(defn- process-match-echo-wrapped
    "Process the given match, but wraps it first in the echo function."
    [[match group]]
    (process-match [match (str "(echo " group ")")]))

(defn parse
    "Parses the given input, processes the matches and returns the result.
    The long/normal tags are processed first, after that the short/echo tags.
    Order of appearance does not matter, all normal tags are processed first."
    [input]
    (clojure.string/replace
        (clojure.string/replace
            input
            tag-pattern
            process-match)
        echo-pattern
        process-match-echo-wrapped))

(defn process
    "Processes the given source, which means that it reads everything from
    the source with slurp, runs it through parse and spits it out into out.

    So (process input *out*) is basically shorthand for (spit *out* (parse input))."
    [source out]
    (spit out (parse (slurp source))))

(defn -main
    "The main function which does everything."
    [& args]
    (if (empty? args)
        (process *in* *out*)
        (doseq [arg args]
            (if (= arg "-")
                (process *in* *out*)
                (process arg *out*)))))


texts: Smallest prime factor of a large number (using BigInteger)

texts:
I'm working on a Project Euler problem and am trying to get the smallest prime factor of a BigInteger:

private static BigInteger smallestPrimeFactor( BigInteger n ){
    for( BigInteger i = new BigInteger("2"); n.compareTo(i) >= 0 ; i = i.add(BigInteger.ONE) ){
        while( n.mod(i) == BigInteger.ZERO )
            return i;
        }
    }
    return BigInteger.ZERO;
}

I have basically just made adjustments to a code snippet I found online. They had something with n = n.divide(i), which I believe was to make things prime, but I wanted to save time just getting the smallest. Is there a better/faster way to go about doing this?


texts:
This changes the application's volume through the Trackbar (1-100, 1% to 100%):

public static class NativeMethods
{
    //Winm WindowsSound
    [DllImport("winmm.dll")]
    internal static extern int waveOutGetVolume(IntPtr hwo, out uint dwVolume);
    [DllImport("winmm.dll")]
    internal static extern int waveOutSetVolume(IntPtr hwo, uint dwVolume);
}

private void trackBar1_Scroll(object sender, EventArgs e)
{
    uint CurrVol = ushort.MaxValue / 2;
    NativeMethods.waveOutGetVolume(IntPtr.Zero, out CurrVol);
    ushort CalcVol = (ushort)(CurrVol & 0x0000ffff);
    int NewVolume = ((ushort.MaxValue / 100) * trackBar1.Value);
    uint NewVolumeAllChannels = (((uint)NewVolume & 0x0000ffff) | ((uint)NewVolume << 16));
    NativeMethods.waveOutSetVolume(IntPtr.Zero, NewVolumeAllChannels);
    label1.Text = Convert.ToString("Volume: " + trackBar1.Value + "%");
}

Is it possible to make String.Format use multiple arguments/values?

For example:

 String Status = String.Format("Current Buffer: {0}", waveProvider.BufferedDuration.Milliseconds, TimesBufferClear) + " Clear: " + TimesBufferClear.ToString() + " Ping: " + PingReply + " Buffer: " + SendStream.BufferMilliseconds;

There, I would like to use it on everything, as they all work pretty much the same. But if I have to write String.Format every time, it will take up much more space.

Is this code okay, or can it be improved?


texts:
I think I'm on the right track, but ANY suggestions or critques are welcome.  The program just scrapes an HTML table and prints it to stdout.

import sys
from urllib2 import urlopen, URLError
from argparse import ArgumentParser
from bs4 import BeautifulSoup

def parse_arguments():
    """ Process command line arguments """
    parser = ArgumentParser(description='Grabs tables from html')
    parser.add_argument('-u', '--url', help='url to grab from',
                        required=True)
    args = parser.parse_args()
    return args

def parse_rows(rows):
    """ Get data from rows """
    results = []
    for row in rows:
        table_headers = row.find_all('th')
        if table_headers:
            results.append([headers.get_text() for headers in table_headers])

        table_data = row.find_all('td')
        if table_data:
            results.append([data.get_text() for data in table_data])
    return results

def main():
    # Get arguments
    args = parse_arguments()
    if args.url:
        url = args.url

    # Make soup
    try:
        resp = urlopen(url)
    except URLError as e:
        print 'An error occured fetching %s \n %s' % (url, e.reason)
        return 1
    soup = BeautifulSoup(resp.read())

    # Get table
    try:
        table = soup.find('table')
    except AttributeError as e:
        print 'No tables found, exiting'
        return 1

    # Get rows
    try:
        rows = table.find_all('tr')
    except AttributeError as e:
        print 'No table rows found, exiting'
        return 1

    # Get data
    table_data = parse_rows(rows)

    # Print data
    for i in table_data:
       print '\t'.join(i)

if __name__ == '__main__':
    status = main()
    sys.exit(status)


texts: Geocoder form with Google Maps autosuggest

texts:
Even though it's simple, I've spent quite a bit of time on it, learning as I go. Is there anyway I can make this code more efficient, more crossbrowser compatible or just generally better?

jsFiddle

<!-- Geocode -->
$(document).ready(function () {
    var GeoCoded = { done: false };
    autosuggest();
    $('#myform').on('submit', function (e) {
    if (GeoCoded.done) return true;

        e.preventDefault();
        var geocoder = new google.maps.Geocoder();
        var address = document.getElementById('location').value;

        $('#myform input[type="submit"]').attr('disabled', true);

        geocoder.geocode({
            'address': address
        },

        function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                var latLng = results[0].geometry.location;
                $('#lat').val(results[0].geometry.location.lat());
                $('#lng').val(results[0].geometry.location.lng());
                GeoCoded.done = true;
                $('#myform').submit();
            } else {
                console.log("Geocode failed: " + status);
                //enable the submit button
                $('#myform input[type="submit"]').attr('disabled', false);
            }

        });

    });

});

function autosuggest() {
        var input = document.getElementById('location');
        var options = {
            types: [],
        };
        var autocomplete = new google.maps.places.Autocomplete(input, options);
    }


texts:
I am writing a function to decode a string, which means performing a string transformation like 3e4f2e --> eeeffffee.

I have two versions of codes which are very similar but slightly different. In version1,

def decoding(s):
    res = []
    curr = 0
    curr_val = 0
    while curr < len(s):
        if not s[curr].isdigit():
            res.append(curr_val * s[curr])
            curr_val = 0
        else:
            curr_val = curr_val * 10 + int(s[curr])
        curr += 1
    return ''.join(res)

I keep in track of curr_val and keep accumulating the value until I see a non-digit string.

In version2, I keep in track of the first position of the digit string and slice the string just to represent the digit string.

def decoding(s):
    digit_start, res = 0, []
    curr = 0
    while curr < len(s):
        if not s[curr].isdigit():
            res.append(int(s[digit_start:curr]) * s[curr])
            digit_start = curr + 1
        curr += 1
    return ''.join(res)

I just keep in track of the right index and multiply the int of that string with the current non-digit string (e.g. 10a --> aaaaaaaaaa)

I wonder if the first version has a way better time complexity or if they have the same time complexity in big-O. I assumed that both of them are \$O(n)\$ where \$n\$ is the length of the input string, but I wonder if slicing inside a loop would significantly increase the time-complexity of the code.

Please note that this is an interview practice, so I care about time-complexity, not the real-world style.


texts: Tracking hours worked for the days of the week

texts:
I am working through a udemy course on Python, this is the first real program I've written. I am new to Python and to programming.

I'd like to replace the main function below with something more efficient and less repetitive but I'm not sure what or how. The most I could think to do is write a function for adding hours and call it under each day.

Most relevant code:

def main(day):

    if day == "Monday":
            print "Today is %s, How many hours would you like to add today?" % (day)
            hours = int(raw_input())
            DOTW['Monday'] = DOTW['Monday'] + hours
            print "Cool your hours for %s are %d" %(day, DOTW['Monday'])
            want = raw_input("Do you want to add more time? y/n \n > ")
            overtime()
            leave(want)

    if day == "Tuesday":
            print "Ah, Today is %s, How many hours have you worked?" %(day)
            hours = int(raw_input())
            DOTW['Tuesday'] = DOTW['Tuesday'] + hours
            print "alright, yours hours for %s are %d" %(day, DOTW['Tuesday'])
            want = raw_input("Do you want to add more time? y/n \n > ")
            overtime()
            leave(want)

    if day == "Wednesday":
            print "Ah, Today is %s, How many hours have you worked?" %(day)
            hours = int(raw_input())
            DOTW['Wednesday'] = DOTW['Wednesday'] + hours
            print "Cool for %s I've got %d hours" %(day, DOTW['Wednesday'])
            want = raw_input("Do you want to add more time? y/n \n > ")
            overtime()
            leave(want)

    if day == "Thursday":
            print "Ah, Today is %s, How many hours have you worked?" %(day)
            hours = int(raw_input())
            DOTW['Thursday'] = DOTW['Thursday'] + hours
            print "Your hours for %s are %d" %(day, DOTW['Thursday'])
            want = raw_input("Do you want to add more time? y/n \n > ")
            overtime()
            leave(want)

    if day == "Friday":
            print "FINALLY IT'S FRIDAY!!! How many hours have you worked?"
            hours = int(raw_input())
            DOTW['Friday'] = DOTW['Firday'] + hours
            print "Cool. for %s I've got %d hours" %(day, DOTW['Friday'])
            want = raw_input("Do you want to add more time? y/n \n > ")
            overtime()
            leave(want)

    if day == "Saturday":
            print "Ah, Today is %s, How many hours have you worked?" %(day)
            hours = int(raw_input())
            DOTW['Saturday'] = DOTW['Saturday'] + hours
            print "alright, yours hours for %s are %d" %(day, DOTW['Saturday'])
            want = raw_input("Do you want to add more time? y/n \n > ")
            overtime()
            leave(want)

    if day =="Sunday":
            print "Ah, Today is %s, How many hours have you worked?" %(day)
            hours = int(raw_input())
            DOTW['Sunday'] = DOTW['Sunday'] + hours
            print "Cool your hours for %s are %d" %(day, DOTW['Monday'])
            want = raw_input("Do you want to add more time? y/n \n > ")
            overtime()
            leave(want)

The entire program: http://pastebin.com/8hLVcGMr


texts: Classifying image by file extension within a PDF creator

texts:
To create a pdfDocument I am using following code which works as expected but do not want to use multiple if else.

Any patterns or any design strategies? It may  be a over do for the example , but will be useful.

string fileExtension = Path.GetExtension(fileName).ToLower();
string outPutPath = Path.GetDirectoryName(fileName) + "\\" + Path.GetFileNameWithoutExtension(fileName) + ".pdf";

Aspose.Pdf.Generator.Pdf pdfConverter = new Aspose.Pdf.Generator.Pdf();

Section pdfSection = pdfConverter.Sections.Add();

//Table pdfTable = new Table() { DefaultCellBorder=new Aspose.Pdf.Generator.BorderInfo((int)BorderSide.All,0.1F)};

//pdfSection.Paragraphs.Add(pdfTable);

Image sourceImage = new Image();
sourceImage.ImageInfo.File = fileName;

if (fileExtension == ".jpg" || fileExtension == ".jpeg")
{
    sourceImage.ImageInfo.ImageFileType = ImageFileType.Jpeg;
}
else if (fileExtension == ".bmp")
{
    sourceImage.ImageInfo.ImageFileType = ImageFileType.Bmp;
}
else if (fileExtension == ".gif")
{
    sourceImage.ImageInfo.ImageFileType = ImageFileType.Gif;
}
else if (fileExtension == ".png")
{
    sourceImage.ImageInfo.ImageFileType = ImageFileType.Png;
}
else if (fileExtension == ".tiff")
{
    sourceImage.ImageInfo.ImageFileType = ImageFileType.Tiff;
}

pdfSection.Paragraphs.Add(sourceImage);

pdfConverter.Save(outPutPath);


texts: Method that Saves user text messaging draft

texts:
I am working on saving the text messaging draft of a user. The flow currently works but I am looking to make this block of code easier to read and smaller. Could anyone help me achieve this?

if (!hasDraft) {
    /**
     * This will get triggered when there is no draft
     * and you create one therefore we need a refresh.
     */
    if (!TextUtils.isEmpty(enteredText)) {
        saveDraftAndRefreshList();
    } else {
        /**
         * This should be the happy case.
         * User has just sent a message so no need to refresh the list
         */
        sendMessage();
    }
 /**
  * This else will only be reached if there has been a draft
  **/
 } else {
     if (TextUtils.isEmpty(enteredText)) {
         /**
          * This will get reached if you had a draft but now removed the text.
          * Thus needing a refresh
          */
         removePreviousDraft();
    } else if (!TextUtils.isEmpty(enteredText)) {
        /**
         * This will get triggered if there was a draft and
         * now they decided to overwrite it.
         */
        overwritePreviousDraft();
    }
}


texts:
Question:Write an algorithm in C to do integer multiplication without using multiplication nor division operators.

Could I get a critique of the doMultiplication function? I know the rest of the code has some dumb stuff in it (like using scanf), but I'm looking for feedback on my multiplication implementation. Are there any cases it won't handle? Is there anything I could possibly have done to optimize it? And lastly, is there anything that would make it more readable?

#include <stdio.h>
#include <math.h>
/*
Write an algorithm/code in C to do integer multiplication  without using multiplication nor division operators.
 */
void main()
{
  int n;
  int m;
  int result;
  printf("Please enter numbers to multiplye\n");
  printf("First number\n");
  int multiple1 = getNumberFromUser();
  printf("\nSecond number\n");
  int multiple2 = getNumberFromUser();
  result = doMultiplication(multiple1,multiple2);
  printf("Result of multiplication = %d\n", result);
}

int getNumberFromUser()
{
  char arg1[10];
  int retry = 0;
  int multiple;
  while(retry == 0)
  {
    printf("Please enter a number:");
    scanf("%s", arg1);
    if(isNumericInput(arg1) != 0)
    {
      char * strEnd;
      multiple = strtol(arg1,&strEnd, 10);
      retry = 1;
    } else {
      printf("Bzzz wrong answer genius try a number \n");
    }
  }

  return multiple;

}

int isNumericInput(char arg[]){
  char * strEnd;
  int userInput = strtol(arg, &strEnd, 10);
  return userInput;
}

int doMultiplication(int n, int m)
{
  int result = 0;
  while(m != 0)
  {
    if((m & 1) != 0)
    {
      result = result + n;
    }
    n = n << 1;
    m = m >> 1;
  }
  return result;
}


texts: How can I avoid repeated code using lambdas?

texts:
I have a method which should accept a Function/Action and do something with that method (in my case I've added retry logic).

I'm wondering how I can remove the duplicated code (for loop, etc) from the last 2 methods. Is there any clever way to do this in C#?

public static class Retry {
    public static void Do(
    Type retryOnExceptionType,
    Action action,
    TimeSpan retryInterval =
    default (TimeSpan),
    int retryCount = 3) {
        if (retryInterval ==
        default (TimeSpan)) retryInterval = TimeSpan.FromSeconds(1);

        Do < object > (
        retryOnExceptionType, () = > {
            action();
            return null;
        }, retryInterval, retryCount);
    }

    public static T1 Do < T1, T2, T3 > (
    Type retryOnExceptionType,
    Func < T2, T3, T1 > action,
    T2 param1,
    T3 param2,
    TimeSpan retryInterval =
    default (TimeSpan),
    int retryCount = 3) {
        if (retryInterval ==
        default (TimeSpan)) retryInterval = TimeSpan.FromSeconds(1);

        var exceptions = new List < Exception > ();

        for (int retry = 0; retry < retryCount; retry++) {
            try {
                return action(param1, param2);
            } catch (Exception ex) {
                if (!retryOnExceptionType.IsInstanceOfType(ex)) throw;

                exceptions.Add(ex);
                Thread.Sleep(retryInterval);
            }
        }

        throw new AggregateException(exceptions);
    }

    public static T Do < T > (
    Type retryOnExceptionType,
    Func < T > action,
    TimeSpan retryInterval =
    default (TimeSpan),
    int retryCount = 3) {
        if (retryInterval ==
        default (TimeSpan)) retryInterval = TimeSpan.FromSeconds(1);

        var exceptions = new List < Exception > ();

        for (int retry = 0; retry < retryCount; retry++) {
            try {
                return action();
            } catch (Exception ex) {
                if (!retryOnExceptionType.IsInstanceOfType(ex)) throw;

                exceptions.Add(ex);
                Thread.Sleep(retryInterval);
            }
        }

        throw new AggregateException(exceptions);
    }
}


texts:
I have a project that reads spreadsheets as a rectangular list of lists (matrix) transforms the matrix and then writes it to another spreadsheet.  I want to be able to read from and write to multiple formats.  Consequentially, the program should double as spreadsheet conversion tool.

Here is an example of just copying one sheet to another:

def ConvertSheet(in_sheet, out_sheet)
    sheet_io = SheetIO()
    data_matrix = sheet_io.read_sheet(in_sheet)
    # different functions would operate on data_matrix before writing.
    sheet_io.write_sheet(out_sheet, modified_data)

Depending on what type of object in_sheet and out_sheet are determine how SheetIO writes it but as far as the client cares, that's SheetIO's problem.

The design I have implemented is an odd factory pattern.  It's primarily why I am asking for advice.

Abstract base class

This is pretty basic and would essentially be the interface in a proper factory pattern:

class ISheetIO(object):
    """ Abstract base class...
    """
    def read_sheet(self):
        raise NotImplementedError("read_sheet not implemented")

    def write_sheet(self):
        raise NotImplementedError("write_sheet not implemented")

Concrete Class

The only concrete base class I have implemented so far.  Note that it reads and writes sub-vectors as rows.  I am specifying that all Concrete classes operate that way.

Also note that I am allowing optional arguments, specifying the range to write them to.

class ExcelSheet(ISheetIO):

    def read_sheet(self, sheet, col_start=0, row_start=0, col_cnt=-1, row_cnt=-1):

        # TODO: Raise an error instead. Research which error to raise
        assert not sheet.ragged_rows

        if row_cnt < 0:
            row_cnt += sheet.nrows + 1
        if col_cnt < 0:
            col_cnt += sheet.ncols + 1

        return [sheet.row_values(r, col_start, row_start)
                for r in xrange(row_start, row_cnt + 1)]

    def write_sheet(self, data, sheet, col_start=0, row_start=0):
        for r, row, in enumerate(data):
            for c, el in enumerate(row):
                sheet.write(row_start + r, col_start + c, el)

# class CSVSheet(ISheetIO):
# class OpenXMLSheet(ISheetIO):

Wrapper Class

This is where things get hairy.  My understanding of the factory pattern is that this should be the factory at it would return a concrete class.  Instead the client instructs SheetIO to read or write and SheetIO gets and uses the concrete class itself through its own factory. The reason for composing the concrete class instead of returning it is, I am permitting the client to request the data with sub-lists as columns.  SheetIO encapsulates that state with read_by_row and remembers to transpose the data again when writing.

class SheetIO(ISheetIO):

    def __init__(self, read_by_row=True):
        self.by_row = read_by_row

    def _factory(self, sheet):

        sheet_type = type(sheet)

        if sheet_type is xlrd.sheet or sheet_type is xlwt.WorkSheet:
            return ExcelSheet()
        # elif CSV
        #    return CSVSheet()
        # elif OpenXML
        #    return OpenXMLSheet()
        else:
            raise TypeError("Unknown Sheet type or not a sheet")

    def read_sheet(self, sheet, **kwargs):
        data = self._factory(sheet).read_sheet(sheet, **kwargs)
        return self.orient_data(data)

    def write_sheet(self, data, sheet, **kwargs):
        oriented_data = self._orient_data(data)
        self._factory(sheet).write_sheet(sheet, oriented_data, **kwargs)

    def _orient_data(self, data):
        if self.by_row:
            return data
        else:
            return self._transpose(data)

    def _transpose(self, matrix):
        return zip(*matrix)


texts: Add Strings in-between index of ArrayList if not already exists

texts:
So as the title states, I am trying to add a specific Items to an ArrayList if they not already exist. So here is how the Array starts.

[a, b, c, d, e, f]

I have this items inside the ArrayList

and I'm gonna add some items after the item d if it doesn't exist already in a pattern.

[a, b, c, d, x, y, z, e, f]

I had a successful run of the items I have provided resulting with the output

[a, b, c, d, e, f]
Adding string x to index 3
Adding string y to index 4
Adding string z to index 5
[a, b, c, d, x, y, z, e, f]
String already exists x skipping...
String already exists y skipping...
String already exists z skipping...
[a, b, c, d, x, y, z, e, f]

here is the code that I have created to get this result

public static void addStringIfNotAlreadyExists(List<String> list, int index, String... strings) {
    for (String s : strings) {
        if (!list.get(index + 1).equals(s)) {
            System.out.println("Adding string " + s + " to index " + index);
            list.add(index + 1, s);
        } else {
            System.out.println("String already exists " + s + " skipping...");
        }
        index++;
    }
}

It's not the best code I have written but it works.

and here is how I call it for the test.

public static void main(String[] args) {
    List<String> list = new ArrayList<>();
    list.add("a");
    list.add("b");
    list.add("c");
    list.add("d");
    list.add("e");
    list.add("f");
    System.out.println(list);
    addStringIfNotAlreadyExists(list, 3, "x", "y", "z");
    System.out.println(list);
    addStringIfNotAlreadyExists(list, 3, "x", "y", "z");
    System.out.println(list);
}

What I am curious in if this code can fail in certain tests, Or how I can improve the code.


texts: Workflow and Design Feedback on an Add / Edit Form

texts:
I was looking for advice, feedback and information on best practices when designing ASP.NET Web Forms in a .NET web application.

Allow me to post a sample of how I currently do things. I am omitting the ASPX page as it only has 2 textboxes and a button. PersonEntity validates, loads, and saves in this example. Real-world would have a "Person" business object that saves, loads.

The Codebehind file of an "Add / Edit" page:

public partial class PersonAddUpdate : System.Web.UI.Page
{
    public int PersonId
    {
        get
        {
            int _personId = 0;
            if (Int32.TryParse(Request.QueryString["id"], out _personId))
            {
                return _personId;
            }
            else
            {
                return 0;
            }
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            if (PersonId != 0)
            {
                var person = GetPersonById(PersonId);

                if (person != null)
                {
                    BindFormToData(person);
                    ViewState.Add("PersonEntity", person);
                }
            }
        }
    }

    protected bool BindDataToForm(PersonEntity person)
    {
        person.FirstName = txtFirstName.Text;
        person.Lastname = txtLastName.Text;

        ViewState.Add("PersonEntity", person);

        // internal entity validation
        return person.Validate();
    }

    protected void BindFormToData(PersonEntity person)
    {
        txtFirstName.Text = person.FirstName;
        txtLastName.Text = person.Lastname;
    }

    protected PersonEntity GetPersonById(int personId)
    {
        PersonEntity person = new PersonEntity();
        return person.LoadById(personId);
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (!Page.IsValid)
        {
            return;
        }

        PersonEntity person;

        if (ViewState["PersonEntity"] == null)
        {
            person = new PersonEntity();
        }
        else
        {
            person = (PersonEntity)ViewState["PersonEntity"];
        }

        if (!BindDataToForm(person))
        {
            // failed entity validation
            return;
        }

        if (!person.Save())
        {
            // problem saving
            return;
        }
        else
        {
            Response.Redirect("PersonDetail.aspx?id=" + person.Id.ToString());
        }
    }
}

Workflow:

Page Load:
Get the id from querystring. If a problem arises, return 0. No records in the system have a "0" id. Try to load data. If there's data, set the form values and add it to viewstate.

On Save: Stop if page is invalid. Create an uninitialized PersonEntity. If viewstate contains an entity, then form binding (gets form values) routine does not need new PersonEntity. If viewstate is null, then we are a new record.

Call BindDataToForm which gets form field values and returns false if it fails internal entity validation. Attempt Save and continue if OK.

Questions:

I've been using this pattern for a while now. Do you see anything I can do to improve it? I was trying to find samples of complete forms that handle Add / Edit, but I was unable to find ones that worked as good as this with ORM-generated code.

Any comments, advice, ideas, or questions?

I hope the code is simple to read and understand.


texts:
I have been working my way through the problems in the book Cracking the Coding Interview.  The instructions were to maintain an animal shelter that operates on a first in, first out basis (i.e. it is a queue). People must adopt the "oldest" (based on arrival time) of all animals at the shelter, or if they would prefer a dog or a cat (and will receive the oldest animal of that type). They cannot choose which specific animal they would like.

AnimalShelter.java

package problem_2_9;

import java.util.LinkedList;
import java.util.NoSuchElementException;

public class AnimalShelter {

    public enum AnimalType{
        DOG, CAT
    }

    private int animalId;
    LinkedList<Integer> cats;
    LinkedList<Integer> dogs;

    public AnimalShelter(){
        cats = new LinkedList<Integer>();
        dogs = new LinkedList<Integer>();
    }

    public void enqueue(AnimalType type){
        switch(type){
        case DOG:
            dogs.add(animalId);
            animalId++;
            break;
        case CAT:
            cats.add(animalId);
            animalId++;
            break;
        }
    }
    public Integer dequeueCat(){
        if(cats.isEmpty()) throw new NoSuchElementException("There are no cats in the animal shelter.");
        return cats.pop();
    }

    public Integer dequeueDog(){
        if(dogs.isEmpty()) throw new NoSuchElementException("There are no dogs in the animal shelter");
        return dogs.pop();
    }

    public Integer dequeueAny(){
        if(dogs.isEmpty() && cats.isEmpty()) throw new NoSuchElementException("There are no animals in the animal shelter.");
        if(dogs.isEmpty()){
            return cats.pop();
        }
        else if(cats.isEmpty()){
            return dogs.pop();
        } else{
            if(cats.peek() < dogs.peek()){
                return cats.pop();
            }
            else{
                return dogs.pop();
            }
        }
    }
}

I've tested the AnimalShelter class using this code:

Main.java

package problem_2_9;

import problem_2_9.AnimalShelter.AnimalType;

    public class Main {

        public static void main(String[] args){
            // dogs = 0 2 4 6
            // cats = 1 3 5 7
            AnimalShelter shelter = new AnimalShelter();
            for(int i = 0; i < 4; i++){
                shelter.enqueue(AnimalType.DOG);
                shelter.enqueue(AnimalType.CAT);
            }

            for(int i = 0; i < 4; i++){
                System.out.println(shelter.dequeueCat());
                System.out.println(shelter.dequeueDog());
            }
        }
    }


texts: Transfer an array of unknown size from C to Python using Ctypes

texts:
I am new to Ctypes. I am writing a piece of code that brings an array of unknown size from C to Python using Ctypes. Unknown size here mean that Python initially doesn't know the size of the array. C code has the algorithm which creates the array.
Somehow after lot of trails, I managed to write code for that:

python code: sample.py

from ctypes import *
#import needed packages
import os

def main():
    a = 6;
    lib_path = os.path.join(os.path.dirname(__file__),  'Debug','{}.dll'.format("sum"))
    #print(lib_path)
    try:
        lib = cdll.LoadLibrary(lib_path)
    except Exception as e:
        raise RuntimeError("Could not   library with this path: {}. {}".format(lib_path, e))
    class truct(Structure):
        _fields_ = [("array", POINTER(c_double)),
                    ("len", c_int)]
    va = truct()
    ty = (c_double * 1 )
    va.array = ty()
    va.len = 1
    lib.sample_function.argtypes= [POINTER(truct)]
    lib.sample_function.restype = c_int
    try:
        ret = lib.sample_function(byref(va))
    except Exception as e:
        raise RuntimeError("Library call raises exception: {}".format(e))

C code:

typedef struct A {

    double *array;
      int a;
} A;
void sample_function2(A* structure){
    int array_local[] = { 0,0,1,1,0};
    int iter2;
    for (iter2 =0;iter2<5;iter2++){
        if(array_local[iter2]){
            structure->array[iter2] = iter2;
    }else{
      structure->array[iter2] = 0;
    }}
}

int sample_function( A* structure)
{
    int n = 5;
    int iter;
    sample_function2(structure);

    return 0;
}

This code works as expected. But is it a good practice to use this method?


texts:
I needed a relatively simple pagination, as currently implemented on GoogleSearch (sans prev & next buttons). Most code I've seen was overly complicated so I came up with something that's simpler.

Any suggestions on how to further optimise this?

function doPaging(currentPageInput) {

    let currentPage = currentPageInput, // input
        range       = 5,  // amount of links displayed
        totalPages  = 20, // determined by amount of items, hardcoded for readability
        start       = 1;  // default

    let paging = [];      // output variable

    // Don't use negative values, force start at 1
    if (currentPage < (range / 2) + 1 ) {
        start = 1;

    // Don't go beyond the last page
    } else if (currentPage >= (totalPages - (range / 2) )) {
        start = Math.floor(totalPages - range + 1);

    } else {
        start = (currentPage - Math.floor(range / 2));
    }

    for (let i = start; i <= ((start + range) - 1); i++) {
        if (i === currentPage) {
            paging.push(`[${i}]`); // add brackets to indicate current page
        } else {
            paging.push(i.toString());
        }
    }
    return paging;
}

OUTPUT:

[ '[1]', '2', '3', '4', '5' ]
[ '1', '[2]', '3', '4', '5' ]
[ '1', '2', '[3]', '4', '5' ]
[ '2', '3', '[4]', '5', '6' ]
[ '3', '4', '[5]', '6', '7' ]
[ '4', '5', '[6]', '7', '8' ]
[ '5', '6', '[7]', '8', '9' ]
[ '6', '7', '[8]', '9', '10' ]
[ '7', '8', '[9]', '10', '11' ]
[ '8', '9', '[10]', '11', '12' ]
[ '9', '10', '[11]', '12', '13' ]
[ '10', '11', '[12]', '13', '14' ]
[ '11', '12', '[13]', '14', '15' ]
[ '12', '13', '[14]', '15', '16' ]
[ '13', '14', '[15]', '16', '17' ]
[ '14', '15', '[16]', '17', '18' ]
[ '15', '16', '[17]', '18', '19' ]
[ '16', '17', '[18]', '19', '20' ]
[ '16', '17', '18', '[19]', '20' ]
[ '16', '17', '18', '19', '[20]' ]


texts:
Heres the idea
Write a program that takes two integers, N and M, and find the largest integer composed of N-digits that is evenly divisible by M. N will always be 1 or greater, with M being 2 or greater. Note that some combinations of N and M will not have a solution.
Example: if you are given an N of 3 and M of 2, the largest integer with 3-digits is 999, but the largest 3-digit number that is evenly divisible by 2 is 998, since 998 Modulo 2 is 0. Another example is where N is 2 and M is 101. Since the largest 2-digit integer is 99, and no integers between 1 and 99 are divisible by 101, there is no solution.

I would just like some tips on what to improve

#include <iostream>
#include <stdexcept>
#include <cmath>

using std::cin; using std::cout; using std::endl; using std::runtime_error;
using std::pow;

unsigned largestNumber(unsigned num1) {
return pow(10, num1) - 1;
}

void validNums(const int num1, const int num2) {
    if (num1 < 1 || num1 > 9 || num2 < 2 || num2 > 999999999)
        throw std::runtime_error("invalid input");
}

int divisbleBy(int num1, int num2) {
    for (; num1 != 0; --num1) {
        if (num1 % num2 == 0)
            return num1;
    }
    return 0;
}

int main()
{
    int num1 = 0, num2 = 0;
    int answer = 0;
    cout << "Enter 2 nums and we'll find biggest number possible with num1 digits and we'll then find closest number that num2 can divide by. Num1 has to be between 1-9 and num2 between 2-999-999-999" << endl;
    cin >> num1 >> num2;
    validNums(num1, num2);
    if (answer = divisbleBy(largestNumber(num1), num2))
        cout << "Largest number possible with " << num1 << " is " << largestNumber(num1) << " and the closest number to " << largestNumber(num1) << " divisible by " << num2 << " is " << answer << endl;
    else
        cout << "Invalid" << endl;
    return 0;
}


texts:
I need to transform

List("home", "mens", "clothing", "jackets")

into

List(
  "/home",
  "/home/mens",
  "/home/mens/clothing",
  "/home/mens/clothing/jackets"
)

This is what I have so far:

val nodes = Array("home", "mens", "clothing", "jackets")
val (rootNode, otherNodes) = nodes.splitAt(1)
val tree = otherNodes.foldLeft(rootNode) { (list, token) =>
    list :+ (list.last + "/" + token)
}

What do you think? any obvious problems?


texts:
I'm trying to write a regular expression to check names for invalid entries. Basically I'm trying to eliminate people entering random junk as their name. I know I can't completely eliminate it but I'm trying to make it a little harder at the very least. Here is what I have so far. It works fine I'm wondering if there's a way to improve this.

[b-df-hj-np-tv-z]{5,}|[aeiou]{4,}|([a-z])(?=([a-z]*\1){3,})|([ ])(?=([a-z]*\3){2,})|[0-9]+


texts: PHP DateTime increments, a neater / more efficient way?

texts:
I'm trying to get to grips with the DateTime class in PHP. Previously I've used date() and mktime() when playing with dates.

Here's the head of a calendar table, and I'm pretty sure I'm doing this in a stupid way! That fact that I'm setting the format each time, and modifying the original date with each Interval, seems 'lumpy':

<?php $date = new DateTime('2013-04-01'); ?>
<?php echo $date->format('Y'); ?>
<?php echo $date->format('D jS');?>
<?php $date->add(new DateInterval('P1D')); echo $date->format('D jS');?>
<?php $date->add(new DateInterval('P1D')); echo $date->format('D jS');?>
<?php $date->add(new DateInterval('P1D')); echo $date->format('D jS');?>
<?php $date->add(new DateInterval('P1D')); echo $date->format('D jS');?>
<?php $date->add(new DateInterval('P1D')); echo $date->format('D jS');?>
<?php $date->add(new DateInterval('P1D')); echo $date->format('D jS');?>

Can anyone point me towards a better way to do this. I'm planning to create a function to spit these calendars out, but I've provided an inline example here so you can see the way I'm using DateTime etc for now.

Thanks


texts: Algorithm for describing chess positions

texts:
I have an interesting problem with my chess application. The application reads PGN files, and at any time while viewing a game from the file, the function below, when called, iterates over the chessboard, gets the square names for each piece, and then constructs a string containing the description of which piece is where.

The function runs without errors, however it has a slight issue with respect to its performance: When the chess board is full, or close to full with 32 pieces, it runs pretty fast. Once the pieces go off the board and there remains a handful of pieces to describe, the function returns with a delay of around half a second. I have not tested the function with performance tools, but one can feel there is something strange going on: given the length of the function and its algorithm (please don't swear reading it), I can't understand why it will run faster when the board is full and slower when it's close to empty.

Can anyone spot what causes this issue? In addition, what can I try to optimize it?

def pos_text():
    global node
    #Dictionary of piece symbols to store their location on the board
    d = {"K": [], "Q": [], "R": [], "B": [], "N": [], "P": [], "k": [], "q": [], "r":   [], "b": [], "n": [], "p": []}
    piece_letters = "KkQqRrNnBbPp"
    #Iterates over the board and assigns square names to the individual piece symbols in d
    for x in range(64):
        sq = str(node.board().piece_at(x))
        if sq in piece_letters:
            d[sq].append(chess.SQUARE_NAMES[x])
    # now makes a string containing the description of pieces:
    pos = "White pieces:\nKing: %s\n" % d["K"][0]
    if d["Q"]:
        pos += "Queens: %s\n" % ", ".join(d["Q"]) if len(d["Q"]) >= 2 else "Queen: %s\n" % d["Q"][0]
    if d["R"]:
        pos += "Rooks: %s\n" % ", ".join(d["R"]) if len(d["R"]) >= 2 else "Rook: %s\n" % d["R"][0]
    if d["B"]:
        pos += "Bishops: %s\n" % ", ".join(d["B"]) if len(d["B"]) >= 2 else "Bishop: %s\n" % d["B"][0]
    if d["N"]:
        pos += "Knights: %s\n" % ", ".join(d["N"]) if len(d["N"]) >= 2 else "Knight: %s\n" % d["N"][0]
    if d["P"]:
        pos += "Pawns: %s\n" % ", ".join(d["P"]) if len(d["P"]) >= 2 else "Pawn: %s\n" % d["P"][0]
    pos += "Black pieces:\nKing: %s\n" % d["k"][0]
    if d["q"]:
        pos += "Queens: %s\n" % ", ".join(d["q"]) if len(d["q"]) >= 2 else "Queen: %s\n" % d["q"][0]
    if d["r"]:
        pos += "Rooks: %s\n" % ", ".join(d["r"]) if len(d["r"]) >= 2 else "Rook: %s\n" % d["r"][0]
    if d["b"]:
        pos += "Bishops: %s\n" % ", ".join(d["b"]) if len(d["b"]) >= 2 else "Bishop: %s\n" % d["b"][0]
    if d["n"]:
        pos += "Knights: %s\n" % ", ".join(d["n"]) if len(d["n"]) >= 2 else "Knight: %s\n" % d["n"][0]
    if d["p"]:
        pos += "Pawns: %s\n" % ", ".join(d["p"]) if len(d["p"]) >= 2 else "Pawn: %s\n" % d["p"][0]
    return pos


texts:
Can I create a method to do work with these five sections? I'm doing binding operations so many times.  Do you have an idea on how to make this code prettier?

ddlModelValue -> ASP.NET DropDownList

var dtModel = Session[SystemConstant.ModelSessionKey] as DataTable;
ddlModelValue.DataSource = dtModel;
ddlModelValue.DataTextField = "Name";
ddlModelValue.DataValueField = "Name";
ddlModelValue.DataBind();

var dtGroup = Session[SystemConstant.GroupSessionKey] as DataTable;
ddlGroupValue.DataSource = dtGroup;
ddlGroupValue.DataTextField = "Name";
ddlGroupValue.DataValueField = "Name";
ddlGroupValue.DataBind();

var dtFit = Session[SystemConstant.FitSessionKey] as DataTable;
ddlFitValue.DataSource = dtFit;
ddlFitValue.DataTextField = "Name";
ddlFitValue.DataValueField = "Name";
ddlFitValue.DataBind();

var dtShellType = Session[SystemConstant.ShellTypeSessionKey] as DataTable;
ddlShellTypeValue.DataSource = dtShellType;
ddlShellTypeValue.DataTextField = "Name";
ddlShellTypeValue.DataValueField = "Name";
ddlShellTypeValue.DataBind();

var dtDataTypeCode = Session[SystemConstant.DataTypeCodeSessionKey] as DataTable;
ddlDataTypeCodeValue.DataSource = dtDataTypeCode;
ddlDataTypeCodeValue.DataTextField = "Name";
ddlDataTypeCodeValue.DataValueField = "Name";
ddlDataTypeCodeValue.DataBind();


texts: Scala code to print a Sudoku board and any possible unsolved values

texts:
I'm working through a Sudoku solver problem that I found at UPenn (no it's not my homework ;)). I'm a beginner at Scala, and I'm trying to write good functional code (not that this particular method really demonstrates that...).

A problem that keeps occurring for me involves trying to use Lists but not using vars, as per good Scala practice. In fact, vars are marked down in the assignment.

In the below method that prints a Scala board plus any unsolved values, I maintain a List of unsolved values. However I have to set this List as a var because I need to reassign it for each iteration of my loop. I don't think that using ImmutableList is a better solution.

What's a better approach here? Should I be re-writing this entire method to be tail recursive? I think that could be difficult and the resulting code might not be as readable. Also am I using too many ifs? Should every if be replaced with pattern matching in Scala?

/**
  * Displays a Sudoku board in a clear readable format. For any unsolved cells, possible answers are printed below
  * alongside their x and y coordinates.
  * @param message a string to display before the board is printed
  * @param board the Sudoku board itself
  */
def printBoard(board: Board, message: String = "Printing a board", displayPossibleValues: Boolean = true) = {
  val rowSeparator = "+ - - - + - - - + - - - +"
  var possibleValues = List[(Int, Int, List[Int])]()
  println(message)
  println(rowSeparator)
  for (i <- 0 until rows) {
    if (i == 3 || i == 6) {
      println(rowSeparator)
    }
    print("| ")
    for (j <- 0 until cols) {
      if (j == 3 || j == 6)
        print("| ")
      val currentCell = board(i)(j)
      if (currentCell.length == 1 && currentCell(0) != 0)
        print(currentCell.mkString + " ")
      else {
        print("x ")
        possibleValues = possibleValues :+ new Tuple3(i + 1, j + 1, currentCell)
      }
    }
    print("|")
    println
  }
  println(rowSeparator)
  if (displayPossibleValues) {
    println("Remaining values:")
    println(possibleValues.mkString("\n"))
  }
  println
}

Sample output from this method:

+ - - - + - - - + - - - +
| 2 8 4 | x 9 3 | 1 6 7 |
| 3 6 9 | 4 7 1 | x x 5 |
| 1 5 7 | 8 2 6 | 4 9 3 |
+ - - - + - - - + - - - +
| 5 7 6 | x 4 x | x 3 1 |
| 8 9 2 | 1 3 5 | 6 7 4 |
| 4 1 3 | x 6 x | 9 x x |
+ - - - + - - - + - - - +
| 7 2 x | x 8 9 | x 4 6 |
| 6 4 x | x 1 2 | x x x |
| 9 3 8 | 6 5 4 | 7 1 2 |
+ - - - + - - - + - - - +
Remaining values:
(1,4,List(3, 5, 9))
(2,7,List(2, 8))
(2,8,List(2, 8))
(4,4,List(2, 9))
(4,6,List(8, 9))
(4,7,List(2, 8))
(6,4,List(2, 7))
(6,6,List(7, 8))
(6,8,List(2, 5, 8))
(6,9,List(2, 8))
(7,3,List(1, 5))
(7,4,List(3, 9))
(7,7,List(3, 5))
(8,3,List(5, 8))
(8,4,List(3, 7))
(8,7,List(3, 5, 8))
(8,8,List(5, 8))
(8,9,List(8, 9))


texts: Calculating when trains will meet, iteratively and using OOP

texts:
I've done a little bit of programming in the past, mostly just dabbling.
After a long time of not touching an IDE, I am getting back into it, with Visual Studio. I just threw this quick project together to make sure I remember how to use classes and objects before I start playing with bigger projects.

I would love a quick critique to make sure there arent any glaring poor practices that could develop into bad habbits in the future.

I know the standard way to solve this problem is just time = distance/(velA+velB), but what would the point of using objects be if i didnt have the objects do something and change their status in someway?

What do you think, looks good?

/*

The goal for this practice program is to solve the common math word problem below using classes and objects.
I feel that using iterations rather than the basic math formula to solve, although clearly less efficient, would be more true to thinking in terms of objects.

Train A, traveling X miles per hour (mph), leaves Westford heading toward Eastford, 260 miles away.
At the same time Train B, traveling Y mph, leaves Eastford heading toward Westford.
When do the two trains meet? How far from each city do they meet?

*/

#include "pch.h"
#include <iostream>
using namespace std;

class Train
{
public:
    Train(int, int);
    int getLocation();
    void update();
private:
    int location, velocity;
};

Train::Train(int loc, int vel) //to initialize the train object and set its location and velocity
{
    location = loc;
    velocity = vel;
}

int Train::getLocation() // returns the location of the train object
{
    return location;
}

void Train::update() // updates the train object for one iteration
{
    location += velocity;
}

int main()
{
    int velA, velB, distance; //to take the values from the user input
    int time;   // to keep track of the number of iterations
                // time is declared here so it can be used outside of the for loop

    //input
    cout << "Enter velocity of the train from Westford:\n";
    cin >> velA;
    cout << "\n\nEnter velocity of the train from Eastford:\n";
    cin >> velB;
    cout << "\n\nEnter the distance between Westford and Eastford:\n";
    cin >> distance;

    //initialize each train
    Train trainA(0, velA);
    Train trainB(distance, 0 - velB);   //location of trainB is distance because the distance between an x coordinate at 0 and another x coordinate is equal to the second x coordinate
                                        //the velocity of trainB is the negative of velB because it is traveling in the opposite direction of trainA

    //run the sim
    for (time = 0; trainA.getLocation() < trainB.getLocation(); time++)
    {
        trainA.update();
        trainB.update();
    }

    //output
    cout << "\n\nThe Trains pass eachother after " << time << " hours."
        << "\nAt that time, the Westford train is " << trainA.getLocation() << " miles from Westford\n"
        << "and the Eastford train is " << distance - trainB.getLocation() << " miles from Eastford.\n\n";

    return 0;
}


texts: object oriented Node.js class RiddleInfo.js

texts:
So I am trying to make a Object oriented Node.js class for store information about riddles.
Please feel free to be harsh as possible. Would love to hear your ideas about how to make this class better!

function RiddleInfo(riddle, answer, hint1, hint2, hint3, ohFactor, difficulty) {
    this.riddle = riddle || null;
    this.answer = answer || null;
    this.hint1 = hint1 || null;
    this.hint2 = hint2 || null;
    this.hint3 = hint3 || null;
    this.ohFactor = ohFactor || null;
    this.difficulty = difficulty || null;
}

RiddleInfo.prototype.getRiddle = function() {
    return this.riddle;
}

RiddleInfo.prototype.setRiddle = function(riddle) {
    this.riddle = riddle;
}

RiddleInfo.prototype.getAnswer = function() {
    return this.answer;
}

RiddleInfo.prototype.setAnswer = function(answer) {
    this.answer = answer;
}

RiddleInfo.prototype.getHint = function(hintNumber) {
    switch(hintNumber)
    {
        case 1:
            return this.hint1;
            break;
        case 2:
            return this.hint2;
            break;
        case 3:
            return this.hint3;
            break;
        default:
            return 'InvalidArgumentException line 25 in RiddleInfo.js: ' +
                   'hintNumber must be 1, 2, or 3 but instead was ' + hintNumber;
    }
}

RiddleInfo.prototype.getOhFactor = function() {
    return this.ohFactor;
}

RiddleInfo.prototype.setOhFactor = function(ohFactor) {
    this.ohFactor = ohFactor;
}

RiddleInfo.prototype.getDifficulty = function() {
    return this.difficulty;
}

RiddleInfo.prototype.setDifficulty = function(difficulty) {
    this.difficulty = difficulty;
}

RiddleInfo.prototype.isSimilarTo = function(otherRiddle) {
    if (this.getRiddle() === otherRiddle.getRiddle() ||
        this.getAnswer() === otherRiddle.getAnswer()
        ) {
        return true;
    } else {
        return false;
    }
}

RiddleInfo.prototype.fill = function(newFields) {
    for (var field in newFields) {
        if (this.hasOwnProperty(field) && newFields.hasOwnProperty(field)) {
            if (this[field] !== 'undefined') {
                this[field] = newFields[field];
            }
        }
    }
};

module.exports = RiddleInfo;


texts: decode `IEnumerable` to string made of 1 byte characters (eg., ASCII)

texts:
I'm looking for a more elegant (eg., with less many functions, eg., "copy into contiguous array then reinterpret") or more efficient way (with less complexity) to transcode a IEnumerable<uint> (~ array of 32bits int), which is a compact way to represent a byte[4] array, into a string as array of 8bits char:
public static string UintArraytoString(this IEnumerable<uint> x) =>
    string.Concat(x.Select(o =>
        new string(BitConverter.GetBytes(o).Select(Convert.ToChar).ToArray())));

I'm using .net 5.0. I'm open to use unsafe methods too. I think that one may do something like a reinterpretcast, but the IEnumerable is not necessarily contiguous.


texts: Convert a password to a phonetic string for end users

texts:
As much as I hate it, sometimes providing passwords to people has to be done electronically. When I do that I try to remove any ambiguity that might be created by the font, user etc. and provide a phonetic translation of the string. For things like 0 and O or l and I which might not be obvious at first.

The function below can take a single string or be piped a string array. I could get crazy with this later to support other languages by making some nested arrays but for now it only supports English.

function Get-PhoneticString{
    param(
        [parameter(ValueFromPipeline=$true, Mandatory=$true)]
        [string]$StringToExplode,
        [string]$Delimiter = " - "
    )
    process{
        # Alphabetic conversions using military phonetics
        $phoneticAlphabet = @{
            "a" = "alfa"; "b" = "bravo"; "c" = "charlie"; "d" = "delta"; "e" = "echo";
            "f" = "foxtrot"; "g" = "golf"; "h" = "hotel"; "i" = "india"; "j" = "juliett";
            "k" = "kilo"; "l" = "lima"; "m" = "mike"; "n" = "november"; "o" = "oscar";
            "p" = "papa"; "q" = "quebec"; "r" = "romeo"; "s" = "sierra"; "t" = "tango";
            "u" = "uniform"; "v" = "victor"; "w" = "whiskey"; "x" = "x-ray"; "y" = "yankee";
            "z" = "zulu"
        }

        $numberAsString = @{
            "0"="zero"; "1"="one"; "2"="two"; "3"="three"; "4"="four"
            "5"="five"; "6"="six"; "7"="seven"; "8"="eight"; "9"="nine"
        }

        $symbolAsString = @{
            "!" = "Exclamation Mark"; '"' = "Double Quote"; "#" = "Number Sign"; "$" = "Dollar"; "%" = "Percent"; "&" = "Ampersand"
            "'" = "Single Quote"; "(" = "Left Parenthesis"; ")" = "Right Parenthesis"; "*" = "Asterisk"; "+" = "Plus"
            "," = "Comma"; "-" = "Minus"; "." = "Period"; "/" = "Slash"; ":" = "Colon"; ";" = "Semicolon"; "<" = "Less Than"
            "=" = "Equality Sign"; ">" = "Greater Than"; "?" = "Question Mark"; "@" = "At Sign"; "[" = "Left Square Bracket"
            "\" = "Backslash"; "]" = "Right Square Bracket"; "^" = "Caret"; "_" = "Underscore"; '`' = "Grave / Accent"
            "{" = "Left Curly Bracket"; "|" = "Vertical Bar"; "}" = "Right Curly Bracket"
        }

        # Convert this string into a character array. For each character find its string equivilent in one of the defined hash tables
        ($StringToExplode.ToCharArray() |  ForEach-Object{
            switch -Regex -CaseSensitive ($_){
                "[a-z]"{$phoneticAlphabet."$_"}
                "[A-Z]"{($phoneticAlphabet."$_").ToUpper()}
                "\d"{$numberAsString."$_"}
                "\s"{$_}# Return whitespace unaltered
                default{ $symbolAsString."$_"}
            }
        }) -join $Delimiter
    }

}

So a sample call and output would look like this

"K0D3R3v13w" | Get-PhoneticString
KILO - zero - DELTA - three - ROMEO - three - victor - one - three - whiskey

It only supports the basic ASCII printable character set. Any uppercase alphabetical characters will have all uppercase strings returned. If the character is not alphanumeric it will be assumed that it is a symbol in the set. If that character is not covered at all then it will show as empty in the resultant string and means something needs to be updated to account for it. Since I am using this for passwords that should cover near all supported characters.


texts:
I took an entire line of input in the form of a string, and tokenized the string into substrings and obtained the first string as the first name and the second as the last name. This program as it stands is very basic and limited however my primary focus was on the creation of generic functions to do all the heavy lifting (generic as in they are not specific to the program and could be used elsewhere I've had several problems in the past where my functions are to narrowed on a specific problem, so please tell me how I did!).

The function for parsing the string, get_substr(), most likely can, and should, be improved and I am hoping for better ideas on how to do it!

/*Input name: first, last. Output name: Last, first*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

#define MAXSIZE 1024

bool readline(char *line, const size_t buffer_len);
bool hasDigits(const char *str);
bool hasPunct(const char *str);
void chop_newline(char *str);
char *remove_leading_whitespace(char *str);
char *get_substr(char *str, char **endptr, const char *str_dim);

bool readline(char *line, const size_t buffer_len) {
    if (fgets(line, buffer_len, stdin) != NULL) {
        chop_newline(line);
        if (line[0] != NULL) {
            return true;
        }
    }
    return false;
}

bool hasDigits(const char *str) {
    for (size_t i = 0; str[i] != '\0'; ++i) {
        if (isdigit((unsigned char)str[i])) {
            return true;
        }
    }
    return false;
}

bool hasPunct(const char *str) {
    for (size_t i = 0; str[i] != '\0'; ++i) {
        if (ispunct((unsigned char)str[i])) {
            return true;
        }
    }
    return false;
}

void chop_newline(char *str) {
    str[strcspn(str, "\n")] = '\0';
}

char *remove_leading_whitespace(char *str) {
    if (str) {
        while (isspace(*str) && str) str++; //remove whitespace
    }
    return str;
}

/*
get_substr

@param **endptr, set to next character after a diliminator in string str
@param *str_dim, list of diliminators used to split string ex: " !,.-?"

when called, absorb incoming whitespace ,read until first diliminator, return substring,
and set **endptr equal to the rest of the string. If endptr is not NULL, then string has more to parse,
returns NULL if nothing was parsed else returns c-string
*/

char *get_substr(char *str, char **endptr, const char *str_dim) {
    char *substr = NULL;
    remove_leading_whitespace(str);
    substr = strtok(str, str_dim);
    *endptr = strtok(NULL, "\0");

    return substr;
}

int main() {
    char str_name[MAXSIZE];
    char *last_name = NULL, *first_name = NULL, *endptr = NULL;

    printf("Please enter your first name followed by your last name: ");
    for (;;) {
        if (readline(str_name, sizeof str_name)) {
            if (!hasDigits(str_name) && !hasPunct(str_name)) {
                break;
            }
            printf("\nTry again, name must contain letters and cannot contain numbers or punctuation...\n");
        }
        else {
            printf("\nEmpty string please try again...\n");
        }
    }

    first_name = get_substr(str_name, &endptr, " ");
    last_name = get_substr(endptr, &endptr, " ");

    if (endptr) {
        printf("Error, too much input, expected: First name Last name\n %s was not saved...\n", endptr);
    }
    else if (!last_name) {
        printf("Error must have a first and last name...\n");
    }
    else {
        printf("Your name is: %s, %s\n", last_name, first_name);
    }

    printf("Press any key to continue...\n");
    getch();
}


texts: Using Interface for context menu for a web application

texts:
I'm currently building an interactive web application that allows users to create flow charts using Angular2, typescript and PixiJS (the latter is a 2D rendering library).

The core part of my application is a PixiJS object housed within an Angular2 component. This PixiJS object contains other graphical UI elements which the user can interact with. Some examples of these graphical UI elements are FlowChartSquareInstance, FlowChartCircleInstance, and FlowChartConnectorInstance.

I need to implement a context menu feature in my app. When right clicking on graphical UI elements like the above, a context menu should appear. However, each graphical UI instance will have a different set of options in its context menu. Hence, the context menu needs to be created dynamically, at runtime.

I found the simplest way to do this is attach a right-click listener to each graphical UI element, which will call a function to create the context menu. The context menu will be created using elements from the PixiJS rendering library.

I defined the following interface:

/*
ContextMenuDisplayer.ts

All UI components that need to display a context menu on right click should
implement this interface
*/

export interface ContextMenuDisplayer {
    /*
    Use to create the context menu object. Needs to use the string array
    returned by getContextMenuOptions
    */
    createContextMenu(contextMenuOptions : string[]) : void;

    /*
    Return a string array of context menu options
    */
    getContextMenuOptions() : string[];
}

The idea is that all graphical UI elements will implement this interface, and their right-click listener function will call the methods defined in this interface.

Consider this example:

class FlowChartSquareInstance implements ContextMenuDisplayer{

    constructor(){
        //The listener function
        this.on("right click", this.onRightClick, this);
    }

    onRightClick(){
        this.createContextMenu(this.getContextMenuOptions);
    }

    createContextMenu(contextMenuOptions : string[]){
        //create the context menu using PixiJS
    }

    getContextMenuOptions() : string[] {
        return ["delete", "copy", "duplicate"];
    }

    //Other methods
}

Is this a good way of adding a context menu feature? Or can it be improved upon? The idea of the interface was to define a way for future developers to add context menu's to any new graphical UI elements they might create. Not all graphical UI elements need to have context menus in my application.

I've decided to post here even though there isn't much code to review to nip this in the bud if it's not a good way of doing it.


texts: How to handle Throw exception + close connection

texts:
I have a function that works with a database. If something wrong happens I want to throw an exception, and I also want that all resources have to be closed.

Is this a good way to do it? There is a better way to do it?

public Strint getStuff(Integer id) throws Exception {

    String result = "";

    Connection connection = db.openConection();
    ResultSet rs = null;

    try {
       // DO STUFF WITH DB
    } catch (Exception e) {
        throw e;
    } finally {
        rs.close();
        db.closeConection(connection);
    }
    return result;
}


texts: Making a decorator with arguments in a flat manner

texts:
I know you must've been already tired of Python decorators, but this one seems new! There is a common practice of making decorators with arguments.
But Flat is better than nested, so let's flatten it up:

def decorator_with_args(arg):

    def wrapper(*args, **kwargs):
        print('decorated with arg: {}'.format(arg))
        return wrapper.func(*args, **kwargs)

    def wrapper_creator(decorable):
        wrapper.func = decorable
        return functools.wraps(decorable)(wrapper)

    return wrapper_creator

Wrapped func is passed as an attribute, arg - via closure. They don't get overwritten with multiple consequent calls to decorator_with_args.

But not chained ones - functools.wraps will update wrapper's __dict__, overwriting its func attribute like this:

@decorator_with_args('This decorator will be applied')
@decorator_with_args('Others will not')
def gotcha():
    pass

So, attributes are not a good place to store our func. But closure seems to be. Let's use it:

def decorator_with_args(arg):
    func = None

    def wrapper(*args, **kwargs):
        print('decorated with arg: {}'.format(arg))
        return func(*args, **kwargs)

    def wrapper_creator(decorable):
        nonlocal func
        func = decorable
        return functools.wraps(decorable)(wrapper)

    return wrapper_creator

Now it looks good to me! Does it to you? Is it pythonic, idiomatic, correct and nicely performing?

And a real example of making something useful (this is a part to be reviewed):

import functools
import logging
import logging.config

def temp_loglevel(level):
    """
    A decorator for setting temporary loglevel for the scope of
    the wrapped function, then reverting it back on wrapper exit

    Arguments:
        level: new logging level to set
    """
    logger = logging.getLogger()
    func = None

    def wrapper(*args, **kwargs):
        old_level = logger.level
        logger.setLevel(level)
        rv = func(*args, **kwargs)
        logger.setLevel(old_level)
        return rv

    def wrapper_maker(decorable):
        nonlocal func
        func = decorable
        logger.warn(
            "temp_loglevel used, don't forget to "
            "remove it when debugging is done"
        )

        return functools.wraps(decorable)(wrapper)

    return wrapper_maker

logging.config.dictConfig(dict(
    version = 1,
    disable_existing_loggers = False,
    formatters = {
        'default': {
            'format': '%(asctime)-15s [%(levelname)s] %(message)s'
        }
    },
    handlers = {
        'std': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'default'
        }
    },
    root = {
        'handlers': ['std'],
        'propagate': False,
        'level': 'INFO'
    }
))

@temp_loglevel(logging.DEBUG)
def print_debug():
    logging.getLogger().debug('This should be visible')

if __name__ == '__main__':
    print_debug()

I would be glad if you put some critique of my code styling as well!


texts: Cycle detection in undirected graphs with recursive DFS

texts:
I wrote a very simple implementation of cycle detection in an undirected graph; I'm not interested in applying it to any real-life case: it's just for explaining the basic idea behind cycle detection in a CS lesson.
I went for recursive DFS, and unlike other implementations I found on the internet, I used just one set for the visited nodes (instead of having a set for the visited nodes and another one for the ancestors):
boolean hasCycleDfs(Node current, Set<Node> visited) {

   if (visited.contains(current)) {
      return true;
   }

   visited.add(current);
   for (Node neighbour: current.neighbors) {
      if (hasCycleDfs(neighbour, visited)) {
         return true;
      }
   }
   visited.remove(current);

   return false;
}

I wrote a couple of tests and they're green:
   @Test
   public void test() {

      List<Node> nodes = IntStream
                .range(1, 8)
                .mapToObj(Node::new)
                .collect(Collectors.toList());

      Node n1 = nodes.get(0);
      Node n2 = nodes.get(1);
      Node n3 = nodes.get(2);
      Node n4 = nodes.get(3);
      Node n5 = nodes.get(4);
      Node n6 = nodes.get(5);
      Node n7 = nodes.get(6);

      n1.add(n2).add(n3);
      n2.add(n4);
      n3.add(n4).add(n6);
      n4.add(n6).add(n7);
      n5.add(n1);
      n6.add(n5);
      assertTrue(hasCycleDfs(n1, new HashSet<>()));

      cleanNodes(nodes);
      n1.add(n2);
      n2.add(n3);
      n3.add(n4);
      n4.add(n1);
      assertTrue(hasCycleDfs(n1, new HashSet<>()));

      cleanNodes(nodes);
      n1.add(n2).add(n5).add(n3);
      n2.add(n3).add(n5);
      n3.add(n4).add(n5);
      n4.add(n5);
      assertFalse(hasCycleDfs(n1, new HashSet<>()));

      cleanNodes(nodes);
      n1.add(n2).add(n3);
      n2.add(n3);
      assertFalse(hasCycleDfs(n1, new HashSet<>()));
   }

   void cleanNodes(List<Node> nodes) {
      nodes.forEach(Node::clearNeighbours);
   }

This is the Node class:
class Node {
   int val;
   Set<Node> neighbors = new HashSet<>();

   Node(int val) {
      this.val = val;
   }

   public Node add(Node child) {
      neighbors.add(child);
      return this;
   }

   public void clearNeighbours() {
      neighbors.clear();
   }

   @Override
   public String toString() {
      return "[" + val + "]";
   }

   @Override
   public boolean equals(Object o) {
      Node node = (Node) o;
      return val == node.val;
   }

   @Override
   public int hashCode() {
      return val * 31;
   }
}

Do you see any edge case I didn't take into account that will give a wrong answer?


texts: Loading a combobox with an enum and binding to it

texts:
I have the following code to load an enumeration into a bound combo box, but am not quite happy with it.

I would prefer to store the actual enum value in the combo box and bind directly to it.
However, I can't quite figure out how to do so.

 public enum HemEnum
    {
        HemNone = -1,
        Hemsew = 0,
        HemWeld = 1,
        Hemdoublefold = 2
    }

 public static void LoadHemCombo(ComboBox cbo)
    {
    var values = from Enum e in Enum.GetValues(typeof(HemEnum))
                     select new { ID = e, Name = e.ToString() };

          foreach (var value in values)
    {
        var s = GetHemTypeDescription((HemEnum)value.ID );
        cbo.Items.Add(s);
    }
    }

  public static string GetHemTypeDescription(HemEnum hemType)
    {
        string s = null;
        switch (hemType)
        {
            case HemEnum.HemNone:
                s = "none";
                break;
            case HemEnum.Hemsew:
                s = "sewn";
                break;
            case HemEnum.HemWeld:
                s = "welded";
                break;
            case HemEnum.hemdoublefold:
                s = "double folded";
                break;
            default:
                s = "not known";
                break;
        }
        return s;
    }

Inside the form load event I load the combo and bind to it.

 LoadHemCombo(cboHem)
 cboHem.DataBindings.Add("Text", myBindingSource, "HemTypeDescription");

 class myObject
 {
    public string HemTypeDescription
    {
        get
        {
            return GetHemTypeDescription(this.HemType);

        }
        set
        {
            this.HemType = GetHemTypeFromDescription(value);
        }
  }

public static vHemEnum GetHemTypeFromDescription(string description)
    {
        int r =0;
        for (var i = (int)HemEnum.HemNone; i <= (int)HemEnum.Hemdoublefold; i++)
        {
            var s = GetHemTypeDescription((HemEnum)i);
            if (description == s)
            {
                r  = i;
                break;
            }
        }
        return (HemEnum)r;
    }
 }

in the designer I set

myBindingSource.DataSource = myObject

and before loading the form I create an instance of myObject and add it to myBindingSource using

myBindingSource.Add(myObject)


texts:
I'd like to get a few pointers about my code.
I know that shared_ptr is up and running, and I'm reinventing the wheel but you can't say no to the school assignment.

template <typename T> class SharedPointer;

template <typename T>
void swap(SharedPointer<T> &lhs, SharedPointer<T> &rhs)
{
    lhs.swap(rhs);
}

template <typename T>
class SharedPointer {
    friend void swap<T>(SharedPointer &lhs, SharedPointer &rhs);

public:
    SharedPointer(): use_c(new std::size_t(0)), p(nullptr), deleter(Deleter()) { }
    SharedPointer(T *ptr): p(ptr), use_c(new std::size_t(1)), deleter(Deleter()) { }
    SharedPointer(T *ptr, const std::function<void(*)> &del):
            p(ptr), use_c(new std::size_t(1)), deleter(del) { }
    SharedPointer(const SharedPointer &rhs):
            use_c(rhs.use_c), p(rhs.p), deleter(rhs.deleter) { ++*use_c; }

    SharedPointer(SharedPointer &&) noexcept;
    SharedPointer& operator=(const SharedPointer &);
    SharedPointer& operator=(SharedPointer &&) noexcept;
    ~SharedPointer() { free(); }

    std::size_t use_count() { return *use_c; }

    bool unique() const { return *use_c == 1; }

    operator bool() const { return p != nullptr; }

    void reset() noexcept { free(); use_c = new std::size_t(0); };
    void reset(T*);
    void reset(T*, const std::function<void(T*)>&);

    void swap(SharedPointer<T>&);

    T* get() const { return p; }

    T& operator*() const { return *p; }
    T* operator->() const { return &*p; }

private:
    std::size_t *use_c;
    T *p;
    std::function<void(T*)> deleter;

    void free();
};

template <typename T>
SharedPointer<T>::SharedPointer(SharedPointer &&rhs) noexcept:
        use_c(rhs.use_c), p(rhs.p), deleter(std::move(rhs.deleter))
{
    rhs.use_c = new std::size_t(0);
    rhs.p = nullptr;
}

template <typename T>
SharedPointer<T> &SharedPointer<T>::operator=(const SharedPointer &rhs)
{
    ++*rhs.use_c;
    free();
    this->use_c = rhs.use_c;
    this->p = rhs.p;
    this->deleter = rhs.deleter;
    return *this;
}

template <typename T>
SharedPointer<T> &SharedPointer<T>::operator=(SharedPointer &&rhs) noexcept
{
    swap(rhs);
    rhs.free();
    rhs.use_c = new std::size_t(0);
    return *this;
}

template <typename T>
void SharedPointer<T>::reset(T *rhs)
{
    if (p != rhs) {
        free();
        p = rhs;
        use_c = new std::size_t(1);
    }
}

template <typename T>
void SharedPointer<T>::reset(T *rhs, const std::function<void(T *)> &del)
{
    if (p != rhs) {
        reset(rhs);
        deleter = del;
    }
}

template <typename T>
void SharedPointer<T>::swap(SharedPointer<T> &rhs)
{
    using std::swap;
    swap(this->use_c, rhs.use_c);
    swap(this->p, rhs.p);
    swap(this->deleter, rhs.deleter);
}

template <typename T>
void SharedPointer<T>::free()
{
    if (p && --*use_c == 0) {
        deleter(p);
        delete use_c;
    } else if (!p) {
        delete use_c;
    }
    use_c = nullptr;
    p = nullptr;
}

I've yet to add here some non-member operators, but I guess that's trivial and it's no use to litter this post so much.
I've tried to test it here and there and it looks like it works but I'm unsure about copy-and-swap and few other things.
It uses this functor class as the default deleter, if anyone is wondering what's that about.

class Deleter {
public:
    template <typename T> void operator()(T *p) const;
};

template <typename T> void Deleter::operator()(T *p) const
{
    delete p;
}

So basically I'd like to ask your help with the copy-and-swap idiom - if this implementation is correct and if it's needed at all and the overall coding style.


texts:
Purpose of the code:

Let's say I have 3 excel files to deal with.

Those file have already been filtered or hidden because the content is very large. And I only need part of the content for every excel files.

I don't want to open every file and worksheets in order to copy the desired range.

I want to write a code to combine every filtered or hidden cells and put those cells to a brand new workbook.

Steps of the code:

1.Combine every filtered or hidden cells of all worksheets for every excel files.

2.Create a new empty single-worksheet workbook.

3.Put all cells of Step 1 into Step 2.

Problem of the code:

1.Running too slow. Maybe there are too many for loops?

import openpyxl
import os
import glob

path = os.getcwd()
data=[]
x=input('name：') + '.xlsx'
target_xls = os.path.join(path,x)
for file in glob.glob(path+'\*.*'):
    if file.endswith((".xlsx")):
        wb = openpyxl.load_workbook(file, data_only=True)
        for sheet in wb.worksheets:
            for j in range(2, sheet.max_row+1 ):
                for i in range(1,sheet.max_column+1):
                    ihidden = sheet.row_dimensions[j].hidden  # Row Visibility True / False
                    svalue = sheet.cell(column=i,row=j).value
                    if ihidden == True:
                        shidden = "HIDDEN"
                    else:
                        shidden = "VISIBLE"
                        data.append(svalue)
WP= openpyxl.Workbook()
ws = WP.active
ws.title = "Sheet1"
x=sheet.max_column
new_list = [data[i:i+x] for i in range(0, len(data), x)]
for elem in new_list:
    ws.append(elem)
WP.save(target_xls)


texts:
I would like you to review the locking mechanism I implement in C# class. Will it be working correctly with many threads?
Please don't mind rest of the code because I just try to repair the class quickly to have a thread safe logging class for my project.
Any other suggestions are welcome.

public static class Debug
{

    static readonly object _consoleLocker = new object();
    static readonly object _diskDriveLocker = new object();

    public static void Log(Tryb tryb, int level, string caller, string message, string messageExt)
    {
        String strAppDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
        strAppDir = strAppDir.Replace("file:\\", ""); // dla windowsa
        strAppDir = strAppDir.Replace("file:", "");  // dla linuksa
        string file = Path.Combine(strAppDir, "log.txt");
        ProcessLogMessage(tryb, "[log]", caller, message, messageExt, file);
    }

    public static void Log(Tryb tryb, int level, string caller, string message, string messageExt, string file)
    {
        ProcessLogMessage(tryb, "[log]", caller, message, messageExt, file);
    }

    public static void Error(Tryb tryb, string caller, string message, string messageExt)
    {
        String strAppDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
        strAppDir = strAppDir.Replace("file:\\", ""); // dla windowsa
        strAppDir = strAppDir.Replace("file:", "");  // dla linuksa
        string file = Path.Combine(strAppDir, "error.txt");
        ProcessLogMessage(tryb, "[error]", caller, message, messageExt, file);
    }

    public static void Error(Tryb tryb, string caller, string message, string messageExt, string file)
    {
        ProcessLogMessage(tryb, "[error]", caller, message, messageExt, file);
    }

    static void ProcessLogMessage(Tryb tryb, string rodzaj, string caller, string message, string messageExt, string file)
    {
        string dane = String.Format("{0}, {1}, {2}, {3}, {4}", DateTime.Now, rodzaj, caller, message, messageExt);
        switch (tryb)
        {
            case Tryb.FILE:
                lock (_diskDriveLocker)
                {
                    WriteLogToFile(dane, file);
                }
                break;
            case Tryb.CONSOLE:
                lock (_consoleLocker)
                {
                    Console.WriteLine(dane);
                }
                break;
            case Tryb.FILEANDCONSOLE:
                lock (_consoleLocker)
                {
                    Console.WriteLine(dane);
                }
                lock (_diskDriveLocker)
                {
                    WriteLogToFile(dane, file);
                }
                break;
        }
    }

    static void WriteLogToFile(string strLogMessage, string strLogFile)
    {
        StreamWriter swLog = null;

        try
        {
            if (!File.Exists(strLogFile))
                swLog = new StreamWriter(strLogFile);
            else
                swLog = File.AppendText(strLogFile);

            swLog.WriteLine(strLogMessage);
        }
        finally
        {
            if (swLog != null)
            {
                swLog.Close();
                swLog.Dispose();
            }
        }
    }

}

public enum Tryb
{
    FILE = 0,
    CONSOLE = 1,
    FILEANDCONSOLE = 2
}


texts: Optimization fo code snippet including multiple np.multipy statements

texts:
I working on optimizing some code for speed in a python module. I have pinned down the bottleneck and is a code snippet which calculates three np.ndarrays. Namely the following code:

xh = np.multiply(K_Rinv[0, 0], x )
xh += np.multiply(K_Rinv[0, 1],  y)
xh += np.multiply(K_Rinv[0, 2],  h)
yh = np.multiply(K_Rinv[1, 0],  x)
yh += np.multiply(K_Rinv[1, 1],  y)
yh += np.multiply(K_Rinv[1, 2],  h)
q = np.multiply(K_Rinv[2, 0],  x)
q += np.multiply(K_Rinv[2, 1],  y)
q += np.multiply(K_Rinv[2, 2],  h)

where x, y and h are np.ndarrays with shape (4206, 5749) and K_Rinv is a np.ndarray witch shape (3, 3). This code snippet is called multiple times and takes more than 50% of the time of the whole code. Is there a way to speed this up ? Or is it just as it is and can't be speed up.

Every idea and criticism is welcome.


texts: Rust function to read the first line of a file, strip leading hashes and whitespace

texts:
I’m writing a Rust function for getting a title based on the first line of a file.

The files are written in Markdown, and the first line should be a heading that starts with one or more hashes, followed by some text. Examples:

# This is a top-level heading
## This is a second-level heading
#### Let's jump straight to the fourth-level heading

I want to throw away the leading hashes, discard any leading/trailing whitespace, and return the remaining string. Example outputs:

"This is a top-level heading"
"This is a second-level heading"
"Let's jump straight to the fourth-level heading"

Assume that, for now, I’m not worried about edge cases like a first line that’s only whitespace and hashes, or a file whose first line is pathologically long.

This is the program I’ve written to do it:

use std::fs;
use std::io::{BufRead, BufReader};
use std::path::PathBuf;

/// Get the title of a Markdown file.
///
/// Reads the first line of a Markdown file, strips any hashes and
/// leading/trailing whitespace, and returns the title.
fn title_string(path: PathBuf) -> String {

    // Read the first line of the file into `title`.
    let file = match fs::File::open(&path) {
        Ok(file) => file,
        Err(_) => panic!("Unable to read title from {:?}", &path),
    };
    let mut buffer = BufReader::new(file);
    let mut first_line = String::new();
    let _ = buffer.read_line(&mut first_line);

    // Where do the leading hashes stop?
    let mut last_hash = 0;
    for (idx, c) in first_line.chars().enumerate() {
        if c != '#' {
            last_hash = idx;
            break
        }
    }

    // Trim the leading hashes and any whitespace
    let first_line: String = first_line.drain(last_hash..).collect();
    let first_line = String::from(first_line.trim());

    first_line
}

fn main() {
    let title = title_string(PathBuf::from("./example.md"));
    println!("The title is '{}'", title);
}

I’m fairly new to Rust, and I’m sure I’m doing stuff that isn’t as optimal or idiomatic as it could be.  Particular questions:

Is this idiomatic Rust?
Is there a better way to strip leading characters from a string? I looked in the documentation for std::string::String and couldn’t see anything. The String::from() feels a bit inefficient.
Is there anything unsafe that could easily crash (the panic! aside)?


texts:
I'm writing a 2d top down game where I perform a lot of "closest" searches between one point and all the rest of the points.

In this example, "me" wants to search for the closest visible house (Home) that I haven't visited yet, and if it is not found, return null.

protected Home getClosestUnvisitedVisibleHome(Person me, final int VISIBLE_ZONE) {
    List<Home> visitedHomes = me.getVisitedHomes();
    Map<Home, Integer> homeDistances = new HashMap<>();
    List<Home> allHomes = getHomes();
    allHomes.stream().parallel().forEach(home -> homeDistances.put(home, range(me, home)));
    List<Home> unvisitedVisibleHomes = allHomes.stream().parallel().filter(
            home -> !visitedHomes.contains(home) && homeDistances.get(home) <= VISIBLE_ZONE
    ).collect(Collectors.toList());
    unvisitedVisibleHomes.sort((home1, home2) -> homeDistances.get(home1).compareTo(homeDistances.get(home2)));
    try {
        return unvisitedVisibleHomes.get(0);
    } catch (IndexOutOfBoundsException e) {
        return null;
    }
}

protected int range(VisibleEntity visibleEntity, VisibleEntity me) {
    return (int)Math.sqrt(Math.pow((visibleEntity.xy[0] - me.xy[0]), 2) + Math.pow((visibleEntity.xy[1] - me.xy[1]), 2));
}

I'm looking for suggestions on how to optimize this particular function and or any suggestions of its content.


texts: Bernstein polynomial type for quadratic clipping

texts:
I would like to implement a Bernstein polynomial class in Julia for learning purposes. The goal in the end is to implement the quadratic clipping algorithm from this paper. I am completely new to Julia coming from Python + Numpy + Numba, so I want to make sure that I program in the canonical Julia way when using Julia.

The naming of variables follows the aforementioned paper.

using Polynomials

type Bernstein
    n::Integer
    i::Integer
    α::Real
    β::Real
end
Bernstein(n, i) = Bernstein(n, i, 0., 1.)

Base.string(B::Bernstein) = "Bernstein $(get_p(B))"
Base.show(io::IO, B::Bernstein) = print(io, string(B))
Base.display(io::IO, B::Bernstein) = print(io, string(B))

function get_p(n, i, α=0, β=1)
    @assert β >= α "Invalid interval"
    return (binomial(n, i)
            * poly([α for _ in 1:i])
            * poly([β for _ in 1:(n - i)])
            * (-1)^(n - i)
            / (β - α)^n)
end
get_p(B::Bernstein) = get_p(B.n, B.i, B.α, B.β)

function ∫(p::Poly, α=NaN, β=NaN)
    integrated = polyint(p)
    if isequal(α, NaN) || isequal(β, NaN)
        return integrated
    else
        return integrated(β) - integrated(α)
    end
end

function inner_product(p::Poly, q::Poly, α=0., β=1.)
    @assert β >= α "Invalid interval"
    ∫(p * q, α, β)
end

function inner_product(B::Bernstein, Q::Bernstein)
    @assert B.α >= Q.α "Invalid interval"
    @assert B.β >= Q.β "Invalid interval"
    m, i, n, j, α, β = B.n, B.i, Q.n, Q.i, B.α, B.β
    (β - α)binomial(m, i)binomial(n, j) / ((m + n + 1)binomial(m + n, i + j))
end

# QUESTION: Is it possible to automatically account for commutativity?
(inner_product(p::Poly, B::Bernstein)
 = inner_product(B::Bernstein, p::Poly)
 = inner_product(B.p, p::Poly))

function Base.LinAlg.norm(q::Poly, α=0., β=1.)
    @assert β >= α "Invalid interval"
    √inner_product(q, q) / (β - α)
end

function Base.LinAlg.norm(B::Bernstein)
    √inner_product(B, B) / (B.β - B.α)
end

B = Bernstein(3, 2)
Q = Bernstein(4, 3)

inner_product(B, Q)
norm(B)


texts:
While trying to learn more about arrays in C, I tried to write some code that did the following:

Read a stream of numbers from the stdin and store them in an array
Print the array in the order the numbers have been stored (i.e. print the original array)
Print the array in reversed order
Sort and print the array
Given an array, search whether an entered value is present in an array. If it is present, print the index otherwise print that the value doesn't exist.

It will be great if somebody could review it and let me know how to improve it.

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

static void printArray(int array[],int startIndex,int endIndex){
    if(startIndex < endIndex){
        while(startIndex <= endIndex){
            printf(" %i ",array[startIndex++]);
        }
    }else{
        while(startIndex >= endIndex){
            printf(" %i ",array[startIndex--]);
        }
    }
    printf("\n");
}

static int cmpfunc(const void * a,const void * b)
{
    if(*(int*)a > *(int*)b) return 1; else return -1;
}

static void sortedArray(int* originalArray){
    qsort((void*)originalArray,(sizeof(originalArray)/sizeof(originalArray[0])),sizeof(originalArray[0]),cmpfunc);
    return;
}

static int getIndex(int value,int array[],int size){
    int i;
    for(i = 0;i < size;i++){
        if(array[i] == value){
            return i;
        }
    }
    return -1;
}

static void identifyTheIndices(int *arbitraryArray,int size){
    char buf[10];
    printf("Enter the value to search for..enter q to exit\n");
    while(fgets(buf,sizeof buf,stdin) != NULL){
                if(buf[0] == 'q'){
            break;
        }
        char *end;
        int value = (int) strtol(buf,&end,0);
        if(end != buf){
            int currentIndex = getIndex(value,arbitraryArray,size);
            if(currentIndex > -1){
                printf("Found the entered value %i at index %i\n",value,currentIndex);
            }else{
                printf("Entered value %i doesn't exist\n",value);
            }
        }
    printf("Enter the value to search for..enter q to exit\n");
    }
}

int main(int argc,char **argv)
{
    int counter = 0;
    if(argc > 1){
        int originalArray[argc-1];
        while(counter < (argc - 1)){
            int currentValue = atoi(argv[counter+1]);
            printf("Reading input value %i into array \n",currentValue);
            originalArray[counter] = currentValue;
            counter++;
        }
        int size = sizeof(originalArray)/sizeof(originalArray[0]);
        printf("Printing out the original array\n");
        printArray(originalArray,0,size - 1);
        printf("Printing out the array in reverse\n");
        printArray(originalArray,size - 1,0);
        printf("Sorting the array in ascending order\n");
        qsort((void*)originalArray,size,sizeof(originalArray[0]),cmpfunc);
        printf("Printing out the sorted array\n");
        printArray(originalArray,0,size-1);
        int arr[] = { 47, 71, 5, 58, 95, 22, 61, 0, 47 };
        identifyTheIndices(arr,sizeof(arr)/sizeof(arr[0]));
    }
    return 0;
}


texts: Finding all indices of largest value in an array

texts:
I have the following code that gives me the indices of an array's largest value:

public static void main(String[] args) {

    float[] elementList = new float[7];
    elementList[0] = 8F;
    elementList[1] = 5F;
    elementList[2] = 4F;
    elementList[3] = 3F;
    elementList[4] = 0F;
    elementList[5] = 8F;
    elementList[6] = 6F;
    // findLargestNumberLocations(elementList);
    largestNumbers(elementList);
}

private static void largestNumbers(float[] numbers) {

    float largeNumber = numbers[0];
    for (int i = 0; i < numbers.length; i++) {
        if (numbers[i] > largeNumber) {
            largeNumber = numbers[i];
        }
    }
    for (int j = 0; j < numbers.length; j++) {
        if(largeNumber == numbers[j]){
            System.out.println("largest number index "+j);
        }
    }
}

Is there any optimized way of doing this?


texts: Comparing objects in a list against each other

texts:
I have a list of ~27000 objects. Each object represents a line from a file where each line is one record of a measurement from some instrument.

The most import aspects of the object are:

Instrument name: int (49099, 89, …)
Station Name: string (K-900, MK-45, …)
Time: datetime object (13:34:17  01/02/2017)

All these objects are going to be used in creating a Hierarchical Data Format file where the top most "layer" is a measurement. Each measurement contains multiple line objects which have the same name and have a difference in time within some duration (30 minutes).
 One major problem is that the data files I read to create the line objects are very unstructured. I cannot assume that subsequent lines in one file have anything to do with each other, so I cannot compare each line to the previous line to have some filtering logic in the reading part. Even files that have been generated on the same date SHOULD look similar, just with different instrument name, but this is not the case for this problem.
 That is why I am reading them all in and THEN comparing all lines to each other. But it is taking a very long time and is not scalable at all.

The code provided is what I am currently doing and I would love to hear any improvements I could make or different ways to tackle my problem.

new = []
for i, r in enumerate(self.records):
    x = (y for y in self.records if  y.compare_record_same_name(r))
    if any(r in x for x in new):
        continue
    else:
        new.append(x)

class Record():
    def compare_record_same_name(self, other):
        duration = abs(self.date_time - other.date_time)
        duration = duration.total_seconds()
        return (self.name == other.name and duration < TIME_SEPERATOR
                and duration > 0)


texts: Access case class parameter inside a map with default

texts:
I have a map whose values are case classes, and I want to access one parameter of that case class with a default value if they map doesn't contain the provided key.

myMap.get(myKey).map(_.valueParam).getOrElse(defaultParam)

intellij-scala suggests that this is a "simplifiable operation on collection” -- is there a more idiomatic way to write this?

*

Edit/Answer: The alternative approach would be to use

myMap.get(myKey).fold(defaultParam)(valueParam)


texts: what is the correct way to pass 3 where () conditions in the same function, multiple filters | eloquente - laravel

texts:
see: https://stackoverflow.com/questions/58882690/what-is-the-correct-way-to-pass-3-where-conditions-in-the-same-function-mult/58883277?noredirect=1#comment104033826_58883277 to better understand

based on laravel's documentation, I came up with the following result:

   public function loadpage($name, $page_name, $pcode)
    {
        $company = Company::where('name', $name)->first();
        if ($company === null) {
              return view('company.not_register', compact('name'));
        }
        $page = Page::where([ ['name', $name],
    ['page_name', $page_name],])->first();
        if ($page === null) {
              return view('company.pages.erros.404', compact('name', page));
        }

        $pagecode = Page::where([ ['name', $name],
    ['page_name', $page_name], ['code', $pcode],])->first();
        if ($pagecode === null) {
              return view('company.pages.erros.invalid_code', compact('company, name', page, pcode));
        }

        $personality = DB::table('personalities')->where('name', $name)->first();

         return view('company.pages.index', compact('company', 'name', 'personality', 'page', pcode));
    }

now it's up to colleagues more experienced than me to see if that's right or is it possible to improve / simplify


texts:
I have a model:

class ColumnItsValues
{
    public int PropertyID { get; set; }
    public string ColumnName { get; set; }
    public string ValueOfColumn { get; set; }
}

two collections:

List<ColumnItsValues> listColumns = new List<ColumnItsValues>()
{
   new ColumnItsValues() {ColumnName="GUID", PropertyID=0, ValueOfColumn=null },
   new ColumnItsValues() {ColumnName="Name", PropertyID=1, ValueOfColumn=null },
   new ColumnItsValues() {ColumnName="Reference", PropertyID=2, ValueOfColumn=null },
   new ColumnItsValues() {ColumnName="Group", PropertyID=3, ValueOfColumn=null },
};

List<ColumnItsValues> listValues = new List<ColumnItsValues>()
{
    new ColumnItsValues() {ColumnName=null, PropertyID=1, ValueOfColumn="An user" },
    new ColumnItsValues() {ColumnName=null, PropertyID=2, ValueOfColumn="LIST of USERS" },
    new ColumnItsValues() {ColumnName=null, PropertyID=3, ValueOfColumn="False" },
    new ColumnItsValues() {ColumnName=null, PropertyID=0, ValueOfColumn=" " },
};

That's my linq query:

var fooColl = from columns in listColumns join values in listValues
    on columns.PropertyID equals values.PropertyID
    select new { AColumn = columns.ColumnName, AValue = values.ValueOfColumn };

My question are:

in my view, I should use where operator, but I use equals. Is it correct?
Could you advice me more high-performance query?


texts:
Giving a review to Oachkatzl and recently about some other synchronization problems (Lazy with invalidate and some node-locking list), I wanted to test my skills and redesign it in most light-weight way I can muster.

I am especially concerned about thread-safety here, because there is NO LOCK statement, only Interlocked.CompareExchange in a loop, that is used for event fields anyway. There is only one field - object _state to prevent torn-down reads (e.g. by overwriting sender+args without proper lock and knowing for sure we won to do the invoke).

Having single field also makes me consider changing this all to struct, because it will be used as private field for public event anyway.

Last thing I was thinking about was to maybe remove the runtime-typechecks (state is Invoked), but do not think it is worth it (would probably need wrapping the delegates in another class and using interface or common base class).

/// <summary>
/// Thread-safe event manager that ensures that subscribers get notified once after the event happens,
/// even if the event already happened.
/// </summary>
/// <typeparam name="Sender">Sender of the event</typeparam>
/// <typeparam name="Args">Additional arguments passed to subscribers</typeparam>
public class OneShotEvent<Sender, Args>
{
    public delegate void Handler(Sender sender, Args args);

    // helper class to store sender and args when invoked
    private class Invoked
    {
        public Sender sender;
        public Args args;
        public Invoked(Sender sender, Args args)
        {
            this.sender = sender;
            this.args = args;
        }
    }

    // Delegate (subscribers) or Invoked (sender and args)
    private object _state;

    /// <summary>
    /// Subscribers will be notified once after the event happens,
    /// can be notified immediately if the event already happened.
    /// </summary>
    public event Handler Event
    {
        add
        {
            var state = _state;
            object prev;
            do
            {
                if (state is Invoked invoked)
                {
                    value(invoked.sender, invoked.args);
                    return;
                }
                prev = state;
                state = Interlocked.CompareExchange(ref _state, Delegate.Combine((Delegate)state, value), prev);
            }
            while (prev != state);
        }
        remove
        {
            var state = _state;
            object prev;
            do
            {
                if (state is Invoked)
                    return;
                prev = state;
                state = Interlocked.CompareExchange(ref _state, Delegate.Remove((Delegate)state, value), prev);
            }
            while (prev != state);
        }
    }

    /// <summary>
    /// Notify subscribers if not already done.
    /// </summary>
    /// <param name="sender">Sender of the notification</param>
    /// <param name="args">Arguments of the notification</param>
    /// <returns>true if no invoke was called before, false if already invoked</returns>
    public bool TryInvoke(Sender sender, Args args)
    {
        var state = _state;
        if (state is Invoked)
            return false;

        var invoked = new Invoked(sender, args);
        object prev;
        do
        {
            prev = state;
            state = Interlocked.CompareExchange(ref _state, invoked, prev);
            if (state is Invoked)
                return false;
        }
        while (prev != state);

        ((Handler)state)?.Invoke(sender, args);
        return true;
    }
}