texts:
I used the Bootstrap v4.0.0 accordion to display my business services. Further, I created a custom post type "service" for my services (Each service is a post).
To display my services dynamically and not hardcode them, I implemented a for-loop within the WordPress while-loop which uses an enumeration to provide the number of the collapsible.
I don't like my solution, especially the enumeration - Is there a better way to solve this?
If you see any other improvement, I would be glad to hear also.
See my code below:

All Services

                        <?php $wv_services = new WP_Query( array(
                            'posts_per_page' => -1,
                            'post_type'      => 'service',
                            'orderby'        => 'date',
                            'order'          => 'ASC'
                        ) );

                        while ( $wv_services->have_posts() ) {

                            $enum_of_collapsible_str_numbers = [
                                "One",
                                "Two",
                                "Three",
                                "Four",
                                "Five",
                                "Six",
                                "Seven",
                                "Eight",
                                "Nine",
                                "Ten",
                                "Eleven",
                                "Twelve",
                                "Thirtenn",
                                "Fourteen",
                                "Fivteen",
                                "Sixteen",
                                "Seventeen",
                                "Eighteen",
                                "Nineteen",
                                "Twenty"
                            ];
                            $total_number_of_service_posts = wp_count_posts('service')->publish;
                            for ($collapsible_str_number = 0; $collapsible_str_number < $total_number_of_service_posts; $collapsible_str_number++) {

                                $wv_services->the_post(); ?>

                                <div class="card-header collapsed" style="cursor:pointer;" data-toggle="collapse"
                                     href="#collapse<?php echo $enum_of_collapsible_str_numbers[$collapsible_str_number] ?>" rel=”nofollow”>

<?php the_title(); ?>

                                <div id="collapse<?php echo $enum_of_collapsible_str_numbers[$collapsible_str_number] ?>" class="card-body collapse"
                                     data-parent="#accordion">

<?php the_content(); ?>

                            <?php }
                        }
                        wp_reset_postdata();
                        ?>


texts:
I am trying to write an efficient loop for rendering a jQuery Mobile listview.  Is this the most efficient loop?  I append elements 100 at a time to try and allow the user to see progress without blocking the UI.  This currently still needs work.

I also use a blend of html strings and jQuery DOM objects.  I'm not sure about the performance cost.

What are your thoughts? Assume items could be an array of 600/700 items.

/**
 * Renders the passed in list items into a JQM listview.
 * @param items {Array{Objects}} - An array of key/value objects
 */
function renderSourceItems(items)
{
    var content = $page.find(".content");

    if (!items)
    {
        content.html('
No Data Found
');
    }
    else
    {
        var column,
            value,
            list,
            markup = "";

        column = _.keys(items[0])[0]; // The key is the database column

        content.empty();

        $('
', {
            "data-role" : "listview",
            "data-filter": "true",
            "data-theme" : "c"
        }).appendTo(content).listview();

        list = content.find('ul');

        for (var i = 0; i < items.length; i++)
        {
            value = items[i][column];
            markup += '
' + (value || "[No Value]") + '
';

            if (i % 100 === 0)
            {
                list.append(markup).listview("refresh");
                markup = "";
            }
        }

        // refresh triggers the page to adjust its sizes,
        // otherwise long lists can force the footer navbar to the bottom of the list intead of the screen bottom.
        list.append(markup).listview("refresh");
    }
}


texts: Refactoring binary search algorithm in Ruby

texts:
I wrote the binary search algorithm with Ruby, the code is below. The question is if there's any way to make it look cleaner?

def binary_search(sample_array, x, l, r)
  mid = (l + r)/2
  return -1 if r < l
  return binary_search(sample_array, x, l, mid-1) if (sample_array[mid] > x)
  return binary_search(sample_array, x, mid+1, r) if (sample_array[mid] < x)
  return mid if (sample_array[mid] == x)
end

result = binary_search(sample_array, x, l, r)
puts "#{result}"

It seems to me that returns can be minimised or even some more Ruby idioms added. Tried to use lambda, but smth went wrong.


texts:
I'm just getting my feet on the ground with Python (maybe 3 days now). The only issue with teaching my self is that I have no one to critique my work.

Correct me if I'm wrong but I think my algorithm/method for solving this problem is quite promising; but, the code not so much.

The program basically strips a web-page and puts it in to the designated directory. My favorite part is the method for deciding the image's extensions :)

import os, re, urllib

def Read(url):
    uopen = urllib.urlopen(url)
    uread = ''
    for line in uopen: uread += line
    return uread

def Find(what, where):
    found = re.findall(what, where)
    match = []
    for i in found:
        i = i[9:-1]
        match.append(i)
    return match

def Retrieve(urls, loc):
    loc = os.path.realpath(loc)
    os.system('mkdir ' + loc +'/picretrieved')
    loc += '/picretrieved'
    x = 0
    exts = ['.jpeg', '.jpg', '.gif', '.png']
    for url in urls:
        x += 1
        for i in exts:
            ext = re.search(i, url)
            if ext != None:
                ext = ext.group()
                urllib.urlretrieve(url, loc + '/' + str(x) + ext)
            else:
                continue

    print 'Placed', str(x), 'pictures in:', loc

def main():
    url = raw_input('URL to PicRetrieve (google.com): ')
    url = 'http://' + url
    loc = raw_input('Location for PicRetrieve older ("." for here): ')
    html = Read(url)
    urls = Find('img src=".*?"',  html)
    print urls
    Retrieve(urls, loc)

if __name__ == '__main__':
    main()


texts: Is there a better way to update fields in an web app?

texts:
This is the stripped down version of my update action for a Posts (blog post) controller:

Posts.update = function(req, res){
    _.extend(req.post, {
        title: req.body.title
    ,   author: req.body.author
    ,   body: req.body.body
    });
    post.save();
};

This way feels a bit clumsy and repetitive, because I have similar code in another method, but I don't want to just straight up _.extend(req.post, req.body) because it may allow someone to change fields that shouldn't be changed  in my models.

Is there a better middle ground?


texts: Find the second largest number in an array with at most n + log2 n - 2 comparisons

texts:
This exercise is from Roughgarden's (excellent) course on algorithms on Coursera:

  You are given as input an unsorted array of n distinct numbers, where
  n is a power of 2. Give an algorithm that identifies the
  second-largest number in the array, and that uses at most \$n + \log_2(n) - 2 \$ comparisons.

Note that it doesn't ask just ask to solve the problem in linear time. If we use \$2 n\$ comparisons the "big-O" time complexity would be linear but greater than \$n + \log_2(n) - 2\$.

Any feedback on the algorithm, implementation, style, and Python is very welcome.

import random
import sys

from math import log
count = 0
def is_greater(a, b):
    global count
    count += 1
    return a > b

def _get_highest_two(arr0, arr1):
    if is_greater(arr0[0], arr1[0]):
        first = arr0[0]
        seconds = arr0[1]
        seconds.append(arr1[0])
    else:
        first = arr1[0]
        seconds = arr1[1]
        seconds.append(arr0[0])
    return (first, seconds)

def get_second(*args):
    if len(args) == 1:
        seconds = args[0][1]
        second_best = seconds.pop()
        for sb in seconds:
            if is_greater(sb, second_best):
                second_best = sb
        return second_best

    _pairs = zip(*[iter(args)]*2)
    _out = [_get_highest_two(*p) for p in _pairs]
    return get_second(*_out)

def main():

    n = int(sys.argv[1])
    arr = [random.randint(0,100000000) for _ in xrange(n)]

    print arr
    print n, sorted(arr)[-2]
    print count
    # is_greater(0,0)
    _pairs = zip(*[iter(arr)]*2)
    _pairs = [(a, [b]) if is_greater(a, b) else (b, [a]) for (a, b) in  _pairs]
    print get_second(*_pairs)
    print count, n + log(n, 2) - 2

    return 0

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


texts: Fetching settings for batches of wafers using loops

texts:
I have this code below that needs to query multiple database tables.

import mysql.connector
import itertools, time
cnx = mysql.connector.connect(host="host", port=3306, user="user", passwd="pass", db="factory")

cursor = cnx.cursor()

cursor.execute("select distinct(batch) from batchdata where equipment = 'DUV001'")
batch = cursor.fetchall()
cursor.execute("select distinct(settingname) from runsettings where runnumber = 1 and equipment = 'DUV001'")
settings = cursor.fetchall()

start =  time.time()

settings = list(itertools.chain(*settings))
batches = list(itertools.chain(*batch))

lstoflst = []
for batch in batches:
    cursor.execute("select distinct(wafer) from batchdata where batch=%s and equipment = 'DUV001'",(batch,))
    wafers = cursor.fetchall()
    wafers = list(itertools.chain(*wafers))

for wafer in wafers:
    waflist = {}
    for i in settings:
        cursor.execute("select float8value from runsettings where settingname = %s and wafer = %s",(i,wafer))
        vals = cursor.fetchall()
        waflist[i] = vals[0][0]

    lstoflst.append(waflist)

print time.time() - start

I know there are a lot of things to improve like:

Error handling
Database connection
prepared statements on the query

But I want to focus first on the performance of this code. It works fine, but its taking at least 5 to 10 seconds minimum before it can finish running the loop.

In what way can I improve the performance of the code above?


texts:
I was working on a little Python challenge that was a bit more difficult than expected: format any non-negative number so 1000 turns into "1,000" , 10000000 into "10,000,000" and so forth. I managed to do it, but I find my solution not very readable:

def formatting(n):
    m = str(n)  # Turn it into string
    m2 = []  # Empty list that will have the split version of the final number
    for i in range(0,len(m),3):  # Iterate every three elements

        m2.append(m[::-1][i:i+3][::-1])  # Append last three numbers, second to last three numbers, etc.
        m2.append(',')  # Add a comma between loops
    m3 = ''.join(m2[::-1])[1:] # Join and drop the first element which is always a comma.
    return m3

This works but it isn't as nice as it could be. What can be done?


texts:
To create a Logging system for a larger application, I came up with the following draft. The log sinks aren't detailed yet, but the factory method for logger creation and a rough draft of the logger itself are. Is this a good start and worth continuing? Or are there pitfalls you can see?

class LoggingSink; // abstract base class
class ConsoleSink : public LoggingSink; // some concrete logging sink
class LogfileSink : public LoggingSink; // ... too

/***********************************************/
class Logger {
public:
    void log(const std::string& msg) {
        for (LoggingSink ls : Sinks)
            ls.log(msg);
    }

private:
    std::list<std::reference_wrapper<LoggingSink>> Sinks;
    friend class LoggerFactory;
};

/***********************************************/
class LoggerFactory {
public:
    std::unique_ptr<Logger> create() {
        std::unique_ptr<Logger> result = std::make_unique<Logger>();
        result->Sinks.assign(StandardAssignedSinks.begin(), StandardAssignedSinks.end());
        return result;
    }

    void addStandardSink(LoggingSink& ls) {
        Sinks.push_back(std::reference_wrapper<LoggingSink>(ls));
    }

private:
    std::list<std::reference_wrapper<LoggingSink>> StandardAssignedSinks;
};

