texts: Rotational Symmetry Indexing in a 1D “Square” Array

texts:
I managed to find a way to rotate a slice in-place (previous question on SO). The slice is linear, but represents a 2d square of elements.
Is this approach efficient?
Please check the previous question linked above if anything is unclear about the algorithm.
Code
enum Rotation {
    Clockwise,
    Counterclockwise,
}

fn rotate_square_slice<T>(slice: &mut [T], s: usize, rotation: Rotation) {
    // iterate ringwise, from outer to inner
    // skip center when size % 2 == 1
    for r in 0..s / 2 {
        // for all unique indices under rotational symmetry ...
        for i in 0..s - (2 * r) - 1{
            // ... get their 4 corresponding positions ...
            let a = s * (   r   ) +   r+i   ;
            let b = s * (  r+i  ) +  s-r-1  ;
            let c = s * ( s-r-1 ) + s-r-i-1 ;
            let d = s * (s-r-i-1) +    r    ;

            //... and swap them in the correct direction.
            match rotation {
                Rotation::Clockwise => {
                    slice.swap(a, b);
                    slice.swap(a, c);
                    slice.swap(a, d);
                },
                Rotation::Counterclockwise => {
                    slice.swap(a, b);
                    slice.swap(c, d);
                    slice.swap(b, d);
                }
            }
        }
    }
}


texts: Solved the problem. Might some cleanup and/or advise

texts:
I wanted to display 1 outcome of 1 single custom field or attribute in the category overview, using a third party customfield extension in my J! and VM website. I got it working using the code below. As this is the first time I actually write PHP and MySQL stuff myself, I was pretty proud, but also thinking 'this can probably be done better..'

<?php
//first get the customfieldid for the product where the custom id is 10
$db2 = JFactory::getDBO();
$db2->setQuery("SELECT virtuemart_customfield_id FROM #__virtuemart_product_customfields WHERE virtuemart_product_id=".$product->virtuemart_product_id." and virtuemart_custom_id=10 ;");
$db2->query();
$customFieldId = $db2->loadResult();

//make a database connection and find the field record that contains the customfield string
$db = JFactory::getDBO();
$db->setQuery("SELECT customsforall_value_id FROM #__virtuemart_product_custom_plg_customsforall WHERE virtuemart_product_id=".$product->virtuemart_product_id." and customfield_id=".$customFieldId." ;");
$db->query();
$staatValueId = $db->loadResult();

//knowing the customsforall id with the product, saved in a $ we get the attached string
$customStaat = JFactory::getDBO();
$customStaat->setQuery("SELECT customsforall_value_name FROM #__virtuemart_custom_plg_customsforall_values WHERE virtuemart_custom_id=10 and customsforall_value_id=".$staatValueId." ;");
$customStaat->query();
$resultStaat = $customStaat->loadResult();

//display the state
echo "".$resultStaat."";
?>

Can I do this better, or clean things up?


texts: Returning a validation error from a command handler

texts:
public class AddPostCommand
{
    public string Title { get; set; }
    public string Body { get; set; }
    public bool Published { get; set; }
}

public class AddPostCommandHandler
{
    public string Handle(AddPostCommand command)
    {
        var param = new
        {
            Slug = command.Title.Replace(" ", "-"),
            PublishDate = command.Published ? DateTime.Now : DateTime.MinValue,
            command.Title,
            command.Body,
            command.Published
        };

        // I removed the data access code for brevity.

        return param.Slug;
    }
}

I have a command and I have a command handler. I also have a controller that invokes the command handler.

Within the command handler I generate a slug (definition). In the database, the slug column has a unique constraint - there must be no duplicate slugs.

I need to find a clean way to inform the caller that they have effectively provided to the command handler a duplicate slug.

I do not perform any validation in the command handler yet. This is the simplest solution I can come up with:

PostRequestHandler requestHandler = new PostRequestHandler();
AddPostCommandHandler commandHandler = new AddPostCommandHandler();

[HttpPost]
public ActionResult AddPost(AddPostCommand command)
{
    string expectedSlug = command.Title.Replace(" ", "-");
    PostRequest request = new PostRequest { Slug = expectedSlug };
    PostModel post = requestHandler.Handle(request);
    if (post != null)
    {
        ModelState.AddModelError("", "A post with this title already exists.");
        return View(post);
    }

    string actualSlug = commandHandler.Handle(command);
    return RedirectToAction("Index", "Post", new { actualSlug });
}

I abhor this code.

My most pressing concern is that I do not want the caller to have to generate the slug. I am also concerned that the controller action is becoming too big.

How might I communicate to the controller that an error has occurred (so that an error message can be displayed to the user) in a clean way?


texts: Converting a state from hash into a JavaScript object

texts:
This code gets a state from a query string hash part, converts the hash part to a JavaScript object and then tries to get a view, dashboard or a mode value. If those keys are not present in object, it returns $.pulse.qs.views.home.

Does this JavaScript code with ternary operator follow common best practices? It looks like ternary operator abuse and it is not readable. Or is it just me?

var state = $.query.getState();
var screen = state[$.pulse.qs.view]
    ? state[$.pulse.qs.view]
    : state[$.pulse.qs.dashboard] || state[$.pulse.qs.mode]
        ? $.pulse.qs.views.dashboard
        : $.pulse.qs.views.home;


texts: Check if the array contains duplicate values

texts:
The problem is old and simple but I wanted to try it in a different way. With some extra memory I have created an OOP-based solution. Hopefully it doesn't hurt in the interview.

import java.util.*;
import java.lang.*;
import java.io.*;

class Main {
  static class Solution {
    private int[] items;
    private List<Integer> duplicates;

    Solution(int[] items) {
      this.items = items;
      this.duplicates = new ArrayList<>();
      if (items.length > 1) {
        solve();
      }
    }

    private void solve() {
      Set<Integer> appeared = new HashSet<>();
      for (int item : items) {
        if (!appeared.add(item)) {
          duplicates.add(item);
        }
      }
    }

    public boolean hasDuplicate() {
      return duplicates.size() > 0 ? true : false;
    }
  }

  private static int[] readInput() {
    Scanner s = new Scanner(System.in);
    int N = s.nextInt();
    int[] arr = new int[N];

    for (int i = 0; i < N; i++) {
      arr[i] = s.nextInt();
    }
    return arr;
  }

  private static void tests() {
    // Falsy
    System.out.println(new Solution(new int[]{}).hasDuplicate());
    System.out.println(new Solution(new int[]{1}).hasDuplicate());
    System.out.println(new Solution(new int[]{1, 2}).hasDuplicate());
    System.out.println(new Solution(new int[]{Integer.MIN_VALUE, Integer.MAX_VALUE}).hasDuplicate());

    // Truthy
    System.out.println(new Solution(new int[]{1, 1}).hasDuplicate());
    System.out.println(new Solution(new int[]{Integer.MAX_VALUE, Integer.MAX_VALUE}).hasDuplicate());
    System.out.println(new Solution(new int[]{Integer.MIN_VALUE, Integer.MIN_VALUE}).hasDuplicate());
  }

  public static void main(String[] args) {
    //System.out.println(new Solution(readInput()).hasDuplicate());
    tests();
  }
}

Note: I cannot use JUnit or any testing framework during the interview.


texts: Finding an equilibrium index in an int array

texts:
Here is a programming challenge from codility

  A zero-indexed array A consisting of N integers is given. An
  equilibrium index of this array is any integer P such that 0 ≤ P < N
  and the sum of elements of lower indices is equal to the sum of
  elements of higher indices, i.e.

  A[0] + A[1] + ... + A[P−1] = A[P+1] + ... + A[N−2] + A[N−1].

  Sum of zero elements is assumed to be equal to 0. This can happen if P
  = 0 or if P = N−1.

  For example, consider the following array A consisting of N = 8
  elements:

  A[0] = -1   A[1] =  3   A[2] = -4   A[3] =  5   A[4] =  1   A[5] =
  -6   A[6] =  2   A[7] =  1

  P = 1 is an equilibrium index of this array, because:

  • A[0] = −1 = A[2] + A[3] + A[4] + A[5] + A[6] + A[7]

  P = 3 is an equilibrium index of this array, because:

  • A[0] + A[1] + A[2] = −2 = A[4] + A[5] + A[6] + A[7]

  P = 7 is also an equilibrium index, because:

  • A[0] + A[1] + A[2] + A[3] + A[4] + A[5] + A[6] = 0

  and there are no elements with indices greater than 7.

  P = 8 is not an equilibrium index, because it does not fulfill the
  condition 0 ≤ P < N.

  Write a function:

class Solution { public int solution(int[] A); }

  that, given a zero-indexed array A consisting of N integers, returns
  any of its equilibrium indices. The function should return −1 if no
  equilibrium index exists.

  For example, given array A shown above, the function may return 1, 3
  or 7, as explained above.

  Assume that:

  • N is an integer within the range [0..100,000];
  • each element of
  array A is an integer within the range
  [−2,147,483,648..2,147,483,647].

  Complexity:

  • expected worst-case time complexity is \$O(N)\$;
  • expected worst-case
  space complexity is \$O(N)\$, beyond input storage (not counting the
  storage required for input arguments).

  Elements of input arrays can be modified.

I think my whole solution is \$O(N)\$ because both my methods are \$O(N)\$. Is that right?
I believe I used some space to generate the sums and it Is still \$O(N)\$. Is it right?

Please review my code:

class Equilibrium {

    public int getEquilibrium(int[] A) {
        long[] sums = generateSums(A);
        long lowSum = 0L;
        int res = -1;
        for (int i = 0; i < A.length; i++) {
            if (lowSum == sums[i+1]) {
                res = i;
                break;
            }
            lowSum += A[i];
        }
        return res;
    }

    // I used long to handle sums greater than 32 bits
    public long[] generateSums(int[] A) {
        // I added another index (default value is 0) to handle the last value (E.G. the sum of previous elements is 0, so the equilibrium index should be the last value because there are no other items after it. I used the newly added index to handle it.)
        long[] res = new long[A.length+1];
        for (int i = A.length-1; i >= 0; i--) {
            res[i] = i+1 == A.length ? A[i] : res[i+1]+A[i];
        }
        return res;
    }
}

Did I follow all the requirements in the problem? How can I improve this and make it faster?


texts: Proper way to work with stored procedures in Entity Framework Core

texts:
I need to work with stored procedures, with the help of Entity Framework Core. This is my function:

public async Task<bool> CheckIfUserRegistered(string phoneNumber, DateTime dateOfBirth)
    {
        if (string.IsNullOrWhiteSpace(phoneNumber))
        {
            return false;
        }
        using (var cmd = _dbContext.Database.GetDbConnection().CreateCommand())
        {
            cmd.CommandText = "dbo.CheckIfUserRegistered";
            cmd.CommandType = CommandType.StoredProcedure;

            cmd.Parameters.Add(new SqlParameter("@phoneNumber", SqlDbType.NVarChar) { Value = phoneNumber });
            cmd.Parameters.Add(new SqlParameter("@dateOfBirth", SqlDbType.Date) { Value = dateOfBirth });

            cmd.Parameters.Add(new SqlParameter("@registered", SqlDbType.Bit) { Direction = ParameterDirection.Output });

            if (cmd.Connection.State != ConnectionState.Open)
            {
                cmd.Connection.Open();
            }

            await cmd.ExecuteNonQueryAsync();

            return (bool)cmd.Parameters["@registered"].Value;
        }
    }