/***********************************************/
int main() {
    ConsoleSink cs;
    LogfileSink lfs("mylogfile.txt");

    LoggerFactory lf;
    lf.addStandardSink(cs);  // adding as reference for polymorphism
    lf.addStandardSink(lfs); // perhaps the addition of some standard sinks should be done in the constructor of LoggerFactory???

    std::unique_ptr<Logger> myLogger = lf.create();

    myLogger->log("Hello Log, I'm going to be injected soon!");
    MyClass myClassInstance(myLogger); // constructor dependency injection

    MyClass myOtherInstance(lf.create()); // direct DI
}

I'm also unsure about the friend class. This is something I never really liked with factories. Any ideas how to improve here?


texts: Positioning link boxes & managing backgrounds

texts:
I've managed to position the link boxes as I wanted and to apply a background to them, but I'm not sure I've done it in the most elegant or efficient way.

Is there a  better way to position the elements without mixing positioning and floats? And is there a way to remove the background between the link boxes without having to turn it off in the section and turn it on again for the boxes? Or any other suggestions?

I've only been coding for a few months, but I aspire to write nice shiny code.

jsfiddle link

Title

Lorem ipsum dolor sit amet.

Title

Lorem ipsum dolor sit amet.

Title

Lorem ipsum dolor sit amet.

section {
    width: 1000px;
    margin: 1em auto;
    background: #C3C3C3 url(images/background.png);
    overflow: hidden;
    border-radius: 5px;
}

.three, .five {
    background: none;
}

.link-box {
    position: relative;
    display: block;
    float: left;
    text-decoration: none;
    color: #333;
    border-radius: 5px;
    width: 300px;
    background: #C3C3C3 url(images/background.png);
}

.left-link {
    float: left;
}

.right-link {
    float: right;
}

.middle-link {
    left: 5%;
}


texts: Python - Input Filtering, Calculating with a Variable Amount of Inputs

texts:
I've been working on an Aerodynamics calculator using python (which I'm relatively new at), In this program, a value can be calculated based on multiple different inputs ie. a calculates b, b calculates c, or c can find b and b can find a.
To elaborate on the function of this program it will loop through it's logic until it has found all the things it could with the given input(s). The code is pretty long for it's function and that's why I'd like to see if it could be optimized or if I could do anything better. For the input method, the input is a string. The code is as follows:
def Find_Pressure(temp):
    pressure = (101.29 * (((temp + 273.1) / 288.08) ** 5.256))
    return pressure

def Find_Temp_Alt(alt, ground_temp):
    Temp = ground_temp - (0.00649 * alt)
    return Temp

def Find_Density(pressure, temp):
    density = (pressure / (0.2869 * (temp + 273.1)))
    return density

def Find_Alt_Temp(temp, ground_temp):
    Alt = ((ground_temp - temp) / 0.00649)
    return Alt

def is_Valid(x):
    try:
        float(x)
        return True
    except ValueError:
        return False

def Parser(ground_temp, temp, alt, pressure, density):
    a = t = p = d = False
    run = True
    Alt = Temp = Pressure = Density = "N/A"
    if is_Valid(alt):
        Alt = float(alt)
        a = True
    if is_Valid(temp):
        Temp = float(temp)
        if Temp <= -273.1:
            t = False
        else:
            t = True
    if is_Valid(pressure):
        Pressure = float(pressure)
        p = True
    if is_Valid(density):
        Density = float(density)
        d = True

    if not is_Valid(ground_temp):
        print('Enter Ground Temp')
    else:
        G_T = float(ground_temp)
        while run:
            run = False
            if a and not t:
                Temp = Find_Temp_Alt(Alt, G_T)
                t = True
                run = True

            if t and not a:
                Alt = Find_Alt_Temp(Temp, G_T)
                a = True
                run = True

            if p and not t:
                Temp = ((288.08 * ((Pressure / 101.29) ** (1 / 5.256))) - 273.1)
                t = True
                run = True

            if t and not p:
                Pressure = Find_Pressure(Temp)
                p = True
                run = True

            if (p and t) and not d:
                Density = Find_Density(Pressure, Temp)
                d = True
                run = True
            if (d and t) and not p:
                Pressure = (Density * 0.2869 * (Temp + 273.1))
                p = True
                run = True

            if (d and p) and not t:
                Temp = ((Pressure / Density * 0.2869) - 273.1)
                t = True
                run = True
        return Alt, Temp, Pressure, Density

I apricate any help/feedback, thanks in advance!


texts:
In react I have a HTML Element Factory, it allows several different types of form elements to be created most with the same onChange but some have specific uses. I have been capturing them in this switch, but its time to refactor, what should an onChange() switch be converted to, should this too be a factory? Or just a object literal with functions? Or should I use a Factory Function here?
Some rough code advice would be very useful.
 const onChange = (event: any, tags: any, formEl: any) => {
    setLayout(
      layout?.map((el: IElement) => {
        if (el.id === formEl.id) {
          switch (formEl.type) {
            case "autocomplete" :
            case "autocompletewide": {
              if (event.target.getAttribute("data-option-index") !== null) {
                el.value =
                  formEl.options[
                    event.target.getAttribute("data-option-index")
                  ].id;
                return el;
              } else {
                el.value = "";
                return el;
              }
            }
            case "autocompletemulti": {
              if (tags.length) {
                const vals: string = tags.map((tag: IOption) => tag.id);
                el.value = vals.toString();
                return el;
              } else {
                el.value = "";
                return el;
              }
            }
            case "datepicker": {
              let dateValue: Date | null = event;
              if (dateValue !== null)
                el.value = dateValue?.toISOString().substr(0, 10);
              else el.value = "";
              return el;
            }
            default: {
              el.value = event.target.value;
              return el;
            }
          }
        } else {
          return el;
        }
      })
    );
  };


texts: Enums with different methods, useful or abuse?

texts:
I'm wondering if the way I wrote our TextHelper class is a really a proper way to do it.
We have products that are interlinked in different ways and every product has multiple text fields that might be empty.

Now depending on where the text is supposed to show up, we want different texts.
A simple example would be:
On the product detail page it should show the shop specific text, if not available, the main description, if that is not available, the main description of it's parent product and the short description of the parents' subproducts.

So much for the motivation. I tried to shorten and simplify the code as much as I could. Is this a good way to use enums or should this be done completely different?

public class ProductTextHelper {
    public static String getTextInOrder(TextType[] order, IProduct p) {
        for (TextType t : order) {
            if (!t.getText(p).equals(""))
                return t.getText(p);
        }
    }

    public enum TextType {
        text1 {
            public String getText(IProduct p) {
                return p.getText1;
            }
        },
        text2 {
            public String getText(IProduct p) {
                String t = p.getText2;
                return t.equals("") ? "" : t + TextType.text1.getText(p);
            }
        },
        text3 {
            public String getText(IProduct p) {
                StringBuilder sb = new StringBuilder();
                sb.append(p.getText3());
                for (IProduct subP : p.getRelatedProducts()) {
                    sb.append(TextType.text2.getText(subP));
                }
            }
        },
        // more enums

        public static final TextType[] useCase1 = {text1, text2};
        public static final TextType[] useCase2 = {text4, text1, text3};
        public static final TextType[] useCase3 = {text3, text2};
        // a few more arrays

        public abstract String getText(IProduct p);
    }
}

And this gets called like that:

ProductTextHelper.getTextInOrder(TextType.usecase2, product);


texts:
Teachers can raise 'dramas' which are when students forget equipment, don't do homework or are flagged for concern. Each drama for each student is stored as a separate record.

I seek a list of all unresolved dramas, grouped by student & date. So if on one day a student forgets their homework and doesn't have equipment, they come up as a single record with the properties EquipmentDrama and HomeworkDrama both set to true.

var dramas = ctx.Dramas.Where(o => !o.Resolved).Select(o => new
  {
    o.Id,
    o.StudentUsername,
    o.Student.FirstName,
    o.Student.LastName,
    o.Student.TutorGroup,
    o.Student.ClassName,
    TeacherName = o.Teacher.FirstName + " " + o.Teacher.LastName,
    o.DramaType,
    o.DateForDetention,
    o.DateHappened
  }).ToLookup(o => o.StudentUsername + o.DateHappened.ToString("ddMMyy"), o => o);
var students = dramas.Select(o => o.Key).Distinct().Select(o => dramas[o].ToList()).Select(o => new FollowUpItem
  {
    Id = String.Join(",", o.Select(d => d.Id)),
    FirstName = o[0].FirstName,
    LastName = o[0].LastName,
    TutorGroup = o[0].TutorGroup,
    EquipmentDrama = o.Any(d => d.DramaType == DramaType.Equipment),
    HomeworkDrama = o.Any(d => d.DramaType == DramaType.Homework),
    IsFlagged = o.Any(d => d.DramaType == DramaType.Flagged),
    ClassName = o[0].ClassName,
    TeacherName = o[0].TeacherName,
    DateForDetention = o[0].DateForDetention,
    DateHappened = o[0].DateHappened
  }).ToList();

Note the reason for using an anonymous type in the first LINQ statement is that I want to retrieve the related fields o.Teacher.FirstName and o.Teacher.LastName in the initial (only) database call. There must be a better way of doing this though!


texts: Switch statement for adding/removing operands to the text part of a label

texts:
I have a switch statement with five cases, and four of them are really similar to the others. How could I properly refactor this code to eliminate the duplication of code?

func appendOperand(operand: Operand) {
    let displayedString = amountLabel.text!
    if displayedString.last != decimalSeparator {
        switch operand {
        case Operand.Div:
            if division {
                dropLastChar()
            } else {
                if multiplication || subtraction || addition {
                    dropLastChar()
                }
                appendOperand(buttonDivision, operand: &division, operandName: "/")
            }
        case Operand.Mult:
            if multiplication {
                dropLastChar()
            } else {
                if division || subtraction || addition {
                    dropLastChar()
                }
                appendOperand(buttonMultiplication, operand: &multiplication, operandName: "x")
            }
        case Operand.Sub:
            if subtraction {
                dropLastChar()
            } else {
                if division || multiplication || addition {
                    dropLastChar()
                }
                appendOperand(buttonSubtraction, operand: &subtraction, operandName: "-")
            }
        case Operand.Add:
            if addition {
                dropLastChar()
            } else {
                if division || multiplication || subtraction {
                    dropLastChar()
                }
                appendOperand(buttonAddition, operand: &addition, operandName: "+")
            }
        default:
            break
        }
    }
}

func appendOperand(button: UIButton, inout operand: Bool, operandName: String) {
    setAllOperatorsToFalse()
    operand = true
    wasDecimalAmount = isDecimalAmount
    isDecimalAmount = false
    setDisplayWith(operandName)
}

func dropLastChar() {
    isDecimalAmount = wasDecimalAmount
    setAllOperatorsToFalse()
    let displayedString = dropLast(amountLabel.text!)
    amountLabel.text! = displayedString
    calculatorMode = displayedString.rangeOfString("[x/+-]", options: .RegularExpressionSearch) != nil
}