I'm not sure, with the correctness of this function, is this the right way to work with stored procedures in EF Core? Don't I have problems with forgotten connections, memory leakings, etc?


texts:
I often come around a requirement where we have to perform a repetitive task on the user's screen (for eg, updating a counter like flash sale/ live class timer, autoscrolling the banner, etc) .
I have written this small file which performs a basic task of pressing a button every 2 seconds for a total of 4 times as a general example and my approach to this problem
Please review and provide your inputs about weather this would be a correct approach or not.
class AVCActivity : AppCompatActivity() {
    private var scrollInterval = 0
    private var run4Times = false
    private val handler = Handler()
    private var count = 0

    override fun onCreate(b:Bundle) {
        scrollInterval = 2000
        run4Times = api.runRepetitiveTask()
        // task will start in onResume
    }

    override fun onPause() {
        super.onPause()
        handler.clearStack()
    }

    override fun onResume() {
        super.onResume()
        if(run4Times){
            handler.clearStack().postDelayed(scrollTask,scrollInterval.toLong())
        }
    }

    private fun Handler.clearStack():Handler{
        this.removeCallbacksAndMessages(null)
        return this
    }

    private val scrollTask = object : Runnable{
        override fun run() {
            if(count < 4){
                count + =1
                btHello?.performOnClick()
                handler.clearStack().postDelayed(this,scrollInterval.toLong())
            }
            else{
                run4Times = false
                handler.clearStack()
            }
        }
    }
}

Some details:

handler fires the runnable every 2 seconds via recursion  for 3 times . on the 4th time, the runnable clears the handler and closes handler recursion
handler gets started in onResume and stopped in onPause to handle case where user has closed the screen before completion of the original task. The condition to weather make the handler fire the runnable is handled via a global variable, initialised in onCreate() .i,e only once .
handler is NOT started in onCreate  because this will cause the handler to run same runnable twice(since onCreate->onResume) . this usually causes a bug where we assume the runnable to run once every 2 seconds, but ends up with 2 runnables running every 2 seconds
every postCall is made after handler.removeCallbacksAndMessages(null) (via extension function clearStack() ) , thereby removing any unprocessed runnables. this is especially required in a case of onResume() , since onResume can be called multiple times and this could lead to same problem as point 3. using this function prevents this case from occurring.
variables like handler and runnable are global to prevent duplication/re assigning.
it is safe to access ui views in runnable  because the handler is going to run the runnable in main thread (my assumption)

Anything else should i be considering? Is it a good general approach? any memory leaks in this approach?
PS :  I think this question might have been asked before, but i am not sure if this has been asked in context to Android/kotlin. Kindly point me to an already asked question with better approach if this is repetitive


texts: Simple python code takes command line argument for file location and tokenizes text

texts:
The usage of this Python program is:

python ~/test.py test.txt

Here is the source:

import sys
#Open file passed by terminal
if len(sys.argv)==2:

    try:
        open(sys.argv[1])
        with open(sys.argv[1]) as inputfile:
            #Iterate through lines
            for line in inputfile:
                #tokenize
                words=line.split()
                #print tokens separated by commas
                print(",".join(words))
        inputfile.close
        sys.exit(0)

    except:
        sys.exit(-1)
sys.exit(-1)

This is the "test.txt"

\ / input("       ")
input(print("some text"))

             one        two                 three
other                    things                  here
             more stuff on this    line

garbage
\n
%20

and it should output (which it does):

\,/,input(",")
input(print("some,text"))

one,two,three
other,things,here
more,stuff,on,this,line

garbage
\n
%20

But I'm wondering if there is some unexpected way to break it. Is there a way to nest carriage returns or something somewhere? Oh, and I realize that I can accomplish the same thing with:

print(",".join(line.split()))

But for this specific instance, I would like to separate the two steps.


texts: Changing the state of another entity into the constructor method

texts:
I have a Clock class who inherites from pyglet.clock.Clock and behaves like a Singleton.

Into the constructor method I have the following line:

pyglet.clock.set_default(self)

Who changes the state of the default clock of pyglet, setting my Clock object as the default clock.

The constructor method leaves the Clock object into a valid state (without this line in the constructor the clock don't tick!).

Changing another entity state in the constructor:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import pyglet

import singleton

class Clock(pyglet.clock.Clock):
    __metaclass__ = singleton.Singleton

    def __init__(self):
        super(Clock, self).__init__()

        pyglet.clock.set_default(self)

class Test(object):
    def update(self, dt):
        print dt

w = pyglet.window.Window()
@w.event
def on_draw():
    w.clear()

t = Test()

c = Clock()
c.schedule_interval(t.update, 1/60.0)

pyglet.app.run()

On the other hand I can do:

Calling pyglet.clock.set_default outside of the constructor:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import pyglet

import singleton

class Clock(pyglet.clock.Clock):
    __metaclass__ = singleton.Singleton

    def __init__(self):
        super(Clock, self).__init__()

class Test(object):
    def update(self, dt):
        print dt

w = pyglet.window.Window()
@w.event
def on_draw():
    w.clear()

t = Test()

c = Clock()
pyglet.clock.set_default(self)
c.schedule_interval(t.update, 1/60.0)

pyglet.app.run()

In this case the call:

pyglet.clock.set_default(self)

Is outside of the constructor method and then the constructor method don't change the state of another entity.

The questions:

What is the solution more elegant or pythonic?
Is any of these solutions a best practice?
How do you resolve this issue?


texts:
This is my first program in C. I'd rather not form any bad habits now. Is there anything that looks like bad practice, or something just looks wrong?

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

int main(void) {
    srand(time(NULL));
    int r = rand() % 10 + 1;
    int correct = 0;
    int guess;
    int counter = 0;

    printf("Guess my number! ");

    do {
        scanf("%d", &guess);
        if (guess == r) {
            counter++;
            printf("You guessed correctly in %d tries! Congratulations!\n", counter);
            correct = 1;
        }

        if (guess < r) {
            counter++;
            printf("Your guess is too low. Guess again. ");
        }

        if (guess > r) {
            counter++;
            printf("Your guess is too high. Guess again. ");
        }
    } while (correct == 0);

    return 0;
}


texts: Code to find the sum of the product of all size-n combinations of an array

texts:
The title is a bit of a mouthful, so here's a quick example:

You've got an array, maybe just the digits 1-3, and you want to get the sum of product of all size-2 combinations of the array. Those combinations are (1,2), (1,3), and (2,3), so the answer I'm looking for is this:

$$1\cdot2+1\cdot3+2\cdot3=11$$

Except now, the array is about 3-4 orders of magnitude in size, and the problem is kinda intractable beyond size-2 combinations.

Here's the code I have made to do the task:

import numpy as np
from itertools import combinations as comb

#A is the target array, in this case, a random array of 1000 elements.
#B is a iterator of length-2 tuples which should act as indices for reading A.

n = 2
A = np.random.rand(1000)
B = comb(range(1000),n)

print np.sum(np.array([np.prod(A[i,]) for i in B]))

The code is fairly condensed, but is kinda simple.  It first makes an iterator object containing all the unique combinations of the indices of A, and then uses those tuples in an (ab)use of numpy's array slicing notation to get reference those indices, find the product there, and then sum it all together.

The greatest weakness of this code, I would guess, is the list comprehension, since it doesn't make use of numpy functions.  As it stands, the code runs fast enough for size-2 combinations, but falls flat for anything higher.  I would like it to at least be tractable for size-3 combinations, but as it stands, this code doesn't make the cut.

Any suggestions or things to look into would be greatly appreciated.


texts:
So I've been learning about MVVM and I had a problem. I often had to start a thread to download or do some longer task in background and when it is done change some properties so the UI updates. The problem is that the UI will update only if I changed it from the main thread. So I often had to create DispatchTimers to wait for the thread to finish and then execute some code in main. Well this is my solution to it.
With this class you can simply go to your ViewModel constructor and do something like this:
ViewModelEventHandler.RegisterEventListener("EventName", EventAction);

EventAction being an action that is executed when the event is raised.
You can simply create an async Task that does its work in the background and it raises the event "EventName" and then EventAction() is executed in main thread. You just have to put new ViewModelEventHandler(); inside your main function.
I also use it a lot for communication between view models. You can raise an event in view model A and a completely unrelated view model B can execute code.
Here is my code:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Windows.Threading;

namespace MVVM {
  public class EventData < T1, T2 > {
    public T1 eventState {
      get;
      set;
    }
    public T2 subs {
      get;
      set;
    }
  }

  class ViewModelEventHandler {
    // holds all events and their subscribed actions, the string is the event name, bool keeps track of if the event is currently raised, and List<Action> holds all the functions that will be executed when the event is raised
    private static Dictionary < string, EventData < bool, List<Action> >> eventList = new Dictionary < string, EventData <bool,List<Action> >> ();

    public ViewModelEventHandler() {
      DispatcherTimer timer = new DispatcherTimer();
      timer.Interval = TimeSpan.FromMilliseconds(1);
      timer.Tick += eventListen_Tick;
      timer.Start();
    }

    public static void RaiseEvent(string eventName) {
      try {
        eventList[eventName].eventState = true;
      }
      catch {}
    }

    public static void RegisterEventListener(string eventName, Action eventMethod) {
      foreach(var regEvent in eventList) {
        if (regEvent.Key == eventName) {
          eventList[eventName].subs.Add(eventMethod);
          return;
        }
      }

      eventList[eventName] = new EventData < bool, List < Action >> ();
      eventList[eventName].eventState = false;
      eventList[eventName].subs = new List < Action > ();
      eventList[eventName].subs.Add(eventMethod);

    }

    public static void RemoveEventListener(string eventName, Action eventMethod) {
      try {
        eventList[eventName].subs.Remove(eventMethod);
      }
      catch {}
    }

    public static void RemoveEvent(string eventName) {
      try {
        eventList.Remove(eventName);
      }
      catch {}
    }

    private void eventListen_Tick(object sender, EventArgs e) {
      foreach(var ev in eventList) {
        if (ev.Value.eventState) {
          ev.Value.eventState = false;
          foreach(Action eventSub in ev.Value.subs) {
            eventSub();
          }
        }
      }
    }

  }
}


texts: Decompress files files in a directory recursively

texts:
Currently I'm trying to redo this code to avoid the breaking line because of the 80 characters rule:

def decompress_all(directory_path, remove_after):
    """
    """
    try:
        if 0 in [ decompress(file_path, remove_after) \
                  for file_path in files_within(directory_path) ]:
            decompress_all(directory_path, remove_after)
        return 0
    except:
        return 1

Python version 2.6.


texts:
I have created a simple validation routine in php and i'm wanting to make sure I am doing things efficiently....

function reg_err_validation($reg_errors) {
        global $woocommerce;
        extract($_POST);

        if($firstname == '' )
        {
            $reg_errors->add( 'registration-error', __( 'Please enter First Name.', 'woocommerce' ));
        }
        if($lastname == '' )
        {
            $reg_errors->add( 'registration-error', __( 'Please enter Last Name.', 'woocommerce' ));
        }
        if($phone == '' )
        {
            $reg_errors->add( 'registration-error', __( 'Please enter Phone.', 'woocommerce' ));
        }
        if($address1 == '' )
        {
            $reg_errors->add( 'registration-error', __( 'Please enter address.', 'woocommerce' ));
        }
        if($city == '' )
        {
            $reg_errors->add( 'registration-error', __( 'Please enter City.', 'woocommerce' ));
        }
        if($postcode == '' )
        {
            $reg_errors->add( 'registration-error', __( 'Please enter Postcode.', 'woocommerce' ));
        }
        return $reg_errors;
}

It all works correctly but would like to try and simplify it if possible.


texts: Using fewer foreach loops to bind values to parameters in PDO

texts:
I want to make a query to order by the IN clause items. I read from another thread that I can use ORDER BY FIELD(a.id, val1,val2......) When binding values to parameters for two occurrences of $in, I ended up using two foreach loops:

      foreach ($tid as $t) {
        $users->bindValue($c++, $t);
      }
      foreach ($tid as $t) {
        $users->bindValue($c++, $t);
      }

Would you prefer other solutions? Is there any way to reduce it to one foreach loop?

    try
    {
      $dbh = new PDO("mysql:host=$hostname;dbname=$databasename", $username, $password);
      $tid = $_POST["tid"];
      $comma = "";
      $in  = str_repeat('?,', count($tid) - 1) . '?';
      $sql = "
              SELECT b.name,a.users
              FROM `table1` a INNER JOIN
              `table2` b ON a.id = b.id
              WHERE a.id IN ($in)
              GROUP BY a.id
              ORDER BY FIELD(a.id, $in)
             ";
      $users = $dbh->prepare($sql);
      $users->bindValue(1, $_SESSION["user_id"]);
      $c = 2;
      foreach ($tid as $t) {
        $users->bindValue($c++, $t);
      }
      foreach ($tid as $t) {
        $users->bindValue($c++, $t);
      }
      $users->execute();
      $dbh = null;

    }
    catch(PDOException $e)
    {
     echo $e->getMessage();
    }

$_POST["tid"] Content Example:

Array
(
    [0] => 215
    [1] => 391
)


texts:
I need to display a "caption" from a video but I cannot use built in captions provided by a vtt file for my situation. I created an array that stores the key,value pair (time, caption). I traverse that array every time the video time is updated and find which caption fits the current time. This solution works and I haven't had any issues (performance or otherwise) but it just feels brute force to me, I'm hoping someone can help me either refine what I have or guide me toward a more elegant solution. Any comments or criticism is appreciated.

 //this function is called whenever video time is updated
    this.onUpdateTime = function(currentTime, totalTime) {

        this.currentTime = currentTime;
        this.totalTime = totalTime;

        /*the for statement traverses the array chapters which contains
        [{"time": X,"caption": "XYZ"},...]*/

        for (var i = 0; i < $scope.chapters.length; i++) {

            /* the first if statement checks if (i is not the same as
            chapters.length (this was done to prevent an off by one error) and the time of
            the video is greater than or equal to time at chapters[i] and the time of the
            video is still less than time at the next chapter marker chapter[i+1]*/

            if (i != $scope.chapters.length - 1 && currentTime >= $scope.chapters[i].time && currentTime < $scope.chapters[i + 1].time) {

                /*set the caption to the value from chapters[i].caption*/

                $rootScope.caption = $scope.chapters[i].caption;

                /*I have never used $scope.$apply but it seemed to be needed to get the caption to display in my view*/

                $scope.$apply(); {

                    /*break the for loop so that it does not needlessly loop through the rest of the array after finding a match*/
                    break;
                }

                /*this if statement if for when i is equal to chapters.length -1, it is the final value in the array so it does
                not check against the "next value" like the previous if statement does because there is not next value*/

            } else if (currentTime >= $scope.chapters[i].time && i == $scope.chapters.length - 1) {

                /*set the caption to the value from chapters[i].caption*/

                $rootScope.caption = $scope.chapters[i].caption;

                /*I have never used $scope.$apply but it seemed to be needed to get the caption to display in my view*/

                $scope.$apply(); {

                    /*break the for loop so that it does not needlessly loop through the rest of the array after finding a match*/
                    break;
                }

                /*if there is not chapter marker at the current time*/
            } else {

                /*set the caption to a blank value because no match was found therefore there is no caption*/
                $rootScope.caption = "";
                $scope.$apply();
            }
        }
        // console.log("onUpdateTime function, currentTime is: " + currentTime);
        // console.log("onUpdateTime function, totalTime is: " + totalTime);
    };


texts: Generic methods for serializing and deserialzing xml files using streams followup

texts:
Recently I asked this question: Generic methods for serializing and deserialzing xml files using streams

However it has come to my attention that this gives me an (harmless) exception when trying to deserialize.

System.IO.FileNotFoundException occurred
  Message="Could not load file or assembly '[Containing Assembly of MyType].XmlSerializers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified."
  Source="mscorlib"
  FileName="[Containing Assembly of MyType].XmlSerializers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
  FusionLog=""
  StackTrace:
   at System.Reflection.Assembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection)
   at System.Reflection.Assembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection)