func setAllOperatorsToFalse() {
    division = false
    multiplication = false
    subtraction = false
    addition = false
    equal = false
}

enum Operand {
    case Div, Mult, Sub, Add, Equal
}

I thought at first making a method that would do everything that is in each case but then I would end up with a lot of arguments for the method.

Another problem I'm facing is the multiplication || subtraction || addition part. If addition == true, multiplication, subtraction and addition are false for example. I am sure there is a more elegant way to do this.

EDIT:

So here is my calculator:

Every time one of the operand (x, +, / or -) is pressed, appendOperand(operand: Operand) is called:

@IBAction func buttonPressed(sender: UIButton) {
    switch sender.tag {
        // operands
    case Tag.Add.rawValue:
        appendOperand(Operand.Add)
    case Tag.Sub.rawValue:
        appendOperand(Operand.Sub)
    case Tag.Mult.rawValue:
        appendOperand(Operand.Mult)
    case Tag.Div.rawValue:
        appendOperand(Operand.Div)
    case Tag.Equal.rawValue:
        appendOperand(Operand.Equal)

    default:
        break
}

It adds the operand at the end of the string displayed in the label ("96x" in my example on the screenshot).

I use these flags for each operator to manage if whether or not the operand button has been pressed before. For example, if I press x, then x will appear on the label. If / was pressed right before, / will be removed from the label before adding x. Or if I pressed x and press it again, x will be removed from the label as if I never pressed it.

These operator are declared on top of the UIViewController:

var addition: Bool = false
var subtraction: Bool = false
var multiplication: Bool = false
var division: Bool = false
var equal: Bool = false


texts: MembershipProvider with Entity Framework and IoC

texts:
I am using Castle Windsor as my IoC container and I registered it as a DependencyResolver to let the MVC framework know about it.

With the Entity Framework I have this DbContext:

public class MyDbContext : DbContext
{
    public DbSet<User> Users { get; set; }
}

In Castle Windsor it is registered as per web request:

container.Register(
    Component.For<DbContext, MyDbContext>()
             .ImplementedBy<MyDbContext>()
             .LifestylePerWebRequest()
);

Because I don't have control over creating the MyMembershipProvider object, this object is created once per web application so it is not possible to inject DbContext directly, because it will be disposed when the web request ends.

I wrote this as a solution:

public interface IDoInContext<TContext>
{
    void DoInContext(Action<TContext> action);
}

public class DoInMyDbContext : IDoInContext<MyDbContext>
{
    IKernel _kernel;

    public DoInMyDbContext(IKernel kernel)
    {
        _kernel = kernel;
    }

    public void DoInContext(Action<MyDbContext> action)
    {
        var context = _kernel.Resolve<MyDbContext>();
        action(context);
        _kernel.ReleaseComponent(context);
    }
}

And I registered like this:

container.Register(
    Component.For<IDoInContext<MyDbContext>>()
             .ImplementedBy<DoInMyDbContext>()
             .LifestyleSingleton()
);

Now I can create a MyMembershipProvider which will be able to interact with the current and correct DbContext every time it needs:

public class MyMembershipProvider : MembershipProvider
{
    IDoInContext<MyContext> db;

    public MyMembershipProvider()
        : this(DependencyResolver.Current.GetService<IDoInContext<MyContext>>())
    { }

    public MyMembershipProvider(IDoInContext<MyContext> db)
    {
        this.db = db;
    }

    public override bool ValidateUser(string username, string password)
    {
        bool result = false;
        db.DoInContext(x => {
            var encodedPassword = encodePassword(password);
            result = x.Users.Any(y => y.Login == username &&
                                      y.Password == encodedPassword);
        });
        return result;
    }

    ...
}

It seems to be stable and I can't see any memory leaks or any other problems. What do you think? Is the DoInContext(Action<TContext> action) thing any sort of pattern, anti-pattern or bad practice?


texts: Euclid's Algorithm (Greatest Common Divisor)

texts:
According to Donald Knuth in "The Art Of Computer Programming", the following is how to find the greatest common divisor of two positive numbers, m and n, using Euclid's Algorithm.

  Divide m by n and let r be the remainder.
  If r is 0, n is the answer; if r is not 0, continue to step 3.
  Set m = n and n = r. Go back to step 1.

Below is my implementation of this algorithm.

#include <stdio.h>

int greatestCommonDivisor(int m, int n)
{
    int r;

    /* Check For Proper Input */
    if((m == 0) || (n == 0))
        return 0;
    else if((m < 0) || (n < 0))
        return -1;

    do
    {
        r = m % n;
        if(r == 0)
            break;
        m = n;
        n = r;
    }
    while(true);

    return n;
}

int main(void)
{
    int num1 = 600, num2 = 120;
    int gcd = greatestCommonDivisor(num1, num2);

    printf("The GCD of %d and %d is %d\n", num1, num2, gcd);

    getchar();
    return 0;
}

Though it appears to work just fine, it doesn't seem to be as elegant as I'd like, especially in the do-while loop.  Also, the while(true) seems dangerous, though I'm pretty confident that r will be reduced to 0 eventually and we'll break out of the loop.

Do you have any suggestions on either making the code more elegant or robust?


texts:
Motivation

const_cast is a beast that I seldomly encounter. But when I do so it is mostly a bad experience.

Nobody knows what most of the C++ programmers do but so far I only ever had one use for const_cast: to cast away a const from a type. For this task const_cast is too verbose:

const std::vector<int> constVectorOfInts = {/*...*/};
// never do this in real code!
auto &mutableVectorOfInts = const_cast<std::vector<int>>(constVectorOfInts);

IMHO, there is no gain in readability when repeating the type.

Enter my proposal:

unconst_cast

We can write a template function unconst_cast that solves only the problem of removing const.

/**
 * @brief Returns a mutable reference to the same object
 */
template <class T> T &unconst_cast(const T &v) { return const_cast<T &>(v); }

/**
 * @brief Returns a mutable pointer to the same object
 */
template <class T> T *unconst_cast(const T *v) { return const_cast<T *>(v); }

int main() {
  int i;
  const int *constPointerToI = &i;
  int *unconstPointerToI = unconst_cast(constPointerToI);
  unconstPointerToI = unconst_cast(&i);
  int &unconstReferenceToI = unconst_cast(*constPointerToI);
  int &unconstReferenceToI2 = unconst_cast(i);
}

Our code from above would become:

auto &mutableVectorOfInts = unconst_cast(constVectorOfInts);

Other pros:

can overload for other types (in contrast to const_cast), e.g. for own iterators (mutableIterator = unconst_cast(constIterator))
we find usages when string searching for "const_cast"

Review Goals

Is this a bad idea?
Is my implementation correct?
Is the naming alright/understandable?


texts: Guessing a number, but comments concerning

texts:
I always get marked down for my comments and I just wanted to see if these comments are acceptable or what I should include/where I should include them.

import java.util.*; //so I can use scanner

public class GuessingGame {
   public static void main(String[] args) {

      Random rand = new Random ();
      int max = 100; //sets limit on the random number generator
      Scanner input = new Scanner(System.in);
      int guess;//so I can compare console input to random number
      boolean play = true;
      int totalGames = 0;
      int totalGuesses = 0;
      int bestGame = Integer.MAX_VALUE;

      System.out.println("Can you guess the word?");
      System.out.println("I am sure you cannot guess!");
      System.out.println("Go ahead and try!");
      System.out.println();

      while (play) { //so game will restart after a win

         System.out.println("I'm thinking of a number between 1 and " + max + "...");
         int numberToGuess = rand.nextInt(max) + 1;
         int numberOfTries = 0;
         //so user can continue guessing until correct
         boolean win = false;
         while (!win) {

            System.out.print("Your guess? " + numberToGuess);
            guess = input.nextInt();
            numberOfTries++;

            if (guess == numberToGuess) {
               win = true;
            } else if (guess > numberToGuess) {
               System.out.println("It's lower.");
            } else if (guess < numberToGuess) {
               System.out.println("It's higher.");
            }
            input.nextLine();
         }

         if (numberOfTries == 1) {
            System.out.println("You got it right in " + numberOfTries + " guess!");
         } else {
            System.out.println("You got it right in " + numberOfTries + " guesses!");
         }

            totalGames++;
            totalGuesses+= numberOfTries;
            System.out.print("Do you want to play again? ");

            //so user can choose to play another game

            String answer = input.nextLine();
            char firstLetter = answer.charAt(0);
            if (firstLetter == 'y' || firstLetter == 'Y') {
            play = true;
            } else {
            play = false;
         }

         bestGame = Math.min(bestGame, numberOfTries);
         System.out.println();
      }

      System.out.println("Overall results:");
      System.out.println("Total games   = " + totalGames);
      System.out.println("Total guesses = " +  totalGuesses);
      System.out.printf("Guesses/game  = %.1f \n", totalGuesses/(double)totalGames);
      System.out.println("Best game     = " + bestGame);
   }
}


texts: Is my design achieving Separation of Concerns in this MVC implementation?

texts:
I've read lots about getters and setters being evil, unless there is good call for one, but I cannot figure out how to implement that knowledge into my Model layer.

Say in my Model layer I have a class that has services like:

findStudentsByID($searchCriteria)
findStudentsByLastName($searchCriteria)

...

Do I require a getter or a setter, say $searchCritera, here so I can maintain Separation of Concerns?

Would it be wrong to simply query the model from the view with findStudentsByID(4);?  Wouldn't that bind the two too much?

I thought I could use at least a setter so I can change the state of the class and then use a method.

For example,

API enforcement:

interrace IModel{
 public function setCriteria($searchCriteria);
 public function findStudentByID();
 public function findStudentByLastName();
}

In my model:

    class Model implements IModel{

    private $searchCriteria;

    public function setCriteria($searchCriteria){
      $this->searchCriteria = $searchCriteria;

    }

    public function findStudentByID(){
     some SQL "WHERE student_id = " $this->searchCriteria;
     return $results;
    }

    public function findStudentsByLastName(){
     some SQL "WHERE last_name = " $this->searchCriteria;
     return $results;
    }

    }

In my controller:

interface IController{
  public function someAction($searchCriteria);
}

class Controller implements IController{

    private $model;

    public function __construct(IModel $model) {
        $this->model = $model;
    }

//for argument say this is from a front controller passing the value
public function someAction($searchCriteria){

$this->model->setCriteria($searchCriteria);  //model state is changed

}

}

In my view:

interface IView{
  public function students();
}
class View implements IView{
  private $model;
  public function __construct(IModel $model){
    $this->model = $model;
  }

  public function students(){
    return $this->model->findStudentsByLastName();
    require_once("some_template_somewhere");  //get my template
  }

}

some template:

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Form Example</title>

Students

      <?php foreach($this->view->students() as $student) { ?>

            <?PHP echo $student["student_id"] ?>

            <?PHP echo $student["LAST"] ?>

    <?PHP } ?>

Implementation:

//some starting point:

$model = new Model();
$controller = new Controller($model);
$view = new View($model);

$controller->someAction($_GET['myAction']);  //changing model state;

$this->view->students();

Do I really need the view there?  Would it be better to simply use this in a view/template (yes, I know they're different)?

  <?php foreach($this->view->model->findByStudentID(4) as $student) { ?>

        <?PHP echo $student["student_id"] ?>

        <?PHP echo $student["LAST"] ?>

<?PHP } ?>

The only thing I can see that will help with future maintainability, which is why I want my separation of concerns to begin with, is that I can switch the layers/concerns without breaking the other layers/concerns.  The interface will make sure I have the setCriteria, etc.

From what I can see

I could switch out the model.
I could switch out the template.
I could switch out the controller.

But say someone makes their own Model.  If they create an additional function, won't that break everything, rippling up?  What if they implement only the stock functions in my model, but they return different information?  I didn't really want a separate layer in my model layer, I thought I had abstracted myself to death already, though I feel like I might be slightly better off with abstract classes instead of interfaces.

EDIT:  I changed the method being called to finding the students by last name so the example makes more sense.


texts:
I am currently doing Encoding on Dropdownlist in our project.

Could you please review and provide your comments about the following approach?  After the encoding on dropdown, if there are any special characters it is displaying in the form of encoded characters, please let me know is there any better approach than this.

// raising the databound event to to encoding
protected void ddlCountry_DataBound(object sender, EventArgs e)
{
    if (ddlCountry.Items.Count > 0)
    {

        foreach (ListItem list in ddlCountry.Items)
        {
            list.Text = EncodeDropDownItem(list.Text);
        }
    }
}

//below are the methods to do encoding
//encoding with antixss's htmlencode method
private string EncodeDropDownItem(string DropdownText)
{
    return Replacecharacters(AntiXss.HtmlEncode(DropdownText));
}

//below method will replace the antixsstags with normal character.
private string Replacecharacters(string value)
{
    string dropdowntext;
    StringBuilder sb = new StringBuilder(value);

    sb.Replace("&#38;", "&");
    sb.Replace("&#60;", "<");
    sb.Replace("&#62;", ">");
    sb.Replace("&#34;", "\"");
    sb.Replace("&#92;", "\\");
    return dropdowntext = sb.ToString();
}


texts: Programming challenge "Friend Request in Social Network"

texts:
I am trying to solve a programming problem on a coding platform. When I execute it on my PC, it works perfectly, but when I submit the code on the coding platform, it throws a "Time Limit Exceeded" error. Can someone check my solution and help optimize it?

  In a social network, a person can invite friends of his/her friend.
  John wants to invite and add new friends. Complete the program below
  so that it prints the names of the persons to whom John can send a
  friend request.

  Input format:

  The first line contains the value of the N which represent the number
  of friends. N lines contain the name of the friend F followed by the
  number of friends of F  finally their names separated by space.

  Input:

3
Mani 3 Ram Raj Guna
Ram 2 Kumar Kishore
Mughil 3 Praveen Naveen Ramesh

  Output:

Raj Guna Kumar Kishore Praveen Naveen Ramesh

  Explanation:

  Ram is not present in the output as Ram is already John's friend.

My Approach

Extract the first word of each line and store them in HashSet and remove them from the string. Names stored in HashSet are already friends of the person (John).
Now extract the names from the String using StringTokenizer and check whether the name is contained in the HashSet. If it is not present then print it.

And can we solve this problem using graph/trees. The problem statement and my code can be found here.

import java.util.HashSet;
import java.util.Scanner;
import java.util.StringTokenizer;

class Ideone {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();   // No of friends
        sc.nextLine();
        HashSet<String> hs = new HashSet<>();   // to store name of the John's friends
        String invitation = "";
        for(int i =0; i < N; i++)
        {
            String str = sc.nextLine();
            String friend = "";
            int j =0;
            while(str.charAt(j)!= ' ')
            {
                friend = friend + str.charAt(j++);
                hs.add(friend);     // add the name before the number to HashSet
            }
            j= j+2;
            invitation=invitation+str.substring(j)+" "; // remove name of John's friend from the string and store back remaining string
        }
        int j =0;
        StringTokenizer st = new StringTokenizer(invitation); // divide string into tokens
        while(st.hasMoreTokens())
        {
            String str = st.nextToken();
            if(!hs.contains(str))   {
                /* check if token(string) is already in hashset ie if the person already friend with John or not
                if he is not then print str
                */
                System.out.print(str+" ");
            }
        }
    }
}


texts: Throttle implementation using pure JavaScript adding and removing event listener

texts:
I am trying to implement throttle function in vanilla JavaScript. I have seen other implementations on the web, but the way I have implemented it is more understandable for myself. I was wondering if any of you experts can take a look and let me know if I am missing some thing. It seems to be working fine but I am not sure the way I handle it is the correct.

HTML:

JS:

var area;
var result;

function init() {
  area = document.querySelector('#move');
  area.addEventListener('mousemove', trottle);
  result = document.querySelector('#result');
}

function updateResult(event) {
  let xCordinate = event.clientX;
  let yCordinate = event.clientY;
  result.textContent = `${xCordinate} , ${yCordinate}`;
}

function trottle(event) {
  updateResult(event);
  let element = event.target
  element.removeEventListener('mousemove', trottle);
  setTimeout(function() {
    element.addEventListener('mousemove', trottle);
  }, 2000)

}

init();


texts:
I am simply implementing a filter function for one my forms. I'd like to hear some reviews where I can improve in my code or my functionality  :)
Summary
I have 1 textbox and 2 comboboxes (See image below):

Category options

Status options

Code
public MainView()
{
    InitializeComponent();
    categoryText.SelectedIndex = 0;
    statusText.SelectedIndex = 0;

    RefreshData();
}

List<ConcessionModel> concessionList = new List<ConcessionModel>();
public void RefreshData()
{
    DataAccess db = new DataAccess();
    concessionList = db.LoadConcessionLog();
    dataGrid.DataSource = concessionList;

    dataGrid.Columns["Id"].Visible = false;
    dataGrid.Columns["PersonCompletingID"].Visible = false;
}

private void searchBtn_Click(object sender, EventArgs e)
{
    dataGrid.DataSource = Filter(productText.Text, categoryText.Text, statusText.Text);
}

private List<ConcessionModel> Filter(string product, string category, string status)
{
    if (category == "All" && status != "All")
    {
        return concessionList
                .Where(x => x.Product
                .IndexOf(product, StringComparison.InvariantCultureIgnoreCase) >= 0 && x.Status
                .IndexOf(status, StringComparison.InvariantCultureIgnoreCase) >= 0)
                .ToList();
    }
    else if (category != "All" && status == "All")
    {
        return concessionList
                .Where(x => x.Product
                .IndexOf(product, StringComparison.InvariantCultureIgnoreCase) >= 0 && x.Category
                .IndexOf(category, StringComparison.InvariantCultureIgnoreCase) >= 0)
                .ToList();
    }
    else if(category == "All" && status == "All")
    {
        return concessionList
                .Where(x => x.Product
                .IndexOf(product, StringComparison.InvariantCultureIgnoreCase) >= 0).ToList();
    }
    else
    {
        return concessionList
                .Where(x => x.Product
                .IndexOf(product, StringComparison.InvariantCultureIgnoreCase) >= 0 && x.Category
                .IndexOf(category, StringComparison.InvariantCultureIgnoreCase) >= 0 && x.Status
                .IndexOf(status, StringComparison.InvariantCultureIgnoreCase) >= 0)
                .ToList();
    }
}

public void ClearConcessionFilter()
{
    productText.Clear();
    categoryText.SelectedIndex = 0;
    statusText.SelectedIndex = 0;
    dataGrid.DataSource = concessionList;
}

ConcessionModel
public class ConcessionModel
{
    public int Id { get; set; }

    [DisplayName("Date Created")]
    public DateTime DateCreated { get; set; }

    public int PersonCompletingID { get; set; }
    public string Product { get; set; }

    [DisplayName("Batch Number")]
    public string BatchNumber { get; set; }

    [DisplayName("Quantity Affected")]
    public string QuantityAffected { get; set; }

    [DisplayName("Reason For Concession")]
    public string ReasonForConcession { get; set; }

    public string Category { get; set; }
    public string Status { get; set; }
}


texts: Math calculation refactoring in JavaScript

texts:
Here's the full source to a plugin I'm developing, the relevant code I want to refactor is:

function measure($element, $bubble){
    var scrollTop = $window.scrollTop(),
        viewportHeight = $window.height(),
        readableTop = $element.position().top,
        readableHeight = $element.height(),
        readableBottom = readableTop + readableHeight,
        scrollHeight = viewportHeight / readableHeight * viewportHeight,
        progress = (scrollTop - readableTop) / (readableHeight - viewportHeight),
        total = getTotalMinutes($element),
        remaining = Math.ceil(total - (total * progress)),
        distanceProgress = (scrollTop - readableTop) / readableHeight,
        distanceLiteral = readableTop + distanceProgress * readableHeight + viewportHeight / 2 - $bubble.height() / 2,
        distance = Math.max(readableTop, Math.min(distanceLiteral, readableBottom));

    return {
        remaining: remaining,
        progress: progress,
        distance: distance
    };
}

How might I make this calculation more understandable? I'm not terribly good at math, so I got there by trial and error, pretty much.

Now I'd like to refactor into something more readable or at least trim the repetitive nonsense, but I have no clue where to start.

Could you lend me a hand or give me any advice on how to tackle this?


texts: Using RxJS Observables to mediate routes in nodejs

texts:
I am learning to be a full stack developer and have been building out an application using Node JS as a backend. Since I have lots of experience using Angular I love RxJS. So naturally I was tempted to use RxJS for some types of tasks. Are there any down sides to using RxJS on the backend, more specifically are there any downs sides I can learn about from the following code implementation?

Im using Sequalize and Postgres. As you can see in the Invite Service I have used the Observable stream to first check if the Invite id is valid and then it checks if the recipient email is found in the database as a current user account or not. From either of the three returned values to the route I can now tell the front end what it must do next.

Other notable things:

I am using typical JWT authentication which in this case is a special user in the db since the request is being made from a web app and there is no actual logged in user.
I decided to pass the invite id and the recipient email in the headers which I know is kind of unusual.

This web app is actually just a mediator to deal with a complicated invite process which is being initialized from a React Native app.

Entry Point:

import inviteGenRouter from './routes/invite.routes';
let inviteRouter = inviteGenRouter(services);
api.use('/invite', inviteRouter);

app.use('/api', [passport.authenticate('jwt-bearer', {
  session: false,
  failWithError: true
}), (err, req, res, next) => {

  if (err) {
    Logger.error('Authentication Handshake: ', err);
    let error = {
      error: err.name,
      message: err.message
    };
    let statusCode = err.status || 500;
    return res.status(statusCode).json(error);
  }
  return next();
}], api);

Invite Routes:

router.route('/').get((req, res) => {
  if (req.headers.data) {
    return services.InviteService.authenticateInvite(req.headers.data)
      .subscribe(
        _res => {
          // Return options for front end.
          // If string the invite code was not found.
          // If null the associated email was not a user account.
          // If user the associated email was found.
        },
        _error => {
          // Some stuff when wrong...
        }
      );
  } else {
    // return some sort of error code.
  }

});

Invite Service:

class InviteService  {

  constructor(models) {
    this.models = models
  }

  findInviteById(id) {
    return Observable.defer(() => {
      return Observable.fromPromise(this.models.Invite.findOne({
        where: { inviteId: id }
      }));
    });
  }

  findUserById(email) {
    return Observable.defer(() => {
      return Observable.fromPromise(this.models.User.findOne({
        where: { email: email }
      }));
    });
  }

  authenticateInvite(token) {
    let payload = jwt.verify(token, appConfig.SESSION_SECRET);

    return this.findInviteById(payload.inviteId)
      .map(_invite => _invite ? _invite : Observable.of('Invalid Invite ID'))
      .mergeMap(_invite => _invite._isScalar ? _invite : this.findUserById(payload.email));
  }
}

module.exports = InviteService;


texts:
I'm trying to create the most efficient (not nicest/prettiest) way of moving particular values within an np.array() to the back of said array.

I currently have two different solutions:

import numpy as np
from numba import jit

@jit(nopython = True)
def move_to_back_a(a, value):
    new_a = []

    total_values = 0

    for v in a:
        if v == value:
            total_values += 1
        else:
            new_a.append(v)

    return new_a + [value] * total_values

@jit(nopython = True)
def move_to_back_b(a, value):
    total_values = np.count_nonzero(a == value)

    ind = a == value
    a = a[~ind]

    return np.append(a, [value] * total_values)

Which give the following output:

In [7]: move_to_back_a(np.array([2,3,24,24,24,1]), 24)
Out[7]: [2, 3, 1, 24, 24, 24]

In [8]: move_to_back_b(np.array([2,3,24,24,24,1]), 24)
Out[8]: array([ 2,  3,  1, 24, 24, 24], dtype=int64)

It doesn't really matter whether I get back my output as a list or as an array, though I expect that returning an array will be more helpful in my future code.

The current timing on these tests is as follows:

In [9]: %timeit move_to_back_a(np.array([2,3,24,24,24,1]), 24)
2.28 µs ± 20.5 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

In [10]: %timeit move_to_back_b(np.array([2,3,24,24,24,1]), 24)
3.1 µs ± 50.2 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

Is there any way to make this code even faster?


texts:
There is repetition here and would appreciate help in improving this code.  Suggestions? Here's the framework for it:

Class Author {
  private Integer id;

  public static List<Book> sortBooksAlphabetically( Author a ) {
    Integer id = a.id;
    if (id == null) { return null; }
    List<Book> list = getAllBooksForAuthor( id );
    // do some sorting and return list
  }

  public static List<Book> sortBooksReverseAlphabetically( Integer id ) {
    if (id == null ) { return null; }
    List<Book> list = getAllBooksForMusician( id );
    // do some sorting and return list
  }

  public static List<Book> sortBooksByPopularity( Integer id ) {
    if (id == null ) { return null; }
    List<Book> list = getAllBooksForAuthor( id );
    // do some sorting and return list
  }

  public static List<Book> getAllBooksForAuthor( Integer id ) {
     if (id == null ) throw new NullPointerException();
     ...
     return listOfBooks;
  }
}


texts:
Is my nonce implementation secure? I'm trying to learn security on wordpress->ajax (and later woocommerce) and with wp_create_nonce. After much struggling I managed to get it working, but is my implementation actually secure? Its a simple plugin used from this tutorial with my security customizations.

When enqueue the scrips the code creates a nonce for the user viewing it. This is saved too $parameters which will be passed to the JS file. The only thing the JS file do, is store this variable as the data -> "security" within the POST. When function post_love_add_love is run, it checks the $_REQUEST['security'] against what I told it should be aka. McLovin. Is this secure?

One assumption is that setting the variable to McLovin is probably a bad thing, but what is a better solution here?

I know I'm a beginner in this and I probably don't know 1 % of the things I should be securing against. But at least they can't visit the link to increase the count.

PHP

<?php
/**
 * Plugin Name: Post Love
 * Plugin URI: http://danielpataki.com
 * Description: Allows users to love your posts
 * Version: 1.0.0
 * Author: Daniel Pataki
 * Author URI: http://danielpataki.com
 * License: GPL2
 */

add_action( 'wp_enqueue_scripts', 'ajax_test_enqueue_scripts' );
function ajax_test_enqueue_scripts() {
    if( is_single() ) {
        wp_enqueue_style( 'love', plugins_url( '/love.css', __FILE__ ) );
    }
    wp_enqueue_script( 'love', plugins_url( '/love.js', __FILE__ ), array('jquery'), '1.0', true );

    $parameters =  array(
        'ajax_url' => admin_url( 'admin-ajax.php' ),
        'security' => wp_create_nonce('McLovin')
        );
    wp_localize_script( 'love', 'postlove', $parameters);
}

add_filter( 'the_content', 'post_love_display', 99 );
function post_love_display( $content ) {
    $love_text = '';

    if ( is_single() ) {

        $love = get_post_meta( get_the_ID(), 'post_love', true );
        $love = ( empty( $love ) ) ? 0 : $love;

        $love_text = '
give love' . $love . '
';
    }
    return $content . $love_text;
}

add_action( 'wp_ajax_nopriv_post_love_add_love', 'post_love_add_love' );
add_action( 'wp_ajax_post_love_add_love', 'post_love_add_love' );

function post_love_add_love() {
    check_ajax_referer( 'McLovin', 'security' );
    $love = get_post_meta( $_REQUEST['post_id'], 'post_love', true );
    $love++;
    update_post_meta( $_REQUEST['post_id'], 'post_love', $love );
    if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
        ob_clean();
        echo $love;
        die();
    }
    else {
        wp_redirect( get_permalink( $_REQUEST['post_id'] ) );
        exit();
    }
}

JS

jQuery( document ).on( 'click', '.love-button', function() {
var post_id = jQuery(this).data('id');
jQuery.ajax({
    url : postlove.ajax_url,
    type : 'post',
    data : {
        action : 'post_love_add_love',
        post_id : post_id,
        security : postlove.security
    },
    success : function( response ) {
        jQuery('#love-count').html( response );
    }
});

return false;
})

CSS

.entry-content .love-button {
    background: #f14864;
    color: #fff;
    padding:11px 22px;
    display:inline-block;
    border:0px;
    text-decoration: none;
    box-shadow: 0px 6px #d2234c;
    position:relative;
}

.entry-content .love-button:hover{
    top:3px;
    box-shadow: 0px 3px #d2234c;
}

.entry-content .love-button:active{
    top:6px;
    box-shadow: none;
}

#love-count {
    background: #eee;
    box-shadow: 0px 6px #ddd;
    color: #666;
    padding:11px 22px;
    display:inline-block;
}


texts: Compacting this repetitive JavaScript bit which trims values in an object

texts:
shippingAddress.first_name = shippingAddress.first_name.trim()
    shippingAddress.last_name = shippingAddress.last_name.trim()
    shippingAddress.address1 = shippingAddress.address1.trim()
    shippingAddress.address2 = shippingAddress.address2.trim()
    shippingAddress.phone = shippingAddress.phone.trim()
    shippingAddress.city = shippingAddress.city.trim()
    shippingAddress.province = shippingAddress.province.trim()
    shippingAddress.country = shippingAddress.country.trim()
    shippingAddress.zip = shippingAddress.zip.trim()