It is a well known problem and most people would fix it by adding this to their csproj:

<Target Name="AfterBuild" DependsOnTargets="AssignTargetPaths;Compile;ResolveKeySource" Inputs="$(MSBuildAllProjects);@(IntermediateAssembly)" Outputs="$(OutputPath)$(_SGenDllName)">
   <!-- Delete the file because I can't figure out how to force the SGen task. -->
   <Delete
     Files="$(TargetDir)$(TargetName).XmlSerializers.dll"
     ContinueOnError="true" />
   <SGen
     BuildAssemblyName="$(TargetFileName)"
     BuildAssemblyPath="$(OutputPath)"
     References="@(ReferencePath)"
     ShouldGenerateSerializer="true"
     UseProxyTypes="false"
     KeyContainer="$(KeyContainerName)"
     KeyFile="$(KeyOriginatorFile)"
     DelaySign="$(DelaySign)"
     ToolPath="$(TargetFrameworkSDKToolsDirectory)"
     Platform="$(Platform)">
      <Output
       TaskParameter="SerializationAssembly"
       ItemName="SerializationAssembly" />
   </SGen>
</Target>

However I've tried something different namely:

public static T DeserializeObject<T>(this Stream stream) where T : IXmlSerializable
{
    Parameters.RequireNotNull(stream, "stream");

    using (var xmlTextReader = XmlReader.Create(stream))
    {
        var importer = new XmlReflectionImporter()
        var mapping = importer.ImportTypeMapping(typeof(T));
        var serializer = new XmlSerializer(mapping);

        T result = (T)serializer.Deserialize(xmlTextReader);
        stream.Close();
        return result;
    }
}

So my question, is this good code? is this a proper work around?


texts:
I started with VBA yesterday. Could this code be improved?

Private Sub Worksheet_Change(ByVal target As Range)
    If target.Column = 3 Then
        Call Modul1.AutoFill(target)
    End If
End Sub

Option Explicit

Sub AutoFill(activeCell As Range)
    Dim storedData As Range: Set storedData = GrabStoredData(activeCell.Value)
    If Not storedData Is Nothing Then
        Call FillRowWith(activeCell, storedData)
    End If
End Sub

Private Function GrabStoredData(itemName As String) As Range
    Dim itemCell As Range
    Set itemCell = Sheets("SourceSheet").Range("A:A").Find(what:=itemName, lookat:=xlWhole)

    If Not itemCell Is Nothing Then
        Set GrabStoredData = Sheets("SourceSheet").Range("B" & itemCell.row & ":G" & itemCell.row)
    End If
End Function

Private Sub FillRowWith(activeCell As Range, storedData As Range)
    Dim counter As Integer
    For counter = 1 To 6
        Sheets("TargetSheet").Cells(activeCell.row, activeCell.Column + counter).Value = storedData.Offset(0, counter - 1).Value
    Next counter
End Sub

We have a SourceSheet that works as the "Database". The SourceSheet has 7 columns, with the first one used to identify an item or order. The other 6 columns contain information.

Lets say we put an order in "TargetSheet" which already exists in "SourceSheet". It will find the order in "SourceSheet" and take the information in the 6 columns and replace 6 columns in "TargetSheet" with that information.

This demo should show it better.


texts: Maintaining users in a Dovecut user database

texts:
I learn BASH scripting occasionally from time to time, now I am working on a simple bash script that serves to maintain Dovecot user database. The general purpose of the script is able to list, add or delete user entries in the specified file. Please add some comments about the code - common mistake and etc. I want to learn more about code simplicity and avoiding bad habits.

#!/bin/bash

USERDB="/etc/dovecot/users"
MAILBOXMAP="/etc/postfix/virtual/virtual-mailbox-maps.cf"

## Add user function

add_user () {

# Reading username

while [[ -z "$USERNAME" ]]; do
    echo -n "Please enter username: "
    read "USERNAME"
done

# Reading domain name

while [[ -z "$DOMAIN" ]]; do
    echo -n "Please enter domain name: "
    read DOMAIN
done

# Reading password and generating hash with doveadm pw

while [[ -z "$PASSWORD" ]]; do
    echo -n "Please enter user password: "
    read "PASSWORD"
done

if [[ -n "$PASSWORD" ]]; then
    USERPASS="$(doveadm pw -p $PASSWORD -s SHA512-CRYPT)"
fi

# Adding provided credentials to Dovecot userdb

echo "Adding user credentials to userdb..."

echo "$USERNAME@$DOMAIN:$USERPASS:::" >> "$USERDB"

# Adding provided user@domain to postfix mailbox map

echo "Adding user credentials to postfix map..."

echo "$USERNAME@$DOMAIN $DOMAIN/$USERNAME" >> "$MAILBOXMAP"

# Hashing the map

if [[ -f "$MAILBOXMAP" ]]; then
     postmap hash://"$MAILBOXMAP"
     echo "Hashing map is done!"
else
     echo "Postfix map not exist or have been moved to another directory!"
     exit 1
fi
exit 0
}

## List all users function

list_users () {

if [[ -f "$USERDB" ]]; then
    awk -F: '/./'' {print $1} ' "$USERDB"
else
    echo "User database not exist or have been moved to another directory!"
    exit 1
fi
}

## Delete user function

delete_user () {
if [[ -n "$DELUSER" ]]; then
    sed -i "/^$DELUSER$/d" $USERDB $MAILBOXMAP && echo "User account have been  deleted!"
else
    echo "User not found!"
    exit 1
fi
}

case "$1" in
 add|-a)
    add_user
    ;;
 list|-l)
    list_users
    ;;
 delete|-d)
    shift
    deluser="$1"
    delete_user
    ;;
 *)
    echo "Unknown command"
    ;;
esac


texts: SICP exercise 3.47 - implementing a semaphore in terms of mutexes

texts:
Can anyone check my solution to the first part of exercise 3.47 in SICP? Thanks.

Exercise 3.47: A semaphore (of size n) is a generalization of a mutex.
Like a mutex, a semaphore supports acquire and release operations, but
it is more general in that up to n processes can acquire it
concurrently. Additional processes that attempt to acquire the
semaphore must wait for release operations. Give implementations of
semaphores

in terms of mutexes
...