What is a more elegant way to write this? I am thinking I can map it somehow or use something similar to Ruby's inject but I'm not sure.


texts: Title capitalization exercise from The Odin Project

texts:
I just finished the book title class exercise for The Odin Project and I would appreciate some honest feedback for my code. The code is intended to be "test-driven learning", and therefore emulates test driven development

Here is the test spec:

require 'book'

describe Book do

  before do
    @book = Book.new
  end

  describe 'title' do
    it 'should capitalize the first letter' do
      @book.title = "inferno"
      expect(@book.title).to eq("Inferno")
    end

    it 'should capitalize every word' do
      @book.title = "stuart little"
      expect(@book.title).to eq("Stuart Little")
    end

    describe 'should capitalize every word except...' do
      describe 'articles' do
        specify 'the' do
          @book.title = "alexander the great"
          expect(@book.title).to eq("Alexander the Great")
        end

        specify 'a' do
          @book.title = "to kill a mockingbird"
          expect(@book.title).to eq("To Kill a Mockingbird")
        end

        specify 'an' do
          @book.title = "to eat an apple a day"
          expect(@book.title).to eq("To Eat an Apple a Day")
        end
      end

      specify 'conjunctions' do
        @book.title = "war and peace"
        expect(@book.title).to eq("War and Peace")
      end

      specify 'prepositions' do
        @book.title = "love in the time of cholera"
        expect(@book.title).to eq("Love in the Time of Cholera")
      end
    end

    describe 'should always capitalize...' do
      specify 'I' do
        @book.title = "what i wish i knew when i was 20"
        expect(@book.title).to eq("What I Wish I Knew When I Was 20")
      end

      specify 'the first word' do
        @book.title = "the man in the iron mask"
        expect(@book.title).to eq("The Man in the Iron Mask")
      end
    end
  end
end

Here if my code:

class Book
  attr_accessor :title

  def title=(book)
    lowercase = ["and", "or", "the", "of", "in", "a", "an"]
    @title = book.capitalize.split(" ").map do |word|
      if lowercase.include? word
        word
      else
        word.capitalize
      end
    end.join(" ")
  end

end


texts:
I'm currently creating a small server back-end. My goal is to write an (efficient) packet parser in C++17 using the command pattern. The packets are given by:

type: value in {0, 1, 255}
size: value in {0, 1, 65535}
data: array[size]

Each packet is processed by a packet_operator. The packet_registry is a packet_operator which simply calls the operator for the given packet type. I currently see no need for multiple, pipelined parsers for a single packet type. The code sample is given below and does compile without warnings.

packets.hpp

#pragma once

#include <array>
#include <memory>

// Test class without proper implementation.
class packet {

public:
    uint32_t m_type = 0;

    uint32_t type() const {
        return m_type;
    }

};

template<class ... ArgTypes>
class packet_operator {

public:
    virtual void operator()(const packet &, ArgTypes... args) = 0;

};

template<class ... ArgTypes>
class packet_registry : public packet_operator<ArgTypes...> {

public:
    using op_ptr = std::shared_ptr<packet_operator<ArgTypes...>>;

    explicit packet_registry(op_ptr op) {
        // Initialize registry with default processor
        for (size_t i = 0; i < m_operators.size(); i++)
            m_operators[i] = op;
    }

    void operator()(const packet &packet, ArgTypes... args) override {
        // Call processor for packet type
        (*m_operators[packet.type()])(packet, args...);
    }

    op_ptr &operator[](uint32_t i) {
        return m_operators[i];
    }

private:
    std::array<op_ptr, 256> m_operators;  // Type will always be in [0, 255]

};

main.cpp

#include <iostream>
#include <memory>

#include "packets.hpp"

class processor : public packet_operator<> {

    int m_id;

public:
    explicit processor(int id) : m_id(id) {
        // Empty
    }

    void operator()(const packet &packet) override {
        std::cout << "Processor " << m_id << ". Type: " << packet.type() << std::endl;
    }

};

void init(packet_registry<> &registry) {
    registry[1] = std::shared_ptr<packet_operator<>>(new processor(1));
    registry[2] = std::shared_ptr<packet_operator<>>(new processor(2));
}

int main() {
    // Create registry with default processor
    auto registry = packet_registry<>(
            std::shared_ptr<packet_operator<>>(new processor(0)));

    // Initialize packet processors
    init(registry);

    // Test packets with type 0, 1, 2 and 3
    packet p0, p1, p2, p3;
    p0.m_type = 0;
    p1.m_type = 1;
    p2.m_type = 2;
    p3.m_type = 3;

    registry(p0);
    registry(p1);
    registry(p2);
    registry(p3);

    return 0;
}

My main concern is my use of functors and shared pointers. Did I use those correctly? Additionally, my linter advised me to add the explicit keyword before the constructors. I've researched what it does, but do not really understand why those types of constructors would always need to be explicit.

I'd also like to know if there are any alternatives to my init method. I'd have to register the processors for every packet type here. I'd prefer some sort of self-registering processor. For example, in Java I could annotate all packet processors using a custom annotation. Those will then be added to the right registry using reflection. Maybe this is achievable through some sort of meta-programming?

Lastly, a more more general question: are there any alternative designs, given that I cannot change the protocol?


texts:
I wrote the following algorithm to try to find the largest duplicate subtree in a tree as described here: http://ayushcshah.github.io/algorithm/binarytree/2016/04/01/detect-duplicate-subtrees.html (I wrote my own solution rather than using the one described in the post). I tried to find the largest duplicate subtree in O(n) time. Not sure it's actually strictly O(n) though due to the getSize() helper method. Could someone help me analyze the runtime?

public static Node findLargestSubtree(Node root) {
    if (root == null) {
        return null;
    }
    Map<String, Node> map = new HashMap<String, Node>();
    Map<Node, Integer> dupes = new HashMap<Node, Integer>();
    postOrderTraversal(root, map, dupes);
    Iterator<Node> it = dupes.keySet().iterator();
    while (it.hasNext()) {
        return it.next();
    }
    return null;
}

private static String postOrderTraversal(Node root, Map<String, Node> map, Map<Node, Integer> best) {
    if (root.left == null && root.right == null) {
        return "1:" + hash(root.data);
    }
    String left = "";
    String right = "";
    if (root.left != null) {
        left = postOrderTraversal(root.left, map, best);
    }
    if (root.right != null) {
        right = postOrderTraversal(root.right, map, best);
    }
    int size = 1;
    if (!left.equals("")) {
        size += getSize(left);
    }
    if (!right.equals("")) {
        size += getSize(right);
    }
    StringBuilder sb = new StringBuilder();
    String hash = sb.append(size).append(":").append(left).append(right).toString();
    if (map.containsKey(hash)) {
        if (best.isEmpty()) {
            best.put(root, size);
        }
        Iterator<Map.Entry<Node, Integer>> it = best.entrySet().iterator();
        if (it.hasNext()) {
            Map.Entry<Node, Integer> e = it.next();
            if (size > e.getValue()) {
                best.remove(e.getKey());
                best.put(root, size);
            }
        }
    } else {
        map.put(hash, root);
    }
    return hash;
}

private static int getSize(String s) {
    int i;
    for (i = 0; i < s.length(); i++) {
        if (s.charAt(i) == ':') {
            break;
        }
    }
    return Integer.parseInt(s.substring(0, i));
}

private static int hash(Character key) {
    return key.hashCode();
}


texts:
I'm developing a small website which is responsive, and I'm planning on displaying a number of items ( Demo ) on the page. As you can see in the link the items are displayed just fine, but what I'm trying to do is calculate the exact number of items that would fit inside the window ( more specific the actual space between the footer and the header ) so none of them will be shown only by half or overflown by the footer.

I got this small function working :

Cluster.prototype.initiate_items_per_page_calculation = function() {
    return Math.floor(Math.floor(($(window).width() - ($(window).width() * 4 / 100)) / $('body').find(this.cluster_public_classes.item_wrapper).outerWidth()) * Math.floor(Math.floor($(window).height() - ($('body').find('header').outerHeight() + $('body').find('footer').outerHeight()) - ($(window).height() * 4 / 100)) / $('body').find(this.cluster_public_classes.item_wrapper).outerHeight()));
};