I have a local state called number-of-processes which tracks the processes that acquired the semaphore. Since it is mutated when acquire and release operations occur, I used a mutex to prevent concurrent writes.
Here is my code: I displayed the outputs of some variable for testing.
> (define (make-serializer n)
    (let ((semaphore (make-semaphore n)))
      (lambda (p)
        (define (serialized-p . args)
          (semaphore 'acquire)
          (let ((val (apply p args)))
            (newline)
            (display val)
            (semaphore 'release)
            val))
        serialized-p)))

  (define (make-semaphore n)
    (let ((mutex (make-mutex))
          (number-of-processes 0))
      (define (acquire)
        (mutex 'acquire)
        (if (< number-of-processes n)
            (begin (set! number-of-processes (+ number-of-processes 1))
                   (display 'acquired)
                   (mutex 'release))
            (begin (mutex 'release)
                   (acquire))))
      (define (release)
        (mutex 'acquire)
        (if (> number-of-processes 0)
            (begin (set! number-of-processes (- number-of-processes 1))
                   (newline)
                   (display 'released)
                   (newline))
            (error "error!"))
        (mutex 'release))
      (define (the-semaphore m)
        (cond ((eq? m 'acquire) (acquire))
              ((eq? m 'release) (release))))
      the-semaphore))

I tested it like this:
(define s (make-serializer 2))
(define p1 (s (lambda () 1)))
(define p2 (s (lambda () 2)))
(define p3 (s (lambda () 3)))
(define p4 (s (lambda () 4)))
(define p5 (s (lambda () 5)))

The outputs are:
> (parallel-execute p1)
acquired
1
released
(1)
> (parallel-execute p1 p2)
acquired
1
acquired
2
released
released
(1 2)
> (parallel-execute p1 p2 p3)
acquired
1
acquired
2
released
acquired
3
released
released
(1 2 3)
> (parallel-execute p1 p2 p3 p4)
acquired
1
acquired
2
released
acquired
4
released
acquired
3
released
released
(1 2 4 3)
> (parallel-execute p1 p2 p3 p4 p5)
acquired
4
acquired
1
released
acquired
2
released
released
acquired
5
acquired
3
released
released
(4 1 2 5 3)

I believe my procedure is working correctly. All my tests passed. How can I improve this code? Thanks.


texts:
I wanted to do some statistics over the history of a Git repository. At first I tried using GitPython, but it wasn't as trivial as I imagined it to be. In the end, I just call the necessary git commands with the submodule module.

Can this code be considered clean and readable or does it have some style issues?

import argparse
import os
import subprocess

def main(args):
    if not os.path.isdir(args.path):
        print "not a directory"
        return
    if ".git" not in os.listdir(args.path):
        print "not a repo"
        return

    os.chdir(args.path)

    commitIDs = []
    start = 0       #load commits in batches, to avoid too long hangs
    max_count = 100
    while True:
        text = subprocess.check_output(["git", "rev-list", args.branch, "--max-count=%s" % max_count, "--skip=%s" % start])
        start += max_count
        for line in text.splitlines():
            commitIDs.append(line)
        #print "loaded", len(commits), "commits"
        if len(text.splitlines()) != max_count:
            break

    for commitID in commitIDs[::-args.skip]:    #start with the oldest commit
        print commitID
        #do something with the commit
        #for example:
        #devnull = open(os.devnull, 'w')
        #subprocess.call(["git", "checkout", commitID], stdout=devnull)

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('path', nargs="?", default=".")
    parser.add_argument('--branch', '-b', default="master")
    parser.add_argument('--skip', '-s', type=int, default=1, help='use every n-th commit')
    args = parser.parse_args()

    main(args)

Update:

import argparse
import os
import subprocess
import sys
import git

def main(args):
    try:
        repo = git.Repo(args.path)
    except:
        sys.exit("no such repo")

    try:
        text = repo.git.rev_list(args.branch).splitlines()
    except:
        sys.exit("no such branch")

    commit_ids = text[::args.skip]

    print "loaded %s commits" % len(commit_ids)

    for commit_id in commit_ids[::-1]:  #start with the oldest commit
        print commit_id
        #do something with the commit
        #for example:
        #repo.git.checkout(commit_id)

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('path', nargs="?", default=".")
    parser.add_argument('--branch', '-b', default="master")
    parser.add_argument('--skip', '-s', type=int, default=1, help='use every n-th commit')
    args = parser.parse_args()

    main(args)
    sys.exit(0)


texts: Reducing the amount of List in a WebScraper

texts:
At the moment, I'm learning and experimenting on the use of web scraping content from different varieties of web pages. But I've come across a common smelly code among several of my applications. I have many repetitive List that has data being append to them.

from requests import get
import requests
import json
from time import sleep
import pandas as pd

url = 'https://shopee.com.my/api/v2/flash_sale/get_items?offset=0&limit=16&filter_soldout=true'
list_name = []
list_price = []
list_discount = []
list_stock = []

response = get(url)
json_data = response.json()

def getShockingSales():
    index = 0
    if response.status_code is 200:
        print('Response: ' + 'OK')
    else:
        print('Unable to access')
    total_flashsale = len(json_data['data']['items'])
    total_flashsale -= 1
    for i in range(index, total_flashsale):
        print('Getting data from site... please wait a few seconds')
        while i <= total_flashsale:
            flash_name = json_data['data']['items'][i]['name']
            flash_price = json_data['data']['items'][i]['price']
            flash_discount = json_data['data']['items'][i]['discount']
            flash_stock = json_data['data']['items'][i]['stock']
            list_name.append(flash_name)
            list_price.append(flash_price)
            list_discount.append(flash_discount)
            list_stock.append(flash_stock)
            sleep(0.5)
            i += 1
        if i > total_flashsale:
            print('Task is completed...')
            return

getShockingSales()
new_panda = pd.DataFrame({'Name': list_name, 'Price': list_price,
                          'Discount': list_discount, 'Stock Available': list_stock})

print('Converting to Panda Frame....')
sleep(5)
print(new_panda)

Would one list be more than sufficient? Am I approaching this wrongly.


texts:
This is my answer for
https://www.hackerrank.com/challenges/construct-the-array/problem
(Passes all the test cases)

Problem

  Your goal is to find the number of ways to construct an array such
  that consecutive positions contain different values.

  Specifically, we
  want to construct an array with \$n\$ elements such that each element
  [contains a value] between \$1\$ and \$k\$, inclusive.
  We also want the first and last
  elements of the array to be \$1\$ and \$x\$. Given \$n\$, \$k\$ and \$x\$, find
  the number of ways to construct such an array.

  Since the answer may be
  large, only find answer modulo \$10^9 + 7\$

  For example, for \$n=4\$, \$k=3\$ and \$x=2\$ there are \$3\$ ways

Solution

public class Solution {
    public static final long MOD = 1_000_000_007L;

    public static long countArray(int n, int k, int x) {
        if (n < 3 || k < 2) return 0;
        if (n == 3 && x == 1) {
            return k - 1;
        }
        if (n == 3) {
            return k - 2;
        }
        long countOne = k - 1, countOther = k - 2, temp;
        for (int i = 4; i < n; i++) {
            temp = countOther * (k - 1) % MOD;
            countOther = (countOne % MOD + countOther * (k - 2) % MOD) % MOD;
            countOne = temp;
        }
        if (x == 1) {
            return countOther * (k - 1) % MOD;
        }
        return (countOne % MOD + countOther * (k - 2) % MOD) % MOD;
    }
}


texts:
I could use some review on this Auth class, as I'm sure it could use many improvements!

I wrote this fairly quickly, so please forgive any overseen bugs.

Example usage:

// Login a user
if (Auth::attempt($_POST['username'], $_POST['password']))
{
    echo 'You have successfully logged in.';
}

// Check if the user is a guest
if (Auth::guest())
{
    echo 'Please log in to see this page.';
}

// Logout a user
Auth::logout();

Source code:

<?php

class Auth {

    /**
     * Whether or not the user is currently logged in
     *
     * @var bool
     */
    public static $user;

    /**
     * Attempts to log a user in with the given credentials
     *
     * @param   string  $username
     * @param   string  $password
     * @return  bool
     */
    public static function attempt($username, $password)
    {
        global $db;

        $stmt = $db->prepare('SELECT * FROM `users` WHERE `username` = :username AND `password` = :password');
        $stmt->execute(array(':username' => $username, ':password' => $password));

        if ($user = $stmt->fetch(PDO::FETCH_ASSOC))
        {
            static::$user = $user;

            static::login($user['id']);

            return true;
        }

        return false;
    }

    /**
     * Login the user with the given id
     *
     * @param   int     $user_id
     * @return  void
     */
    public static function login($user_id)
    {
        if ($user_id)
        {
            $_SESSION['user_id'] = $user_id;
        }
    }

    /**
     * Log out the current user
     *
     * @return  void
     */
    public static function logout()
    {
        static::$user = null;

        $_SESSION = array();
        unset($_SESSION['user_id']);
        session_destroy();
    }

    /**
     * Checks if a user is currently logged in
     *
     * @return bool
     */
    public static function check()
    {
        return isset($_SESSION['user_id']);
    }

    /**
     * Checks if the current user is a guest
     *
     * @return  bool
     */
    public static function guest()
    {
        return ! isset($_SESSION['user_id']);
    }

}

I'm also not sure if using all static methods in the class could lead to problems later on?

I know there is currently no password hashing - I'm still working on the hashing method.


texts: Pick a random big word from a list of words using Python

texts:
I am trying to randomly pick a large word (7 letters or more in length) from a large text file of words.

I know that there has to be a better and more efficient way to do this.

def goalWord():
    with open("words.txt","r") as allWords:
        wordList = allWords.read()
        wordList = wordList.split()
        bigWords = []
        for word in wordList:
            if len(word) > 6:
                bigWords.append(word.upper())
        return random.choice(bigWords)

Here is the sample input:

A
a
aa
aal
aalii
aam
Aani
aardvark
aardwolf
Aaron
Aaronic
Aaronical
Aaronite
Aaronitic
Aaru
Ab
aba
Ababdeh
Ababua
abac
abaca
abacate
abacay

Output would be a random word from words.txt that is greater than 6 characters in length.


texts: Recursive method to return a set of all combinations

texts:
Can someone explain me how this code works or if it is possible to be written in another way? I tried it with just ArrayList but cannot figure it out.

public static Set<Set<Integer>> combinations(List<Integer> groupSize, int k) {

    Set<Set<Integer>> allCombos = new HashSet<Set<Integer>> ();
    // base cases for recursion
    if (k == 0) {
        // There is only one combination of size 0, the empty team.
        allCombos.add(new HashSet<Integer>());
        return allCombos;
    }
    if (k > groupSize.size()) {
        // There can be no teams with size larger than the group size,
        // so return allCombos without putting any teams in it.
        return allCombos;
    }

    // Create a copy of the group with one item removed.
    List<Integer> groupWithoutX = new ArrayList<Integer> (groupSize);
    Integer x = groupWithoutX.remove(groupWithoutX.size()-1);

    Set<Set<Integer>> combosWithoutX = combinations(groupWithoutX, k);
    Set<Set<Integer>> combosWithX = combinations(groupWithoutX, k-1);
    for (Set<Integer> combo : combosWithX) {
        combo.add(x);
    }
    allCombos.addAll(combosWithoutX);
    allCombos.addAll(combosWithX);
    return allCombos;
}


texts:
I have a function that deletes duplicate entries.  The highest ID is kept and the older ones are removed.

function:

DELETE [tableName]
FROM [tableName]
INNER JOIN (SELECT * , ROW_NUMBER() OVER
           (PARTITION BY [fork_id] ORDER BY ID DESC)
           AS RowNumber FROM [tableName])
Numbered ON [tableName].ID = Numbered.ID
WHERE RowNumber > 1

For example, it changes

|------|---------|--------|
|  ID  | fork_id |   Car  |
|------|---------|--------|
|  1   |    2    |  AUDI  | <--- removed
|  2   |    1    |  AUDI  |
|  3   |    2    |  BMW   |
|------|---------|--------|

to

|------|---------|--------|
|  ID  | fork_id |   Car  |
|------|---------|--------|
|  2   |    1    |  AUDI  |
|  3   |    2    |  BMW   |
|------|---------|--------|

The problem with that query is the execution time exceed time when with have many rows (more than 50k) in the table.

I have a primary key for the ID column

I'm In the sql server, I have a limitation about execution time.

  A connection can be cut off by the server for a number of reasons:

  Idle connection longer than 5 minutes.
  Long running query.
  Long running open transaction.
  Excessive resource usage.

  sources


texts: DRYing out my Sass, looping through selectors

texts:
Need help with DRYing out my Sass... there is just so much repetition in here:

.cta_foo {      @include linear-gradient(#f69c28,#b75d00,#b75d00); text-shadow: -1px -1px 0 #b85e00;
    &:hover {   @include linear-gradient(#FFAC41,#E77500,#E77500); } }
.cta_bar {      @include linear-gradient(#17b629,#0e831c,#0e831c); text-shadow: -1px -1px 0 #008A0F;
    &:hover {   @include linear-gradient(#25CF39,#179F27,#179F27); } }
.cta_baz {      @include linear-gradient(#67a9e4,#3a7ab2,#3a7ab2); text-shadow: -1px -1px 0 #4477a5;
    &:hover {   @include linear-gradient(#72B4EF,#448BCA,#448BCA); } }

I started out with an @each directive but just got confused quickly. I ask not just for this one instance but because I'm trying to wrap my head around maps and lists and loops and such.

Update

@mixin linear-gradient just generates a linear-gradient with fallback color:

@mixin linear-gradient($start,$end,$fallback) {
    background-color: $fallback; background-image: linear-gradient($start,$end);
    @include ms-filter($start,$end);
}


texts: Dynamic filtering and sorting with Entity Framework

texts:
I'm developing an application using ASP.NET MVC 3 and Entity Framework 4.1. In that application I have a lot of paged lists. Users can filter and sort these lists.

This results in code like the one below. I'm not really happy with this code. Is there a better way to do the filtering and sorting with Entity Framework?

Some of you might suggest putting that code into a service class and not in the controller, but that would just move the ugly code somewhere else. Instead of ugly code in a controller, I'd end up with ugly code in a service.

public UsersController : Controller
{
    private const int PageSize = 25;

    public ActionResult Index(int page = 1, string sort = "", UserSearchViewModel search)
    {
        // Get an IQueryable<UserListItem>
        var users = from user in context.Users
                    select new UserListItem
                    {
                        UserId = user.UserId,
                        Email = user.Email,
                        FirstName = user.FirstName,
                        LastName = user.LastName,
                        UsertypeId = user.UsertypeId,
                        UsertypeDescription = users.Usertype.Description,
                        UsertypeSortingOrder = users.Usertype.SortingOrder
                    };

        // Filter on fields when needed
        if (!String.IsNullOrWhiteSpace(search.Name)) users = users.Where(u => u.FirstName.Contains(search.Name) || u.LastName.Contains(search.Name));
        if (!String.IsNullOrWhiteSpace(search.Email)) users = users.Where(u => u.Email.Contains(search.Email));
        if (search.UsertypeId.HasValue) users = users.Where(u => u.UsertypeId == search.UsertypeId.Value);

        // Calculate the number of pages based on the filtering
        int filteredCount = users.Count();
        int totalPages = Convert.ToInt32(Math.Ceiling((decimal)filteredCount / (decimal)PageSize));

        // Sort the items
        switch(sort.ToLower())
        {
            default:
                users = users.OrderBy(u => u.FirstName).ThenBy(u => u.LastName);
                break;
            case "namedesc":
                users = users.OrderByDescending(u => u.FirstName).ThenByDescending(u => u.LastName);
                break;
            case "emailasc":
                users = users.OrderBy(u => u.Email);
                break;
            case "emaildesc":
                users = users.OrderByDescending(u => u.Email);
                break;
            case "typeasc":
                users = users.OrderBy(u => u.UsertypeSortingOrder);
                break;
            case "typedesc":
                users = users.OrderByDescending(u => u.UsertypeSortingOrder);
                break;
        }

        // Apply the paging
        users = users.Skip(PageSize * (page - 1)).Take(PageSize);

        var viewModel = new UsersIndexViewModel
                        {
                            Users = users.ToList(),
                            TotalPages = totalPages
                        };

        return View(viewModel);
    }
}


texts:
I have a bit reordering function for a radix 4 algorithm which takes around 600 000 cycles to do its job for 4096 elements of floats (real and imaginary parts):

void bit_r4_reorder(float* x, float* y, int N)// N = 4096
{
  int bits = 0;
  int i, j, k;
  float tempr, tempi;

  for (i = 0; i < MAXPOW; i++)//MAXPOW = 24
      if (pow_2[i] == N)
          bits = i;

  for (i = 0; i < N; i++)
  {
      j = 0;
      for (k = 0; k < bits; k += 2)
      {
         if (i & pow_2[k])     j += pow_2[bits - k - 2];
         if (i & pow_2[k + 1]) j += pow_2[bits - k - 1];
      }

  if (j > i)
  {
    tempr = x[i];
    tempi = y[i];
    x[i] = x[j];
    y[i] = y[j];
    x[j] = tempr;
    y[j] = tempi;
  }
 }
}

I've counted the cycles for the different parts of this function and it turns to be (maybe pretty obvious) that the last for() loop containing the swap part is what takes the most part of cycles.

Can you look at this code and give me some hints or suggestion on how I can optimize the code (if it is even possible)?


texts: Reading a text file that may have embedded nulls

texts:
I've always used fgets to read a file. However, I want to read a file that may have embedded \0. I thought of using ftell to query the size, but it doesn't seem to work on all files.

I've got a test file,

31 32 33 00 34 35 36 0A E2 82 AC 0D 0A 61

Here is my fgets.

#include <stdlib.h> /* EXIT */
#include <stdio.h>  /* printf perror fputc fread */
#include <string.h> /* strlen */
#include <errno.h>  /* errno */
#include <assert.h> /* assert */

int main(void) {
    char file[1000], *f = file, *a;
    const int granularity = 80;
    int is_done = 0;

    for( ; ; ) {
        /* Fail when contents bigger than the size;
         would be a good spot to use realloc. */
        if(granularity > sizeof file - (f - file))
            { errno = ERANGE; break; }
        if(!fgets(f, granularity, stdin))
            { if(ferror(stdin)) break; is_done = 1; break; }
        f += strlen(f);
    }

    for(a = file; a < f; a++) printf("%02hhX ", *a);
    fputc('\n', stdout);
    return is_done ? EXIT_SUCCESS : (perror("stdin"), EXIT_FAILURE);
}

Running this, (I'm on a UNIX-like machine,)

$ bin/fgets < test
31 32 33 E2 82 AC 0D 0A 61

Here is my fread.

#include <stdlib.h> /* EXIT */
#include <stdio.h>  /* printf perror fputc fread */
#include <errno.h>  /* errno */
#include <assert.h> /* assert */

int main(void) {
    char file[1000], *f = file, *a;
    const int granularity = 80;
    size_t read;
    int is_done = 0;

    for( ; ; ) {
        if(granularity > sizeof file - (f - file))
            { errno = ERANGE; break; }
        read = fread(f, 1, granularity, stdin);
        if(ferror(stdin)) break;
        assert(read >= 0 && read <= granularity);
        f += read;
        if(read != granularity) { is_done = 1; break; }
    }

    for(a = file; a < f; a++) printf("%02hhX ", *a);
    fputc('\n', stdout);
    return is_done ? EXIT_SUCCESS : (perror("stdin"), EXIT_FAILURE);
}

Running this,

$ bin/fread < test
31 32 33 00 34 35 36 0A E2 82 AC 0D 0A 61

I would like to know if this is pedantically correct and how I improve.


texts:
I've subclassed UI button and used it in my View Controller's viewDidLoad method, like so:

PLOTDefaultButton *createAccountBtn = [[PLOTDefaultButton alloc] init];
CGRect createAccountBtnFrame = createAccountBtn.frame;
createAccountBtnFrame.origin.x = 20;
createAccountBtnFrame.origin.y = self.view.bounds.size.height - 135;
createAccountBtnFrame.size.width = self.view.bounds.size.width - 40;
createAccountBtn.frame = createAccountBtnFrame;
[createAccountBtn setTitle:@"Create an account" forState:UIControlStateNormal];

createAccountBtn.backgroundColor = [UIColor plotYellow];
createAccountBtn.titleLabel.textColor = [UIColor colorWithRed:0.165 green:0.212 blue:0.267 alpha:1];
createAccountBtn.layer.shadowColor = [UIColor colorWithRed:0.831 green:0.106 blue:0.082 alpha:1].CGColor;

[createAccountBtn addTarget:self action:@selector(showCreateAccount:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:createAccountBtn];

PLOTDefaultButton *loginBtn = [[PLOTDefaultButton alloc] init];
CGRect loginBtnFrame = loginBtn.frame;
loginBtnFrame.origin.x = 20;
loginBtnFrame.origin.y = self.view.bounds.size.height - 67.5;
loginBtnFrame.size.width = self.view.bounds.size.width - 40;
loginBtn.frame = loginBtnFrame;
[loginBtn setTitle:@"Log in" forState:UIControlStateNormal];
[loginBtn addTarget:self action:@selector(showLogin:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:loginBtn];

And the UIButton subclass:

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor plotDarkBlue];
        self.titleLabel.textColor = [UIColor whiteColor];
        self.layer.cornerRadius = 5;
        self.layer.masksToBounds = NO;
        self.layer.borderWidth = 0;

        self.layer.shadowColor = [UIColor colorWithRed:0.086 green:0.110 blue:0.141 alpha:1].CGColor;
        self.layer.shadowOpacity = 1;
        self.layer.shadowRadius = 0;
        self.layer.shadowOffset = CGSizeMake(0, 3);

        self.titleLabel.font = [UIFont fontWithName:@"Avenir-Medium" size:17];

        CGRect frame = self.frame;
        frame.size.height = 47.5;
        self.frame = frame;
    }
    return self;
}

With quite a few different button styles going on, ie.

With most of the differences coming from positioning, dimensions, text colour, background colour and shadow colour. Now am I trying to fit too much into one subclass, what would be people's approach to a sane amount of code in the viewDidLoad methods in their View Controllers, in relation to styling the UI?


texts:
I'm fairly new to Python - though not new to programming by any means. I have this Python script and it works perfect for my needs but being new(er) to Python I'm just looking to see if there are any general things I could be doing better or 'more Python-esque'. I recently refactored all of this into what you see now - it used to be one long script. It's now separated out into logical methods. But I know all too well that code can ALWAYS be cleaner. So, any tips or things that could be improved?

Side note: I changed the file paths/Twitter authentication tokens/etc for security purposes but the rest of the code is untouched.

import tweepy
import pytz
import os

idfile = '/pathtofile/tweet_lastID.txt'

def get_tweets():
    '''
    Sets up and returns the twitter api.
    '''
    consumerKey = 'consumerKey'
    consumerKeySecret = 'consumerKeySecret'
    accessToken = 'accessToken'
    accessTokenSecret = 'accessTokenSecret'
    auth = tweepy.OAuthHandler(consumerKey, consumerKeySecret)
    auth.set_access_token(accessToken, accessTokenSecret)
    return tweepy.API(auth).user_timeline('mytwitterhandle', since_id=get_last_id_from_file())

def get_last_id_from_file():
    '''
    Gets the id of the last downloaded tweet from the id file.
    '''
    with open(idfile, 'r') as f:
        return f.readline().rstrip()

def update_last_id(tweets):
    '''
    Updates the id file with the latest id.
    '''
    if not tweets:
        return

    for tweet in reversed(tweets):
        latestID = tweet.id_str

    with open(idfile, 'w') as f:
        f.write(latestID + '\n')

def write_tweets_to_file(tweets):
    '''
    Writes the given tweets to the backup file.
    '''
    if not tweets:
        return

    doc_path = '/pathtofile/tweets_backup.txt'
    with open(doc_path, 'a') as f:
        for tweet in reversed(tweets):
            f.write('\n'.join(tweet).encode('utf8'))

def format_date(date):
    '''
    Formats a given date to the format '%-d %b %Y at %-I:%M%p'.
    '''
    datefmt = '%-d %b %Y at %-I:%M%p'
    homeTZ = pytz.timezone('US/Central')
    utc = pytz.utc

    ts = utc.localize(date).astimezone(homeTZ)
    timeString = ts.strftime(datefmt)
    timeOfDay = timeString[len(timeString)-2:]
    timeString = timeString[:-2]
    return timeString + timeOfDay[:-1].lower()

def make_tweet(tweet):
    '''
    Returns a formatted tweet to be written to the backup file from the given tweet data.
    '''
    return [format_date(tweet.created_at), tweet.text, '----------\n']

if __name__ == '__main__':
    tweets = get_tweets()
    new_tweets = []

    for tweet in tweets:
        new_tweets.extend([make_tweet(tweet)])

    write_tweets_to_file(new_tweets)
    update_last_id(tweets)


texts:
This question was asked through the Facebook interview and the suggested solution is solving via binary search.

I have put the binary search solution but it still looks too complicated.

Question:

  Given an int array wood representing the length of n pieces of wood and an int k. It is required to cut these pieces of wood such that more or equal to
  k pieces of the same length len are cut. What is the longest len you can get?

Input: wood = [5, 9, 7], k = 3
    Output: 5
    Explanation:
    5 -> 5
    9 -> 5 + 4
    7 -> 5 + 2

Input: wood = [5, 9, 7], k = 4
Output: 4
Explanation:
5 -> 4 + 1
9 -> 4 * 2 + 1
7 -> 4 + 3

package AmazonOthers.src;

import java.util.Arrays;

public class CutWood {

    public static void main(String[] args) {
        int[] array1 = {5,9,7};
        int k = 3;
        System.out.println( woodCut(array1,k) ) ;

        int[] array2 = {124,232,456};
        Arrays.sort(array2);
        int k2 = 7;
        System.out.println( woodCut(array2,k2) ) ;

        int[] array3 = {3,6,7,11};
        Arrays.sort(array3);
        int k3 = 8;
        System.out.println( woodCut(array3,k3) ) ;

    }

    private static int woodCut(int[] array1,int k) {

        int l = 0;
        int h = Integer.MAX_VALUE;

        while(l<h){
            int mid = l + (h-l)/2;
            if(isValid(array1, mid, k)){
                l = mid +1;
            }else{
                h=mid-1;
            }
        }
        return h;

    }

    private static boolean isValid(int[] array1, int mid, int k) {

        int count = 0;
        for(int val: array1){
            count+=val/mid;
        }
        return count>=k;
    }

}


texts:
I'm just beginning with Python and programming, so been trying to get as much experience reading code as possible.

The script mentioned below do grab images from URLs and put them in into a folder. The code is tested and works fine. Is there a way to shorten/improve this code? Any ideas/suggestions are appreciated.

import urllib2
from os.path import basename
from urlparse import urlsplit
from bs4 import BeautifulSoup # for HTML parsing

global urlList
urlList = []

# recursively download images starting from the root URL
def downloadImages(url, level): # the root URL is level 0
    print url
    global urlList
    if url in urlList: # prevent using the same URL again
        return
    urlList.append(url)
    try:
        urlContent = urllib2.urlopen(url).read()
    except:
        return

    soup = BeautifulSoup(''.join(urlContent))
    # find and download all images
    imgTags = soup.findAll('img')
    for imgTag in imgTags:
        imgUrl = imgTag['src']
        try:
            imgData = urllib2.urlopen(imgUrl).read()
            fileName = basename(urlsplit(imgUrl)[2])
            output = open(fileName,'wb')
            output.write(imgData)
            output.close()
        except:
            pass

    # if there are links on the webpage then recursively repeat
    if level > 0:
        linkTags = soup.findAll('a')
        if len(linkTags) > 0:
            for linkTag in linkTags:
                try:
                    linkUrl = linkTag['href']
                    downloadImages(linkUrl, level - 1)
                except:
                    pass

# main
downloadImages('http://www.yahoo.com', 1)

Python version 2.6.


texts: See if a specific resource exists in a Kubernetes namespace

texts:
I want to have a function that checks to see if a certain resource (deployment, job, cronjob etc) exist in a namespace. Using the Kubernetes Python client, I can create a boolean function (using deployments as a concrete example).

from kubernetes import client, config

def deployment_exists(name, namespace="default"):
    config.load_kube_config()
    client = client.AppsV1Api()
    try:
        client.read_namespaced_deployment(name, namespace)
        return True
    except ApiException as e:
        if e.status == 404:
            return False
    return False

Is there a way to achieve the same without relying on the ApiException explicitly?


texts: Using an extra mock simply to take advantage of the behaviour observation tooling

texts:
I'm writing integration for a project, but our framework doesn't provide any ability to inject dependencies, so I've written tests with a unit testing framework (GTest) and used a mock (GMock) in an odd way simply to leverage its behaviour obverving functions.  I have a python script to run it, it all works, but, is there a better approach I should be taking?

/** Class that exists simply to provide stubs for callbacks */
class Monitor
{
 public:
  virtual auto subscribe() -> void {}
};

/** Mocking the ClientMonitor in order to leverage the Mocking tools, i.e.
 * EXPECT_CALL.Times, etc. */
class MockMonitor
{
 public:
  MOCK_METHOD1(subscribe, void());
};

TEST_F(Test, RECEIVE_PROXY_STATUS_EVENT_AVAILABLE)
{
  using ::testing::_;
  MockMonitor cm;

  // Listen for when the service event changes.
  auto const subscription_status = proxy_->getPayloadEvent().subscribe(
    [&cm](int64_t id, std::string const& payload) {
      cm.subscribe();
    });

  EXPECT_CALL(cm, subscribe());

  std::cout << "Waiting " << response_window_.count() << " ms for event..." << std::endl;
  std::this_thread::sleep_for(response_window_);
  std::cout << "Done waiting\n";
  return;
}

This is an integration test so I actually want the communication to work, and there's no way I can see when I go through the code to actually mock it "normally", i.e.

if I derive proxy_ and override getProxyStatusEvent(), I could  return a mock (in this case it would be something complex like CommonAPI::FNV::FNVEvent<PayloadEvent, CommonAPI::Deployable< int32_t, CommonAPI::FNV::IntegerDeployment >, CommonAPI::Deployable< std::string, CommonAPI::FNV::StringDeployment >>, but then that class has its own private signal handler, etc..

So, basically, because the lack of injection, I'd have to create some complex mocks based on internal code that could change at any time.. not a good solution even if possible.

Thus, the solution I wrote above seems to acheive my goals quite simply

It only tests public api methods
It's small
It's flexible

It does seem odd however to create a mock of a dummy class simply to get functions like EXPECT_CALL.  Is there a better approach I could be taking?

Also, for context, I'm using GTest again simply for the tools it provides, i.e. test fixtures, command line parsing of test naems, the asserts, etc.  This could easily work without GTest.


texts:
I built this simple slider with JS, but I am not so experienced with programming and I wonder what can be improved in this code, how to dry it, or how to apply some OOP paradigms to it, what is not good in it, what is bad practice... If you are going to build this simple slider how would you approach it?

JSFIDDLE

HTML

    <button id="prev">Prev</button>

    <button id="next">Next</button>

CSS

* {
    margin: 0;
    padding: 0;
    border: 0;
    list-style-type: none;
    transition: all .5s;
}
body {
    font: bold 100%/1.5 monospace;
}
.container {
    width: 300px;
    height: 200px;
    margin: auto;
    position: relative;
}
.slider-wrapper {
    overflow: hidden;
}
.slider-wrapper ul {
    width: calc(8 * 300px);
    overflow: hidden;
}
.slider-wrapper li {
    float: left;
}
img {
    display: block;
}
button {
    font: bold 80%/1.5 monospace;
    cursor: pointer;
    padding: 1em;
    background-color: purple;
    color: whitesmoke;
    border-radius: 50%;
    position: absolute;
    top: 35%;
    z-index: 5;
}
#prev {
    left: -50px;
}
#next {
    right: -50px;
}

JS

    //window.addEventListener('load',function(){
var imgs = document.getElementsByTagName('img');
var numOfImgs = imgs.length; // 4
var widthOfImg = 300; //imgs[0].getBoundingClientRect().width; // 300
var prevBtn = document.getElementById('prev');
var nextBtn = document.getElementById('next');
var currentImg = 0;
var sliderWrapper = document.querySelector('.slider-wrapper>ul');
var translatedPixels = 0;

prevBtn.addEventListener('click', function () {
    if (currentImg === 0) {
        return;
    }
    currentImg--;
    sliderWrapper.style.transform = 'translateX(' + (-translatedPixels + widthOfImg) + 'px)';
    translatedPixels -= 300;
});
nextBtn.addEventListener('click', function () {
    if (currentImg === numOfImgs - 1) {
        return;
    }
    currentImg++;
    sliderWrapper.style.transform = 'translateX(' + -widthOfImg * currentImg + 'px)';
    translatedPixels += 300;
});
//});


texts:
I forked the original implementation of VerbalExpressions in Scala here: https://github.com/pathikrit/ScalaVerbalExpressions

I am looking forward to these things in the code review:

package com.github.verbalexpressions

import java.util.regex.Pattern
import com.github.verbalexpressions.VerbalExpression._

case class VerbalExpression(prefix: String = "", expression: String = "", suffix: String = "", modifiers: Int = 0) {

  def add(value: String) = copy(expression = expression + value)

  def andThen(value: StringOrVerbalExp) = add(s"($value)")
  def `then` = andThen _
  def find = andThen _

  def maybe(value: StringOrVerbalExp) = add(s"($value)?")

  def zeroOrMore(value: StringOrVerbalExp) = add(s"($value)*")

  def oneOrMore(value: StringOrVerbalExp) = add(s"($value)+")
  def multiple = oneOrMore _
  def many = oneOrMore _

  def anything = add("(.*)")
  def anythingBut(value: StringOrVerbalExp) = add(s"([^$value]*)")

  def something = add("(.+)")
  def somethingBut(value: StringOrVerbalExp) = add(s"([^$value]+)")

  def whitespaces(enable: Boolean = true) = add(if (enable) "\\s+" else "\\S+")
  def words(enable: Boolean = true) = add(if (enable) "\\w+" else "\\W+")
  def digits(enable: Boolean = true) = add(if (enable) "\\d+" else "\\D+")

  def anyOf(value: StringOrVerbalExp) = add(s"[$value]")
  def any = anyOf _

  def lineBreak = add("(\\n|(\\r\\n))")
  def startOfLine(enable: Boolean = true) = copy(prefix = if (enable) "^" else "")
  def endOfLine(enable: Boolean = true) = copy(suffix = if (enable) "$" else "")

  def or(value: StringOrVerbalExp) = copy("(" + prefix, expression + ")|(" + value, ")" + suffix)

  def range(args: (Any, Any)*) = add(s"[${(args map {case (a, b) => s"$a-$b"}).mkString}]")

  def addModifier(modifier: Modifier) = copy(modifiers = modifiers | modifier.mask)
  def removeModifier(modifier: Modifier) = copy(modifiers = modifiers ^ modifier.mask)

  def modify(modifier: Modifier, add: Boolean) = if (add) addModifier(modifier) else removeModifier(modifier)

  def withAnyCase(enable: Boolean = true) = modify(CaseInsensitive, enable)
  def searchOneLine(enable: Boolean = true) = modify(MultiLine, enable)

  def repeat(n: Int) = add(s"{$n}")
  def repeat(atleast: Int, atmost: Int) = add(s"{$atleast,$atmost}")
  def repeatAtleast(n: Int) = add(s"{$n,}")

  def beginCapture = add("(")
  def endCapture = add(")")

  def reluctant = add("?")
  def possessive = add("+")

  def replace(source: String, value: String) = source.replaceAll(toString, value)

  lazy val compile = Pattern.compile(prefix + expression + suffix, modifiers)
  def regexp = compile.pattern()

  def test = Pattern.matches(toString, _: String)
  def check = test
  def notMatch(test: String) = !check(test)

  override def toString = regexp
}

object VerbalExpression {
  sealed trait StringOrVerbalExp
  implicit def lift(s: String): StringOrVerbalExp = new StringOrVerbalExp {override def toString = Pattern.quote(s)}
  implicit def lift(v: VerbalExpression): StringOrVerbalExp = new StringOrVerbalExp {override def toString = v.regexp}

  sealed abstract class Modifier(val mask: Int)
  object UnixLines extends Modifier(Pattern.UNIX_LINES)
  object CaseInsensitive extends Modifier(Pattern.CASE_INSENSITIVE)
  object Comments extends Modifier(Pattern.COMMENTS)
  object MultiLine extends Modifier(Pattern.MULTILINE)
  object Dotall extends Modifier(Pattern.DOTALL)
  object UnixCase extends Modifier(Pattern.UNICODE_CASE)
  //object UnicodeCharacterClass extends(Pattern.UNICODE_CHARACTER_CLASS)

  implicit class StringMatchUtils(s: String) {
    def is(expr: VerbalExpression) = expr check s
    def matches = is _
    def isNot(expr: VerbalExpression) = expr notMatch s
  }

  val $ = VerbalExpression()
}

Main file to review
New APIs I can add that are supported by other libraries
New helpful APIs I can add that can exploit the powerful Java Pattern library
General Scala guidelines and suggestions
Any bugs or things I missed in general...


texts: Best way to get nearest non-zero value from list

texts:
I have a list of values and I need to, given any arbitrary starting index, find the closest value which is non zero, if the value at the starting index is zero...

Here is what I have:

def getNearestNonZero(start_index):
    mylist = [4,2,6,7,3,0,0,9,4,2,5,8,1,7]
    val = mylist[start_index]
    if val == 0:
        loop_length = 0
        after = mylist[start_index+1:]
        before = mylist[:start_index]
        before =  before[::-1]
        print(before, after)

        if len(before) >= len(after):
            loop_length = len(before)
        else:
            loop_length = len(after)

        for i in range(loop_length):
            if i < len(before):
                before_val = before[i]
            if i < len(after):
                after_val = after[i]

            if before_val > 0:
                return before_val

            if after_val > 0:
                return after_val

    return val

result = getNearestNonZero(6)
print(result)

result = getNearestNonZero(5)
print(result)

  [0, 3, 7, 6, 2, 4] [9, 4, 2, 5, 8, 1, 7]

  9

  [3, 7, 6, 2, 4] [0, 9, 4, 2, 5, 8, 1, 7]

  3

What I do, is I first check to see if the value at the start_index is > 0. If it is, great, return it. If however, the value is zero, we need to find the closest non-zero, with a preference for before, rather than after...

To do this, I split mylist into two separate lists, before and after. If my start index is 6, before will now look like: [4,2,6,7,3,0] and after will look like: [9,4,2,5,8,1,7].

Since I need the closest value to the start_index, I reverse my before list: before = before[::-1]

I then get the length of the longest of the two (before and after).

I then loop and check the value at each index of the two lists. The first one to have a value > 0 is returned and my work is done.

However, this feels very clunky and as if it can be done in a cleaner way.

Does anyone have any recommendations? What is the faster/cleaner/pythonic way for finding the nearest non-zero value in a list, given a starting index?


texts: Script that retrieves trending topics from Twitter

texts:
The following code fetches trending topics from Twitter's API using a WOEID. It caches the response, loading from this cache the next time if its relatively fresh (generated within the last 15 minutes) to avoid returning a "Rate limit exceeded" message from Twitter.

A 'force-refresh' flag can be passed to skip the cache.

Please could someone have a look at the code and suggest ways it can be improved?

<?php
use Abraham\TwitterOAuth\TwitterOAuth;
$cache_file = '/home/domstapleton/public_html/home/profiles/default/cache/twitter-trends-' . $_GET['location-code'] . '.data';
if (file_exists($cache_file) && !$_GET['force-refresh']) {
    $data = unserialize(file_get_contents($cache_file));
    if (($data['timestamp'] > time() - 15 * 60)) {
        $trends = $data['trends'];
        echo $trends;
        exit;
    }
}
if (!$trends) {
    require '/home/domstapleton/lib/twitteroauth-master/autoload.php';
    $consumer_key = 'REDACTED';
    $consumer_secret = 'REDACTED';
    $access_token = 'REDACTED';
    $access_token_secret = 'REDACTED';
    $connection = new TwitterOAuth($consumer_key, $consumer_secret, $access_token, $access_token_secret);
    $trends = $connection->get('trends/place', array('id' => $_GET['location-code']));
    if (strpos($trends, 'Rate limit exceeded') !== false) {
        if (file_exists($cache_file)) {
            $data = unserialize(file_get_contents($cache_file));
            $trends = $data['trends'];
            echo $trends;
        }
    } else {
        $data = array('trends' => json_encode($trends), 'timestamp' => time());
        file_put_contents($cache_file, serialize($data));
        echo json_encode($trends);
    }
}


texts: excel vba udf: entire column as fn parameter

texts:
I have a function that accepts a range as an input. It works fine when I supply the function with a range like a1:a5, but not when I use an entire column like a:a.

I could always loop over the whole column (ie. a:a) but that is so slow.

Here is a simple example.

Function r_sum(r1 As Range) As Long

    For Each c In r1.Cells
        r_sum = r_sum + c.Value
    Next c

End Function

How can I supply my functions with ranges (ie. a:a or 2:2, entire columns or rows) and have the function execute efficiently? How do excel's worksheet functions do it so well?

The method I used above (ie. looping over every cell in the range) is so slow that I can't possibly imagine using such a technique, especially since many of the functions I have currently are complex and will crash the program.


texts:
When I was working in Rust this week, I missed kotlin's fun <T> Sequence<T>.single(): T. Basically, calling this function means that you are asserting that the sequence contains only one element and that you want that one element back. The most common use case is you've filtered a sequence down to one element. It's also clearer than using first() for the same task as it is clear that there is only supposed to be one thing and that if there is more than one you need to crash because your assumptions don't hold anymore.

I wanted it in Rust, so I implemented it and put it on crates.io. Before I go 1.0.0, however, I'd like to ask for review, mostly focusing on usability of the crate (thus design) and style of the code.

//! This crate exposes a `Single` trait for extracting the element from a
//! single-element iterator (or `panic!`ing if that precondition is false).

use std::{fmt, error, result};

type Result<T> = result::Result<T, self::Error>;

/// Trait to extract the element from a single-element iterator.
pub trait Single {
    /// The item type of the wrapped iterator.
    type Item;

    /// Get the single element from a single-element iterator.
    ///
    /// Note that many iterators return references to the elements,
    /// so this method will as well if the backing iterator does.
    ///
    /// # Examples
    ///
    /// ```
    /// # use single::{ self, Single };
    /// # use std::iter;
    /// assert_eq!(iter::empty::<i32>().single(), Err(single::Error::NoElements));
    /// assert_eq!(iter::once(0).single(), Ok(0));
    /// assert_eq!(iter::repeat(0).single(), Err(single::Error::MultipleElements));
    /// ```
    fn single(self) -> Result<Self::Item>;
}

/// An error in the execution of [`single::Single::single`](trait.Single.html#tymethod.single).
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Error {
    /// Asked empty iterator for single element.
    NoElements,
    /// Asked iterator with multiple elements for single element.
    MultipleElements,
}

impl fmt::Debug for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(self, f)
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Error::NoElements => write!(
                f,
                "SingleError::NoElements: {}",
                error::Error::description(self),
            ),
            Error::MultipleElements => write!(
                f,
                "SingleError::MultipleElements: {}",
                error::Error::description(self),
            ),
        }
    }
}

impl error::Error for Error {
    fn description(&self) -> &str {
        match *self {
            Error::NoElements => "Asked empty iterator for single element",
            Error::MultipleElements => "Asked iterator with multiple elements for single element",
        }
    }
    fn cause(&self) -> Option<&error::Error> { None }
}

impl<I> Single for I where I: Iterator {
    type Item = <Self as Iterator>::Item;

    fn single(mut self) -> Result<Self::Item> {
        match self.next() {
            None => Err(Error::NoElements),
            Some(element) => if self.next().is_none() {
                Ok(element)
            } else {
                Err(Error::MultipleElements)
            }
        }
    }
}

#[cfg(test)]
mod test {
    use std::iter;
    use super::Single;

    #[test]
    #[should_panic(expected = "Asked empty iterator for single element")]
    fn panic_empty() { let _: i32 = iter::empty().single().unwrap(); }

    #[test]
    #[should_panic(expected = "Asked iterator with multiple elements for single element")]
    fn panic_multiple() { let _ = iter::repeat(0).single().unwrap(); }
}

Future growth by optimization(?) with std::iter::ExactSizeIterator and/or std::iter::TrustedLen may be possible in the future, but would require benchmarking to see if it is worthwhile.


texts:
I've implemented just as Ryan Bates suggested in his railscast episode, I've got everything working just right, so here is his approach in the controller :

def new
    session[:order_params] ||= {}
    @order = Order.new(session[:order_params])
    @order.current_step = session[:order_step]
  end

  def create
    session[:order_params].deep_merge!(params[:order]) if params[:order]
    @order = Order.new(session[:order_params])
    @order.current_step = session[:order_step]
    if @order.valid?
      if params[:back_button]
        @order.previous_step
      elsif @order.last_step?
        @order.save if @order.all_valid?
      else
        @order.next_step
      end
      session[:order_step] = @order.current_step
    end
    if @order.new_record?
      render "new"
    else
      session[:order_step] = session[:order_params] = nil
      flash[:notice] = "Order saved!"
      redirect_to @order
    end
  end

I'm ok with new method, but I wonder how can the create method be refactored. He said that he will do an episode how to refactor this in the future but he did not yet.

This was my take on he reactoring (more splitting than refactoring):

  def create
    session[:order_params].deep_merge!(params[:order]) if params[:order]
    @order = Order.new(session[:order_params])
    @order.current_step = session[:order_step]

    process_step

    if @order.new_record?
      render "new"
    else
      session[:order_step] = session[:order_params] = nil
      flash[:notice] = "Order saved!"
      redirect_to @order
    end
  end

def process_step
  if @order.valid?
    if params[:back_button]
      @order.previous_step
    elsif @order.last_step?
      @order.save if @order.all_valid?
    else
      @order.next_step
    end
    session[:order_step] = @order.current_step
  end
end


texts: Select random IDs from a table, using MySQLi

texts:
I've created a "simple" function that receives a MySQLi resource and, using a custom where query, will fetch random IDs from a provided table.

Some caveats on this:

No object-style! This needs to be understood by people who only know the old mysql_* procedural API;
No order by rand()! It is slow, but very tempting;
It has to allow me to fetch a fixed number of IDs, or all available IDs;
It must always return something, even if it is a simple array;
It is required to allow for a table name to be passed;
A custom where is required, since I need to provide complex queries;
It doesn't really matter if it is a truly random function: pseudo-random is perfectly fine;
No prepared statements: this function will be used alongside some prepared statements. Those will give errors like "Commands out of sync; you can't run this command now";
The code needs to run on PHP 5.3.29.

And here's the code:

<?PHP
    function get_random_ids_from_table(&$link, $table, $where = null, $length = -1)
    {
        $ids_r = mysqli_query($link, 'select id from `' . $table . '`' . ($where ? ' where ' . $where : ''));
        if(!$ids_r)
        {
            return array();
        }

        $count = mysqli_num_rows($ids_r);

        if(!$count)
        {
            return array();
        }

        $ids = array();
        if($length < 1 || $length > $count)
        {
            while($id = mysqli_fetch_assoc($ids_r))
            {
                $ids[] = $id['id'];
            }
            mysqli_free_result($ids_r);
            shuffle($ids);
        }
        else
        {
            while(count($ids) < $length)
            {
                $offset = mt_rand(0, $count - 1);
                if(!isset($ids[$offset]))
                {
                    mysqli_data_seek($ids_r, $offset);
                    $id = mysqli_fetch_assoc($ids_r);
                    $ids[$offset] = $id['id'];
                }
            }
            $ids = array_values($ids);
        }

        mysqli_free_result($ids_r);

        return $ids;
    }

This function works perfectly fine as-is, but it has a problem: it's still slow! It takes 500-1400ms when executed 4 times! I've already reduced its execution time from 3s. (Old version, for reference: http://pastebin.com/ASfBfWmg). And this is to select IDs from 500 rows. I'm expecting that the code runs on 2000+ rows.

How can I improve its horrendous speed? And which other changes you think that are necessary to make it more readable?


texts:
This is my current coursework for university where I am to write a spell checking application and compile using C++11.

I have a dictionary file that is read into the program automatically and stored into a binary search tree in order. The user provides a text file that they would like to check which is split into tokens and stored in a string vector.

The program then loops through the string vector and checks if that word exists in the BST. If the word is not in the BST, it will print the word to the console as incorrectly spelled.

#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
#include <cstring>
#include "bst.h"

using namespace std;

string read_file(string &filename)
{
    ifstream file(filename);
    // If there is a file
    if (file)
    {
        string data;
        // Find total number of bytes of file
        file.seekg(0, file.end);
        data.resize(file.tellg());
        file.seekg(0, file.beg);
        // Read text into data string
        file.read(&data[0], data.size());
        // Close the file
        file.close();
        // Return the string
        return data;
    }
    else return string("");
}

void split_words(vector<string> &words, string &data)
{
    char *token, *delim = " .,?!:;/\"\'\n\t";
    // Set token to first word
    token = strtok(&data[0], delim);
    // Split rest of words
    while (token != nullptr)
    {
        // Convert each word from dictionary to lower case
        for (int i = 0; i < strlen(token); ++i)
        {
            char word = tolower(token[i]);
            token[i] = word;
        }
        // Push word to end of vector
        words.push_back(token);
        // Get the next word
        token = strtok(nullptr, delim);
    }
    // Free the memory
    token = nullptr;
    delim = nullptr;
    delete token;
    delete delim;
}

int main(int argc, char **argv)
{
    string file_to_check, file_data, word_dictionary = "dictionary.txt";
    int spell_count = 0;

    BinarySearchTree *tree = new BinarySearchTree();
    vector<string> words;

    // Loop through arguments
    for (int i = 0; i < argc; ++i)
    {
        // Set file name if provided as argument
        if (string(argv[i]) == "-i" && argv[i+1] != nullptr)
            file_to_check = argv[i+1];
    }

    // If there was no file name as argument, prompt user
    if (file_to_check.empty())
    {
        cout << "File name: ";
        getline(cin, file_to_check);
        cout << endl;
    }

    // If file name is not empty, run spell checking methods
    if (!file_to_check.empty())
    {
        // Read words from dictionary.txt into file_data string
        file_data = read_file(word_dictionary);
        // Split the words and store into vector
        split_words(words, file_data);
        // Insert words into Binary Search Tree
        for (int i = 0; i < words.size(); ++i)
            stringstream(words[i]) >> *tree;

        // Store the data read from specified file
        file_data = read_file(file_to_check);
        // Split sentences and store each word in words vector
        split_words(words, file_data);
        cout << endl;

        // Loop through words vector and check if it exists in dictionary
        for (int i = 0; i < words.size(); ++i)
        {
            // Print out non-occurring words
            if (!tree->exists(words[i]))
            {
                spell_count++;
                cout << words[i] << endl;
            }
        }
        cout << endl;

        // Print the total number of spelling mistakes
        cout << spell_count << " spelling mistakes" << endl;
    }
    else
    {
        // If still no file specified, print message and exit
        cout << "No file specified!" << endl;
        return 0;
    }

    // Free the memory
    delete tree;

    return 0;
}


texts:
The code works fine, but could likely be better. How can I improve it?

From Wikipedia:

A skip list is a data structure that allows fast search within an ordered sequence of elements. Fast search is made possible by maintaining a linked hierarchy of subsequences, with each successive subsequence skipping over fewer elements than the previous one. Searching starts in the sparsest subsequence until two consecutive elements have been found, one smaller and one larger than or equal to the element searched for. Via the linked hierarchy, these two elements link to elements of the next sparsest subsequence, where searching is continued until finally we are searching in the full sequence

public class SkipList<T extends Comparable<T>>{

int maxLevels;
Random rand = new Random();
Node first;
int size;

public SkipList(int listLevels){
    this.maxLevels = listLevels;

    first = new Node(null);
    Node d = new Node(null);
    first.down = d;

    for(int j = listLevels - 2; j >= 0; j--){

        d.down = new Node(null);
        d = d.down;
    }
}

/*
 *Makes a new Node containing data and links the node to the node
 *previous and after on all levels from the nodes height and below.
 */

public void insert(T data){

    int levels = setHeight();
    Node newNode = new Node(data);
    Node node = first;

    for(int i = maxLevels; i > levels; i--){
        node = node.down;
    }

    for(int i = levels; i >= 1; i--){

        Node previous = findPreviousNodeOnLevel(data, node);
        newNode.next = previous.next;
        previous.next = newNode;

        if(i > 1){
            newNode.down = new Node(data);
            newNode = newNode.down;
            node = previous.down;
            }
    }
    size++;
}

/*
 * Gives a random number between 1 and maxLevels
 */
private int setHeight(){
    int n = 0;
    int level = 0;
    while( n != 1 && level < maxLevels){
        n = rand.nextInt(2) + 1;
        level ++;
    }
    return level;
}

/*
 * Finds @param data in the list
 */
public T get(T data){
    Node node = getPreviousNode(data);
    if(node == null || node.next == null || node.next.data == null){
        return null;
    }
    return getPreviousNode(data).next.data;
}

/*
 * Removes @param data from the list
 */

public boolean remove(T data){
    Node previous = getPreviousNode(data);
    if(previous.next != null){
        Node toRemove = previous.next;
        previous.next = toRemove.next;

        while(toRemove.down != null){
            toRemove = toRemove.down;
            previous = findPreviousNodeOnLevel(data, previous.down);
            previous.next = toRemove.next;
        }

        return true;
    }

    return false;
}

/*
 * Returns the node that is before @param data in the list.
 */
private Node getPreviousNode(T data){
    Node previous = findPreviousNodeOnLevel(data, first);

    while(true){
        if(previous.next != null && previous.next.data.equals(data)){
            return previous;
        }

        if(previous.down != null){
        previous = previous.down;
        previous = findPreviousNodeOnLevel(data, previous);
        }
        else{
            return null;
        }
    }
}

/*
 * Returns the node before @param data at the same height/level as @param current
 */
private Node findPreviousNodeOnLevel(T data, Node current){

    while(current.next != null && current.next.data.compareTo(data) < 0){
        current = current.next;
    }
    return current;
}

public int getSize(){
    return size;
}

private class Node {

    T data;
    Node next;
    Node down;

    Node(T data){
        this.data = data;
    }
}

}


texts: Convert two collections of different objects into a single collection

texts:
I am combining two lists of separate objects into a single combined list. The below code works perfectly but it is not the most elegant or efficient solution. Is there a better solution?

var articles = context.Articles.Where(a => a.Author.ID == authorID).ToList();
var reviews = context.Reviews.Where(a => a.Author.ID == authorID).ToList();

var items = articles.ConvertAll(x => new ItemViewModel(x.ID, x.Title, x.Summary, "article", x.PublishDate)).Union(reviews.ConvertAll(r => new ItemViewModel(r.ID, r.Title, r.Summary, "review", r.PublishDate))).Take(20).OrderByDescending(i => i.publishDate);


texts:
I'm looking for 3 different answers:

Using Java predefined functions
Converting from string to number
Without the above two (any other types of answers are also welcome)

I am looking for improving my code (as per the above 3 conditions for 3 answers) taken from my repository here.

/*
 * Checks if the year passed is a leap year
 *
 * @param year; requires the year to have 4 digits
 * @return true if leap, else false
 *
 */

public static boolean isLeapYear(int year) {
    String testYear = String.valueOf(year);
    if (testYear.charAt(2) == '1' || testYear.charAt(2) == '3' ||
            testYear.charAt(2) == 5 || testYear.charAt(2) == '7' ||
            testYear.charAt(2) == '9') {
        //If the third digit is odd

        if (testYear.charAt(3)=='2'||testYear.charAt(3)=='6'){
            return true;
        }
        else{
            return false;
        }
    }
    else{
        if (testYear.charAt(2) == '0' && testYear.charAt(3) == '0') {
            if(testYear.charAt(0) == '1' || testYear.charAt(0) == '3' ||
                    testYear.charAt(0) == 5 || testYear.charAt(0) == '7' ||
                    testYear.charAt(0) == '9'){
                //If first digit is odd

                if(testYear.charAt(1)=='2'||testYear.charAt(1)=='6'){
                    return true;
                }
                else{
                    return false;
                }
            }

            //If second digit is not odd
            else if(testYear.charAt(1)=='0'||testYear.charAt(1)=='4'||
                    testYear.charAt(1)=='8'){
                return true;
            }
            else
                return false;
        }
        else if (testYear.charAt(3)=='0'||testYear.charAt(3)=='4'||
                testYear.charAt(3)=='8'){
            //If fourth digit is not odd
            return true;
        }
        else
            return false;
    }
}