Just that the calculations are not that exact. For instance I have the item's width of 260px and it's height 160px ( adding a few pixels because there two more layers of background behind the visible layer that are rotated 3deg, so there are about 5 pixels more on each side ) plus the white space between them which is 15px on each side, and there are the footer and the header heights which cut from the space, so taking all of this into consideration my calculations are not that accurate anymore. So I was wondering if I could get a little bit of help with making this work perfectly no matter what the screen size is (:


texts: Performance of dynamic Fibonacci generator and dead rabbits

texts:
I would like to improve my code style and its efficiency.

I'm just moving beyond the standard recursive approach to a lot of simple algorithms.

This post has two code snippets with slightly different but related problems. They're both in Python.

The first snippet is just to produce Fibonacci numbers. I think I've done this with O(n) time complexity. Do you have suggestions on how to make my code more readable and more efficient?

# Using bottom-up dynamic programming approach, define all fibonacci numbers
def fib(num):

    # First and second generations are trivial
    if num == 1 or num == 2:
        return 1

    # If not trivial, keep going:

    # Set up array
    allGenerations = [None] * (num + 1)
    allGenerations[1] = 1
    allGenerations[2] = 1

    # Fill in the array until you reach the given generation
    for i in range(3, num+1):
        allGenerations[i] = allGenerations[i - 1] + allGenerations[i - 2]
    return allGenerations[num]

The second snippet tries to use what I learned from the first snippet to solve a related problem. The numbers represent living rabbits. If rabbits lived forever, their population sizes would follow a fibonacci sequence. In this alteration, rabbits live for a fixed amount of time (input m). Newborn rabbits keep living, adult rabbits produce themselves and one offspring, and rabbits that are about to die just produce one offspring (see http://rosalind.info/problems/fibd/).

I'm not sure how to analyze the time complexity of this problem, but it seems high? So questions are (1) What is the time complexity of my solution? and (2) How can I improve efficiency and readability?

def rabbit(n, m):
    # First two generations are trivial
    if n == 1 or n == 2:
        return 1

    # If not trivial, keep going:

    # Set up array
    allGenerations = [None] * (n + 1)

    # Each index in the generations will be another array whose indicies represent the ages of the rabbits in that generation
    allGenerations[1] = [1]
    allGenerations[2] = [0, 1]

    # Bottom-up filling of generations
    for i in range(3, n + 1):
        # Initalize answer as a list of number of rabbits at each age
        answer = [None] * (i)

        # Get the previous generation
        previous = allGenerations[i - 1]

        # Initalize the number of newborns
        newborns = 0

        # From age 1 (first reproductive age) to either age at death
        # or the oldest in the previous generation (whichever comes first), produce newborn rabbits
        for j in range(1, min(m, len(previous))):
            newborns += previous[j]

        # The 0-index of the answer represents newborn rabbits
        answer[0] = newborns

        # Move every element in the previous generation up one index into the new generation
        for k in range(0, len(previous)):
            answer[k + 1] = previous[k]

        # Put this answer into the list of all answers
        allGenerations[i] = answer

    # Return all living rabbits
    return sum(answer[:m])

# Some testcases

import unittest

class mainTest(unittest.TestCase):
    def test(self):
        self.assertEqual(rabbit(1, 3), 1)
        self.assertEqual(rabbit(2, 3), 1)
        self.assertEqual(rabbit(3, 3), 2)
        self.assertEqual(rabbit(4, 3), 2)
        self.assertEqual(rabbit(5, 3), 3)
        self.assertEqual(rabbit(6, 3), 4)
        self.assertEqual(rabbit(7, 3), 5)
        self.assertEqual(rabbit(25, 31), 75025)
        self.assertEqual(rabbit(30, 30), 832040)
        self.assertEqual(rabbit(35, 29), 9227437)
        self.assertEqual(rabbit(40, 28), 102333267)
        self.assertEqual(rabbit(45, 27), 1134880302)

if __name__ == '__main__':
    unittest.main(argv=[''], exit = False)


texts:
The following code seems to have several redundant Flush, Close and Abort statements despite using the use statement.

This code requests a token using API keys and caches it for efficiency reasons and subsequent usage to avoid requesting token each time until it expires.

You'll notice expiry check (plus some extra 1 sec buffer) token.expires_at.Add (TimeSpan 1000L) followed by either HTTP call or it simply returns the token from the cache.

I have the use requestStream statement along with requestStream.Close(). Is it necessary to close if you are using the use statement? Same with the use reader statement.
request.Abort() do we need to abort the request, I was expecting close or something?
I believe making it asynchronous will make it more efficient. Any help in that regard will be highly appreciated.

Otherwise the code works fine and I need a second pair of eyes to look at it. Please help to reduce the lines of code as much as possible.

let requestToken (): Token =

    if token.expires_at.Add (TimeSpan 1000L) < DateTime.Now then

        let data : byte[] = System.Text.Encoding.ASCII.GetBytes("");

        let url = "https://example.com"

        let request = WebRequest.Create(url) :?> HttpWebRequest
        request.Method <- "POST"
        request.ContentType <- "application/x-www-form-urlencoded"
        request.Accept <- "application/json;charset=UTF-8"
        request.ContentLength <- (int64)data.Length

        use requestStream = request.GetRequestStream()
        requestStream.Write(data, 0, data.Length)
        requestStream.Flush()
        requestStream.Close()

        let response = request.GetResponse() :?> HttpWebResponse
        use reader = new StreamReader(response.GetResponseStream())

        let result = JsonConvert.DeserializeObject<Token>(reader.ReadToEnd())

        token.access_token <- result.access_token
        token.token_type <- result.token_type
        token.expires_in <- result.expires_in
        token.expires_at <- DateTime.Now + TimeSpan.FromMilliseconds(double(result.expires_in))

        reader.Close()
        response.Close()
        request.Abort()

        token
    else
        token

Usage

let token : Token = requestToken()


texts: My method of escaping MySQL strings in C++

texts:
This is how I'm currently escaping MySQL strings in C++:

std::string escapeSQL(const char* dataIn)
{
   if (!MySQL_Database_Connection__global->host)
      int a = NULL;

   if (dataIn)
   {
      std::size_t dataInLen = strlen(dataIn);
      std::string to(((dataInLen * 2) + 1), '\0');
      mysql_real_escape_string(MySQL_Database_Connection__global, &to[0], dataIn, dataInLen);
      return (to);
   }
   else
   {
      return ("");
   }
}

char query[1024] = {'\0'};
snprintf(query, sizeof(query), "SELECT * FROM database.table WHERE column = '%s';", escapeSQL(userTypedArgument).c_str());

It seems to be doing the job, but I'm curious if I can get a review of my escapeSQL() function for any pitfalls I may have overlooked.


texts:
I have this recursive generator that fetches 100 messages from an API and gets the next 100 until there are no more messages to get:

async* fetchAllMessages(channel: Channel & TextBasedChannelFields, startingMessageId?: Snowflake) {
    const results = await channel.fetchMessages(this.buildQueryLogOptions(startingMessageId));
    const finalMessageIdFromBatch = results.lastKey();

    if (!results) {
        return;
    }

    if (!finalMessageIdFromBatch) {
        return;
    }

    yield results;
    yield* this.fetchAllMessages(channel, finalMessageIdFromBatch);
}

and I consume the generator like so:

Async.parallelLimit(allTextChannels.map(channel => async function(callback) {
    const messageGenerator = await this.fetchAllMessages(channel, undefined);

    for ( ; ; ) {
        const generatorResult = await messageGenerator.next();

        if (generatorResult.done) {
            break;
        }

        await this.logMessagesForChannelAndUser(channel, this.client.user.id, generatorResult.value);
    }

    console.log('finished channel: ', this.getNameForChannel(channel));
    callback(undefined, true);
}.bind(this), 4, () => console.log('done'));

This works great for a majority of channels, but the recursive generator is really slamming the call stack for huge channels; node process is crashing with ELIFECYCLE 3221225725 (call stack overflow).  I really like the recursive generator pattern because of its simplicity, but should I abandon it in this case?  Or is there a better pattern out there for 'pausing' after a certain number of iterations and picking it back up with a new instantiation?


texts: Dijkstra's and Prim's algorithms: correctness/efficiency

texts:
This is in preparation for a competition that only allows C++03.

// Neighbor index plus weight of edge connecting this vertex with neighbor
struct NeighborWeight
{
    Index neighbor;
    Distance weight;
};
// Represents adjacency information for a single vertex (contains all
// neighbors and weights of edges connecting them)
typedef std::list<NeighborWeight> AdjVertex;
// Represents adjacency information for all vertices (thus representing
// a complete directed/undirected graph)
typedef std::vector<AdjVertex> AdjList;

// Dijkstra's algorithm: computes SHORTEST PATH to all vertices from a starting
// vertex for a DIRECTED/UNDIRECTED graph with NONNEGATIVE edge weights.
// result.dist[v] = shortest distance from source to v.
// result.prev[v] = predecessor of v in shortest path from source to v.
// If v is not connected to start_vertex, dist[v] = max value of Distance, and
// prev[v] = -1.
// If v = start_vertex, prev[v] = -1.

// Prim's algorithm (call with do_prim = true): computes MINIMUM SPANNING TREE
// starting from a seed vertex for an UNDIRECTED graph with ANY edge weights.
// result.dist[v] should be ignored.
// result.prev[v] = parent of v in minimal spanning tree.
// If v is not connected to start_vertex, prev[v] = -1.
// If v = start_vertex, prev[v] = -1;

struct DijkstraResult
{
    std::vector<Distance> dist;
    std::vector<Index> prev;
};

DijkstraResult dijkstra(AdjList al, Index start_vertex, bool do_prim = false)
{
    typedef std::pair<Distance, Index> DistAndIndex;

    const Distance infinity = std::numeric_limits<Distance>::max();
    const Index undefined_index = -1;
    const Index num_vertices = al.size();

    std::vector<Distance> dist(num_vertices, infinity); // tentative distances
    std::vector<Index> prev(num_vertices, undefined_index); // predecessors
    std::vector<uint8_t> is_visited(num_vertices, false);
    std::set<DistAndIndex> unvisited_queue;

    dist[start_vertex] = 0;

    // Populate unvisited_queue in order with (Distance, Index) pairs
    unvisited_queue.insert(std::make_pair(0, start_vertex));
    for (Index v = 0; v < num_vertices; ++v)
        if (v != start_vertex)
            unvisited_queue.insert(unvisited_queue.end(),
            std::make_pair(infinity, v));

    while (!unvisited_queue.empty())
    {
        // u = index of unvisited vertex with least distance
        Index u = unvisited_queue.begin()->second;
        // If this least distance is infinity, break (no more connected verts)
        if (unvisited_queue.begin()->first == infinity) break;
        // Visit this vertex
        unvisited_queue.erase(unvisited_queue.begin());
        is_visited[u] = true;
        // In Prim's, distances are computed from the MST. Adding a vertex
        // to the MST makes the distance 0.
        if (do_prim) dist[u] = 0;
        // vert = vertex corresponding to u
        AdjVertex &vert = al[u];
        // Iterate through neighbors of u
        for (AdjVertex::iterator it = vert.begin(); it != vert.end(); ++it)
        {
            // v = it->neighbor is the index of the neighbor; it->weight is the
            // edge weight between u and v
            Index v = it->neighbor;
            // Skip if v is visited
            if (is_visited[v]) continue;
            // Now compute new dist for v
            Distance alt = dist[u] + it->weight;
            // And compare with previous
            if (alt < dist[v])
            {
                unvisited_queue.erase(std::make_pair(dist[v], v));
                unvisited_queue.insert(std::make_pair(alt, v));
                dist[v] = alt;
                prev[v] = u;
            }
        }
    }

    DijkstraResult res = { dist, prev };
    return res;
}

There's another set of typedefs and functions that duplicates a list of undirected edges into an AdjList structure.


texts: Encrypt texts, with saved password using pycrypto

texts:
I have the code bellow, which is supposed to be used inside a larger program.
Please see notes about the requirements below the code.

from __future__ import print_function
from Crypto.Cipher import AES
from Crypto.Protocol.KDF import PBKDF2
import base64
import os
import sys
import binascii

if sys.version_info.major > 2:
    raw_input = input

EncodeAES = lambda c, s: base64.b64encode(c.encrypt(s))
DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip()

def get_digest(password, salt):
    """
    Get a digest based on clear text password
    """
    iterations = 5000
    return PBKDF2(password, salt, dkLen=32, count=iterations)

def authenticate(password, salt, digest):
    """
    salt and digest are stored in a file or a database
    """
    dig = get_digest(password, salt)
    return binascii.hexlify(dig) == digest

def write_password():
    """
    Write a secret password as a hash and the salt used for this hash
    to a file
    """
    salt = base64.b64encode(os.urandom(32))
    passwd = raw_input("Please type in the secret key:")
    key = get_digest(passwd, salt)
    f = open('passwords.txt', 'wt')
    hpk = salt+'$6$'.encode('utf8')+binascii.hexlify(key)
    f.write(hpk.decode('utf-8'))
    f.close()

def get_digest_from_file(filename):
    """
    Read a digested password and salt from the file
    """
    f = open(filename, 'rt')
    sf = f.readline()
    f.seek(0)
    salt, digest = f.readline().split('$6$')
    return salt.encode('utf-8'), digest.encode('utf-8')

def get_cipher(password, salt):
    """
    Create a chiper object from a hashed password
    """
    iv = os.urandom(AES.block_size)
    dig = get_digest(password, salt)
    chiper = AES.new(dig, AES.MODE_ECB, iv)
    return chiper

def cli_auth():
    """
    Read password from the user, if the password is correct,
    finish the execution an return the password and salt which
    are read from the file.
    """
    salt, digest = get_digest_from_file('passwords.txt')
    while True:
        password = raw_input("Please type in your password:").encode('utf-8')
        if authenticate(password, salt, digest):
            return password, salt

def prepare_data(text, block_size):
    """
    prepare data before encryption so the lenght matches the expected
    lenght by the algorithm.
    """
    num_blocks = len(text)//block_size + 1
    newdatasize = block_size*num_blocks
    return text.ljust(newdatasize)

def save_a_secret_message():
    """
    PoC to show we can encrypt a message
    """
    secret_msg = """This is a very important message! Learn Cryptography!!!"""
    # the secret message will be encrypted with the secret password found
    # in the file
    passwd, salt = cli_auth()
    cipher = get_cipher(passwd, salt)
    # explictly destroy password, so now there is no clear text reference
    # to the input given by the user
    del(passwd)
    msg = EncodeAES(cipher, prepare_data(secret_msg, AES.block_size))
    with open('secret.enc','wt') as s:
        s.write(msg.decode())
    print("The cipher message is:", msg.decode())

def read_a_secret_message():
    """
    PoC to show we can decrypt a message
    """
    passwd, salt = cli_auth()
    cipher = get_cipher(passwd, salt)
    del(passwd)
    with open('secret.enc') as s:
        msg = s.readline()
        print("The decrypted secret message is:")
        decoded = DecodeAES(cipher, msg)
        print(decoded)

if __name__ == '__main__':
    if '-i' in sys.argv:
        write_password()
    save_a_secret_message()
    read_a_secret_message()

The user is supposed to enter is password only once.
but decryption and  encryption take place many times while the program is running.
There should be a mechanism to save the password (or a digest) on the disk (not in clear text).
Should be Python2 and Python3 compatible.

So far, it seems to me, it all works OK. I tested python2 and python3. The cipher text can be decrypted with different Python versions too.

However, I am not a Crypto expert, and I would definitely like to here some criticism about this code.


texts: Pagination links for various lists using Spring-HATEOAS

texts:
I'm using Spring HATEOAS to create some links on my REST API. However, the entities i'm returning are very close, so the code to generate the links are the same:

private Iterable<Link> getTemperatureSensorLinks(Links sensorLinks, Integer curPage) {

        Integer lastPage = sensorLinks.getLastPageNum();
        Integer firstPage = sensorLinks.getFirstPageNum();
        Integer nextPage = sensorLinks.getNextPageNum();
        Integer prevPage = sensorLinks.getPrevPageNum();

        List<Link> result = new ArrayList<>();
        result.add(linkTo(methodOn(SensorController.class).getTemperatureSensor(firstPage)).withRel("first"));
        result.add(linkTo(methodOn(SensorController.class).getTemperatureSensor(lastPage)).withRel("last"));
        if(nextPage != null)
            result.add(linkTo(methodOn(SensorController.class).getTemperatureSensor(nextPage)).withRel("next"));
        if(prevPage != null)
            result.add(linkTo(methodOn(SensorController.class).getTemperatureSensor(prevPage)).withRel("prev"));

        return result;
    }

I have another method that's exactly the same, except that the method is getMotionSensor(page) instead of getTeperatureSensor(page).

I tried to factor out the method like this:

private Iterable<Link> getSensorLinks(Links sensorLinks, Method m, Integer curPage) {

        Integer lastPage = sensorLinks.getLastPageNum();
        Integer firstPage = sensorLinks.getFirstPageNum();
        Integer nextPage = sensorLinks.getNextPageNum();
        Integer prevPage = sensorLinks.getPrevPageNum();

        List<Link> result = new ArrayList<>();
        result.add(linkTo(m, firstPage).withRel("first"));
        result.add(linkTo(m, lastPage).withRel("last"));
        if(nextPage != null)
            result.add(linkTo(m, nextPage).withRel("next"));
        if(prevPage != null)
            result.add(linkTo(m, prevPage).withRel("prev"));

        return result;
    }

But then the calling methods get super ugly with reflection, and the checked exceptions thrown by Class.getMethod().

Is there a better way that I'm not seeing ?


texts:
I'm using the following function to index ebook data with Lucene.  I'm looking to improve the structure and organization of this function.

public string BuildIndex(int pageNum, int pageSize)
{
    var watch = new System.Diagnostics.Stopwatch();
    watch.Start();
    var version = Lucene.Net.Util.Version.LUCENE_30;

    Analyzer analyzer = new StandardAnalyzer(version);
    DirectoryInfo path = new DirectoryInfo("C:\\LuceneIndex");
    Lucene.Net.Store.Directory directory = new MMapDirectory(path);
    using (IndexWriter iwriter = new IndexWriter(directory, analyzer, IndexWriter.MaxFieldLength.UNLIMITED))
    {
        //Initialize the StringBuilder with 4 MB to accommodate our data
        StringBuilder bodyBuilder = new StringBuilder(4*1024*1024);
        var files = ReaderDAL.FetchBooklistSearchData(pageNum, pageSize);
        foreach (var file in files) {
            bodyBuilder.Clear();
            DirectoryInfo filePath = new DirectoryInfo(file.IndexFilePath);

            if (filePath.Exists)
            {
                foreach (var pageFile in filePath.EnumerateFiles())
                {
                    using (StreamReader reader = pageFile.OpenText()) {
                        String line = reader.ReadToEnd();
                        bodyBuilder.AppendLine(line);
                    }
                }
            }
            //file.IndexFilePath
            Document doc = new Document();
            doc.Add(new Field("id", file.BookId.ToString(), Field.Store.YES, Field.Index.NO));
            doc.Add(new Field("author", file.Author, Field.Store.YES, Field.Index.ANALYZED));
            doc.Add(new Field("annotation", file.Annotation, Field.Store.YES, Field.Index.ANALYZED));
            doc.Add(new Field("publisher", file.Publisher, Field.Store.YES, Field.Index.ANALYZED));
            doc.Add(new Field("title", file.Title, Field.Store.YES, Field.Index.ANALYZED));
            doc.Add(new Field("body", bodyBuilder.ToString(), Field.Store.YES, Field.Index.ANALYZED));
            iwriter.AddDocument(doc);
        }

        iwriter.Optimize();
        iwriter.Flush(true, true, true);
    }

    watch.Stop();

    return watch.Elapsed.TotalSeconds.ToString();
}


texts:
In short, the code picks up to 9 different ids from li in jailplayer.

If a hillside, it shall save the value of the id, and then checks if there are more li, up to 9 pcs.

Then I save this in an array, depending on how many ids were found.

This looks like a mess.  Can someone help me shorten this code and make it easier to read?

if ($("#jailplayer").children("li").length >= 1) {
                var player1 = $("#jailplayer").find("li:nth-child(1)").attr("id");
                sender = sender + ',';
                sender = sender + player1;

            } else {
                var player1 = '';
            }
            console.log('done one, searching 2');

            if ($("#jailplayer").children("li").length >= 2) {
                var player2 = $("#jailplayer").find("li:nth-child(2)").attr("id");
                sender = sender + ',';
                sender = sender + player2;

            }else {
                var player2 = '';
            }
            if ($("#jailplayer").children("li").length >= 3) {
                var player3 = $("#jailplayer").find("li:nth-child(3)").attr("id");
                sender = sender + ',';
                sender = sender + player3;

            }else {
                var player4 = '';
            }

            if ($("#jailplayer").children("li").length >= 4) {
                var player4 = $("#jailplayer").find("li:nth-child(4)").attr("id");
                sender = sender + ',';
                sender = sender + player4;
            }else {
                var player4 = '';
            }

            if ($("#jailplayer").children("li").length >= 5) {
                var player5 = $("#jailplayer").find("li:nth-child(5)").attr("id");
                sender = sender + ',';
                sender = sender + player5;
            }else {
                var player5 = '';
            }

            if ($("#jailplayer").children("li").length >= 6) {
                var player6 = $("#jailplayer").find("li:nth-child(6)").attr("id");
                sender = sender + ',';
                sender = sender + player6;
            }else {
                var player6 = '';
            }

            if ($("#jailplayer").children("li").length >= 7) {
                var player7 = $("#jailplayer").find("li:nth-child(7)").attr("id");
                sender = sender + ',';
                sender = sender + player7;
            }else {
                var player7 = '';
            }

            if ($("#jailplayer").children("li").length >= 8) {
                var player8 = $("#jailplayer").find("li:nth-child(8)").attr("id");
                sender = sender + ',';
                sender = sender + player8;
                player8 .= ',';

            }else {
                var player8 = '';
            }

            if ($("#jailplayer").children("li").length >= 9) {
                var player9 = $("#jailplayer").find("li:nth-child(9)").attr("id");
                sender = sender + ',';
                sender = sender + player9;
            }else {
                var player9 = '';
            }

            console.log('adding ize');

            var ize =[sender];


texts:
The old code I had before  was atrociously slow but after some advice and research I was able to take a 2-5 minutes run time down to about 5-30 seconds.  That is acceptable, but still looking to have it run as quickly as possible.

I'm still cleaning it up, like there shouldn't be two seperate PP entities calls.

public static List<DailyTeamGoal> GetListDailyTeamGoals(int teamId)
{
    string teamGoal = "";
    List<ProPit_User> lstProPit_User = new List<ProPit_User>();
    using (PPEntities db = new PPEntities())
    {
        Team team = db.Teams.Where(x => x.teamID == teamId).FirstOrDefault();

        if (team != null)
        {
            teamGoal = Convert.ToString(team.goal);
        }

        lstProPit_User = db.ProPit_User.Where(x => x.teamID == teamId).ToList();
    }

    List<DailyTeamGoal> lstDailyTeamGoal = new List<DailyTeamGoal>();
    using (TEntities db = new TEntities())
    using (PPEntities ppdb = new PPEntities())
    {
        //have to get every day of the month
        DateTime dt = DateTime.Now;
        int days = DateTime.DaysInMonth(dt.Year, dt.Month);
        decimal orderTotal = 0m;
        for (int day = 1; day <= DateTime.Now.Day; day++)
        {
            DailyTeamGoal dtg = new DailyTeamGoal();
            dtg.Date = day.ToString(); //dt.Month + "/" + day; + "/" + dt.Year;
            dtg.TeamGoal = teamGoal;
            //decimal orderTotalRep = 0m;

            DateTime dtStartDate = Convert.ToDateTime(dt.Month + "/" + day + "/" + dt.Year);
            DateTime dtEndDate = dtStartDate.AddDays(1);

            var ordersQuery = db.Orders.Where(o => o.DateCompleted >= dtStartDate
                                                && o.DateCompleted <= dtEndDate
                                                && (o.Status == 1 || o.Status == 2)
                                                && o.Kiosk != 0).ToList();

            var lstSalesRepIDs = ppdb.ProPit_User
                .Where(x => x.teamID == teamId).Select(v => v.SalesRepID).ToList();

            var total = (from o in ordersQuery
                            where lstSalesRepIDs.Contains(o.SalesRepID)
                            select o.OrderTotal).Sum();

            orderTotal += total;
            dtg.DailyTotal = orderTotal;

            lstDailyTeamGoal.Add(dtg);
        }
    }

    return lstDailyTeamGoal;
}


texts:
I am making a quiz app using tkinter in Python. I will be having a database that will have questions and options to display in application. Is it good to structure the program as shown, or should it be re-structured in some other way?

import tkinter as tk

def iQuiz(source,row=0,column=0,rowspan=None,columnspan=None):
    storeObj=tk.Frame(source,bg="powder blue")
    storeObj.grid(row=row,column=column,rowspan=rowspan,columnspan=columnspan)
    return storeObj

def button(source,text,command=None,row=0,column=0,rowspan=None,columnspan=None):
    storeObj=tk.Button(source,text=text,command=command)
    storeObj.grid(row=row,column=column,rowspan=rowspan,columnspan=columnspan)
    return storeObj

def radioButton(source,text,indicator='off',command=None,row=0,column=0,rowspan=None,columnspan=None):
     storeObj=tk.Radiobutton(source,text=text,indicator=indicator,command=command)
    storeObj.grid(row=row,column=column,rowspan=rowspan,columnspan=columnspan)
    return storeObj

def label(source,text,row=0,column=0,rowspan=None,columnspan=None):
    storeObj=tk.Label(source,text=text)
    storeObj.grid(row=row,column=column,rowspan=rowspan,columnspan=columnspan)
    return storeObj

class Application(tk.Frame):

    def __init__(self,title):
        tk.Frame.__init__(self)
        self.master.title(title)
        self.option_add('*Font','aerial 20 bold')
        self.pack(expand=tk.YES, fill=tk.BOTH)

        #widget for quiz app
        frame=iQuiz(self,column=1)
        frame.config(width=1000,height=500)
        frame.grid_propagate(0)
        que_label=label(frame,"question is here",row=1)
        opt1=radioButton(frame,"Option A is here",row=2)
        opt2=radioButton(frame,"Option B is here",row=3)
        opt3=radioButton(frame,"Option C is here",row=4)
        opt4=radioButton(frame,"Option D is here",row=5)
        ans_label=label(frame,"\nanswer will be shown on click of show me answer",row=6)
        answer=button(frame,"Show me answer",row=7)

        frame_pre=iQuiz(self,column=0)
        pre=button(frame_pre,'Previous')
        pre.config(bg='Powder blue',fg='white')

        frame_next=iQuiz(self,column=2)
        nxt=button(frame_next,'Next')
        nxt.config(bg='powder blue',fg='white')

if __name__=='__main__':
    Application('Quiz App').mainloop()


texts: Creating the buttons on a calculator using a for-loop

texts:
How can I make the for-loop more compact by using functions for actionlistener?

package räknare;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import java.awt.event.ActionListener;
import java.awt.Font;
import java.awt.event.ActionEvent;

public class miniräknare {

    static JFrame frame;
    static JTextField textField;
    static JButton[] nummerButton;
    static String Inmatning= null;
    static double talOne;
    static double talTwo;
    static double resultat;
    static String räknesätt;
    static String svar;
    public static void main(String[] args) {
    Inmatning = new String();
    nummerButton=new JButton [10];
    frame=new JFrame("Kalkylatorn");
    frame.setBounds(100,100,270,450);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);
    textField= new JTextField();
    textField.setHorizontalAlignment(SwingConstants.RIGHT);
    textField.setBounds(10,22,234,62);
    frame.getContentPane().add(textField);
    textField.setColumns(10);

    for (int i=1 ; i<10 ; i++) {
        nummerButton[i]= new JButton(String.valueOf(i));
        int kolumn =((i-1)%3);
        int horisont=((i-1)/3);
        nummerButton[i].setBounds((10+(kolumn*60)),(220-(horisont*60)),50,50);
        nummerButton[i].setFont(new Font("Tahoma", Font.BOLD, 20));
        frame.getContentPane().add(nummerButton[i]);
        nummerButton[i].addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                    JButton myButton = (JButton)e.getSource();
                    String Inmatning= textField.getText() + myButton.getText();
                                textField.setText(Inmatning);                                   }
        });
    }