texts:
I've been working on generating primes and prime products quickly to aid me in my research on prime numbers, their density, etc. The answer to my Large Number Limit Extravaganza question proved to be extremely useful in writing my programs. I have now expanded on this program to look at the difference in the amount of primes up to a certain point according to a lower bound, and the amount of "straight inhibitors" up to a certain point. A straight inhibitor is a figment of my imagination that I have used in my math and is extremely important for it.

import math
grandtotal = 1000
def prime_sieve(limit):
    a = [True] * limit
    a[0] = a[1] = False

    for i, isprime in enumerate(a):
        if isprime:
            yield i
            for n in xrange(i * i, limit, i):
                a[n] = False

def getDotArrayLog():
    e=55
    data = []
    while e<grandtotal:
        e+=1
        data.append((2 * e / (math.log(2.0 * e, 10) + 2)) - e / (math.log(e, 10) - 4))
    return data

def getDotArrayProduct():
    e=55
    data = []
    product = 1.0
    while True:
        if e==grandtotal: break
        e+=1
        for p in prime_sieve(e):
            product *= (1.0 - 1.0 / p)
        data.append(product)
        product = 1.0
    return data

if __name__ == "__main__":
    logs = getDotArrayLog()
    producta = getDotArrayProduct()
    print "Tested all the way up to", grandtotal
    counter = 0
    for e in logs:
        a = (1-producta[counter])*(counter+55)
        print "Amount of primes:", e
        print "Amount of inhibitors:", a
        print e-a
        counter+=1

I'm looking for some optimizations, condensations, and probably a great lecture on proper conventions.


texts:
As an educational exercise, I would like to make this code more efficient, with fewer lines, without using other standard functions.

The goal here is to convert a number to X base and display it, (sample for hexadecimal) including 0x0 => 0, or 0x4096 => 4096.

int     print_hex(int number, int base)
{
    int     i;
    int     len;
    char    c;
    char    buffer[base];

    if (!number)
    {
        putchar('0');
        return 1;
    }
    i = 0;
    while (i < base && number > 0)
    {
        c = "0123456789abcdef"[number % base];
        buffer[i] = c;
        number /= base;
        i++;
    }
    buffer[i] = '\0';
    len = i;
    while (i--)
        putchar(buffer[i]);
    return (len);
}


texts: Enable Jquery Containment without using position: relative

texts:
I was trying to constrain ui-modal-dialog closed by the "body" of html using Jquery's constrainment. I thought it was possible to just set .draggable( { containment: 'body' }): However, ui-modal-dialog always escapes and I can overscroll more than containment area such as "body" in this case( I also tried some rectangle [0, 0, 1024, 768] though, ui-modal-dialog can break its boundary). Now, I set the position: relative in the "html" and "body" in the code and it seems work so far.

My question is that I can use draggable({containment: some-container}) for constraining the ui-modal-dialog  without using relative: position.?

My JS fiddle: Containment not working

https://jsfiddle.net/kimihiro/qmgs37re/

My JS fiddle: Containment with position: relative in  "html" and "body" of styling Jquery.

https://jsfiddle.net/kimihiro/jtb3yhs8/

The same "Containment not working" code is below but not working here...

$.widget("ui.dialog", $.extend({}, $.ui.dialog.prototype, {
   _title: function(title) {
     if (!this.options.title) {
       title.html("&#160;");
     } else {
       title.html(this.options.title);
     }
   }
 }));
 $("#dialog").dialog({
   autoOpen: false,
   　　height: 300,
   width: 830,
   dialogClass: 'myTitleClass',
   modal: true,

   title: "Carpe Diem. Nunca Acredito Posteiro",
   closeOnEscape: false,
   open: function(event, ui) {
     $('.ui-dialog-titlebar-close', ui.dialog | ui);
   },

   buttons: {

     "Save": function() {
       $(this).trigger(updateKeyword());
     }
   }
 }).draggable({ containment: 'body' });

 $("#opener").click(function() {
   $("#dialog").dialog("open");
 });
input#opener {
  height: 30px;
  width: 200px;
  left: 50%;
  margin-top: -15px;
  /* = -height / 2   */
  margin-left: -100px;
  /* = -width / 2    */
  position: fixed;
  top: 80%;
  background: rgba(4, 115, 184, 0.9);
  color: #fff;
  font-style: Arial;
  font-size: 16px;
  font-weight: 700;
  line-height: 1.5;
  border-style: outset;
  display: flex;
  transition: .5s ease;
  vertical-align: middle;
  justify-content: center;
}

.myTitleClass .ui-dialog-title {
  white-space: normal;
}

.myTitleClass .ui-dialog-titlebar {
  background: rgba(4, 115, 184, 0.9);
  color: #fff;
  font-size: 16px;
  font-weight: 700;
  height: 60px;
}

.myTitleClass .ui-widget-content .ui-state-default {
  background-image: none;
  background-color: rgba(4, 115, 184, 0.6);
  color: #fff;
  font-size: 16px;
  font-weight: 700;
  border-style: none;
}

.myTitleClass .ui-widget-content .ui-state-hover {
  background-image: none;
  background-color: rgb(4, 127, 184);
  color: #fff;
  font-size: 16px;
  font-weight: 700;
  border-style: none;
}

.ui-widget-overlay {
  position: fixed;
  background: black;
}

.myTitleClass .ui-dialog-titlebar-close {
  background: rgba(4, 115, 184, 0.9);
  border-radius: 17px;
  height: 33px;
  margin: -10px 0 0;
  padding: 1px;
  position: absolute;
  right: -28px;
  top: -24%;
  width: 33px;
}

.myTitleClass.ui-icon-close {
  background: url("http://download.jqueryui.com/themeroller/images/ui-icons_*COLOR*_256x240.png");
}

.ui-dialog {
  overflow: visible;
}

#footer {
  background: #0473b8;
  color: #fff;
  font-size: 12px;
  line-height: 50px;
  text-align: center;
  bottom: 0;
  height: 50px;
  position: fixed;
  width: 100%;
}
html {
  height: 100%;
   overflow-x: hidden;

}

body {
  height: 100%;
  overflow: hidden;

}

}

<link href="https://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<input type="button" id="opener" value="Register Keyword">
</button>

Merry Christmas.

footer


texts: Populating an HTML combo box by looped concatenation

texts:
This code takes the results of a database query and uses them to populate the options in a combobox on a form.

Would it be better to start with an empty htmlCode and then concatenate all the <option> code in the loop before finally using echo outside the loop?

Also, do I need to declare $boxOption, $paramKey and $paramValue as class variables or are they OK as is because they're only used in this method?

public function populateComboBox ($boxToPopulate)
    {
        $this->boxOptions = $this->getQueryResults($this->boxParams[$boxToPopulate]['query']);

        foreach ($this->boxOptions as $boxOption) {

            foreach ($this->htmlParams as $paramKey => $paramValue) {

                if (!empty($this->boxParams[$boxToPopulate][$paramKey])) {

                    $this->htmlParams[$paramKey] = $boxOption[$this->boxParams[$boxToPopulate][$paramKey]];
                }
            }

            $this->htmlCode = "<option value='{$this->htmlParams['value']}' "
                              . "class='{$this->htmlParams['class']}'>"
                              . "{$this->htmlParams['text']}</option>\n";

            echo <<<_CODE
                                {$this->htmlCode}
_CODE;
        }

    }

I use an array for each combobox on the form:

    $this->boxParams['issue'] = array (
        'query' => 'SELECT interface_issue, current_issue '
                 . 'FROM interface_issue '
                 . 'WHERE current_issue = -1 '
                 . 'ORDER BY interface_issue;',
        'value' => 'interface_issue',
        'class' => '',
        'text' => 'interface_issue'
    );


texts: Pivotting SQL Table Response to JSON in JavaScript

texts:
Issue

Our API returns two formats JSON and this SQL table format. I'm not sure what it is truly called so I'll give a few examples below. Like all API responses, it can be a list or a single response but it is always in the same format. I'm creating a utility function for this SQL table format to be converted into a JSON object so the front-end only needs to be concerned with a single format, JSON.

Problem

Convert SQL Table Response to JSON

Examples of the SQL table format

Here is the SQL table format as a success message.

{
  "COLUMNS":["SUCCESS","RETMESSAGE"],
  "DATA":[[true,"Order Approved"]]
}

Here is an example of a list

{
  "COLUMNS":["PRODUCTID","PRODUCTNAME"],
  "DATA":[[1001,"Product1"],[1002,"Product2"],[1003,"Product3"]]
}

Current Solution

The current solution is the following. It works well but I keep coming back to it and thinking there is a more elegant way of writing this.

const request = {
        "COLUMNS":["SUCCESS","RETMESSAGE"],
        "DATA":[[true,"Order Approved"]]
      };

const desiredFormat = [{
        "SUCCESS":true,
        "RETMESSAGE":"Order Approved"
      }];

function tableToJSON (dataset) {
    const data = dataset.DATA;
    const columns = dataset.COLUMNS;
    const jsonData = [];
    data.forEach( (row) => {
      const json = {};
      row.forEach( (item, index) => {
        json[columns[index]] = item;
      });
      jsonData.push(json);
    });
    return jsonData;
  }

const formattedResponse = tableToJSON(request);

console.log(JSON.stringify(formattedResponse) === JSON.stringify(desiredFormat))
// Outputs: True


texts:
Below is my first attempt at programming a Celsius to Fahrenheit converter in C# winforms. I'm looking for tips and advice on improving my style and what I can do to make the code more efficent/proper, or is it good as is? I apologize ahead of time if i've forgotten any details and would be happy to provide more upon request.

namespace TemperatureConverter
{
  public partial class Form1 : Form
  {
    public Form1()
    {
        InitializeComponent();
        // Initalize the handler to allow use of only control/number characters.
        this.txtCelsius.KeyPress += new KeyPressEventHandler(txtCelsius_KeyPress);
        // Limits user's inpute to 5 characters max.
        txtCelsius.MaxLength = 5;
        // Prevents the user from resizing window.
        this.FormBorderStyle = FormBorderStyle.FixedDialog;
    }
    // Main function. Converts the input into Fahrenheit and outputs to the targeted label.
    private void btnConvert_Click(object sender, EventArgs e)
    {
        double C;
        double F;

        C = double.Parse(txtCelsius.Text);
        F = C * 9 / 5 + 32;
        lblFahrenheit.Text = F.ToString();
    }
    // Prevents user from entering anything other than Number and Control characters.
    private void txtCelsius_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (!Char.IsControl(e.KeyChar) && !Char.IsNumber(e.KeyChar))
        {
            e.Handled = true;
        }
    }
  }
}


texts: Removal of a character to make a string a palindrome

texts:
This code determines which index for a given string if that character is removed will produce a palindrome string.

  For eg
    s = "baa"
    After removing b the string "aa" is palindrome.

Here this is what I have written until now. Due to time complexity problems, it exceeds 2ms. How this can be made faster?

#include <iostream>
#include <string>
using namespace std;

bool checkPalindrome(string s){
  bool found = true;
  int len = s.length();
  for(int i=0;i<len;i++){
    if(s[i] != s[len-i-1])
    {
      found = false;
      break;
    }
   }
  return found;
 }  // end of function

   int main() {

     int test;
     cin>>test;   // get the number of test case
     for(int i=0;i<test;i++){
       string s;
       cin>>s;    // get the string as input
       if(checkPalindrome(s)){
         cout<<-1<<endl;   //if already string is palindrome
       }
       else{
         int len = s.length();
         for(int i=0;i<len;i++){
           string aa = s.substr(0,i) + s.substr(i+1,len);
           if(checkPalindrome(aa)){
             cout<<i<<endl;
             break;
           }
       }
     }

   }
   return 0;
  }


texts: Get all points on a uniform discrete grid inside a circle's radius

texts:
I have a 2-dimensional grid defined by a known point gridCenter and distance between points gridStep and need to find all points on this grid that are inside or on the radius of a circle defined by center and radius.

My solution is to use a brute-force approach like so:

public static IEnumerable<Vector2> GetPointsInCircle(Vector2 circleCenter, float radius, Vector2 gridCenter, Vector2 gridStep)
{
    if (radius <= 0)
    {
        throw new ArgumentOutOfRangeException("radius", "Argument must not be negative.");
    }

    if (gridStep.x <= 0 || gridStep.y <= 0)
    {
        throw new ArgumentOutOfRangeException("gridStep", "Argument must not contain negative components.");
    }

    var minimumPoint = GetClosestGridPoint(new Vector2(circleCenter.x - radius, circleCenter.y - radius), gridCenter, gridStep);
    var maximumPoint = GetClosestGridPoint(new Vector2(circleCenter.x + radius, circleCenter.y + radius), gridCenter, gridStep);

    for (var x = minimumPoint.x; x <= maximumPoint.x; x += gridStep.x)
    {
        for (var y = minimumPoint.y; y <= maximumPoint.y; y += gridStep.y)
        {
            var point = new Vector2(x, y);

            if (Vector2.Distance(point, circleCenter) <= radius)
            {
                yield return point;
            }
        }
    }
}

private static Vector2 GetClosestGridPoint(Vector2 point, Vector2 gridCenter, Vector2 gridStep)
{
    var leftGridPoint = gridCenter.x + Mathf.Floor((point.x - gridCenter.x) / gridStep.x) * gridStep.x;
    var rightGridPoint = leftGridPoint + gridStep.y;
    var closestHorizontalGridPoint = (point.x - leftGridPoint) > (rightGridPoint - point.x) ? rightGridPoint : leftGridPoint;

    var bottomGridPoint = gridCenter.y + Mathf.Floor((point.y - gridCenter.y) / gridStep.y) * gridStep.y;
    var topGridPoint = bottomGridPoint + gridStep.y;
    var closestVerticalGridPoint = (point.y - bottomGridPoint) > (topGridPoint - point.y) ? bottomGridPoint : topGridPoint;

    return new Vector2(closestHorizontalGridPoint, closestVerticalGridPoint);
}

And usage (and unit test) are as follows:

[Test]
public void GetPointsInCircleTest()
{
    var results = AdaptiveSpatialGrid2D<int>.GetPointsInCircle(new Vector2(0.1f, 0.1f),
        1,
        new Vector2(0, 0),
        new Vector2(1, 1));

    var expected = new List<Vector2>()
    {
        new Vector2(0,0),
        new Vector2(0,1),
        new Vector2(1,0) //(1,1) is outside of circle radius and invalid
    };

    CollectionAssert.AreEquivalent(expected, results);
}

This method will be executed frequently (probably once a second) inside of a game and needs to be as light-weight as possible. Typically the grid will have few points inside of the circle at any time (in the region of fifty).

Are there any optimizations I can make to improve execution speed?

Additionally, the code currently resides inside my grid's class as a static method, but I wonder if it would be better placed somewhere more generic, as really it applies to any 2D grid, not just my implementation.

General comments on the code are also welcome.


texts:
I made a class that I think satisfies the conditions:

Actions can be added to the queue at any time by any number of clients.
Action's executing in the order in which were added.
Only one Action executing at time.

public sealed class SequentialTaskScheduler
{
    private static volatile SequentialTaskScheduler instance = null;

    private static readonly object padlock = new object();

    private readonly ConcurrentQueue<Action> queue = new ConcurrentQueue<Action>();

    SequentialTaskScheduler()
    {
        var task = Task.Factory.StartNew(ThreadProc);
    }

    public static SequentialTaskScheduler Instance
    {
        get
        {
            if (instance == null)
            {
                lock (padlock)
                {
                    if (instance == null)
                    {
                        instance = new SequentialTaskScheduler();
                    }
                }
            }
            return instance;
        }
    }

    public void AddToQueueForExecution(Action action)
    {
        queue.Enqueue(action);
    }

    private void ThreadProc()
    {
        while (true)
        {
            Action item;
            bool isSuccessfull = false;
            isSuccessfull = queue.TryDequeue(out item);
            if (isSuccessfull)
            {
                item();
            }
            System.Threading.Thread.Sleep(100);
        }
    }
}

I will be grateful for the advice about dangers of such an implementation. And also will be grateful for the advice how to improve it.

Update:

I get feedback on this task from company.

uncertain use of volatile
use threadsafe singleton or singleton
Task.Factory.StartNew take pool from thread but does not return it.
use busy loop with Thread.Sleep is not elegant solution.

How to improve code with those remark's? I think that first two reason are non constructive, but the third and four are constructive. i will be grateful for the advices.


texts:
I have worked on one application related for booking space and required to store activity of user into table and access from admin side.
For that I have created one database entity and EventLogger class.

public partial class UserEventLog
{
    public int ID { get; set; }
    public string UserID { get; set; }
    public Enum_SourceType SourceType { get; set; }
    public Enum_EventType EventType { get; set; }
    public string EventId { get; set; }
    public string EventName { get; set; }
    public Enum_LogType LogType { get; set; }
    public string LogMessage { get; set; }
    public string LogDescription { get; set; }
    public string IPAddress { get; set; }
    public string HostName { get; set; }
    public DateTimeOffset EventTriggeredOn { get; set; }
    public virtual AspNetUser User { get; set; }
}

related enum

public enum Enum_SourceType
{
    User,
    Order
}
public enum Enum_LogType
{
    Information,
    Warning,
    Error
}
public enum Enum_EventType
{
    Create,
    Update,
    Delete,
    Duplicate,
    DownLoad,
    Preview,
    Search,
    AppliedCoupon,
    Cancel,
    LoggedIn,
    Register,
    SendMail,
    ConfirmEmail,
    Account,
    View,
    SendMessage
}

and I have created EventLogger class for log event from whole application.

  public class EventLogger
{

    public static IUserEventLogService UserEventLogService
    {
        get
        {
            return Core.ContainerManager.GetConfiguredContainer().Resolve<IUserEventLogService>();
        }
    }
    public static IUnitOfWorkAsync UnitOfWork
    {
        get
        {
            return Core.ContainerManager.GetConfiguredContainer().Resolve<IUnitOfWorkAsync>();
        }
    }
    public static async Task Log(DateTimeOffset eventTriggeredOn, Enum_EventType eventType, string eventName, Enum_LogType logType, string logMessage,string eventId = "", string logDescription = "")
    {

        var currentUserId = System.Web.HttpContext.Current.User.Identity.GetUserId();
        string ipAddress = GetLocalIPAddress();
        var userEventLog = new UserEventLog()
        {
            EventId = eventId,
            LogType = logType,
            EventName = eventName,
            EventTriggeredOn = eventTriggeredOn,
            EventType = eventType,
            LogMessage = logMessage,
            LogDescription = logDescription,
            IPAddress = ipAddress,
            UserID = currentUserId,
            ObjectState = Repository.Pattern.Infrastructure.ObjectState.Added,
            SourceType = Enum_SourceType.User
        };
        UserEventLogService.Insert(userEventLog);
       await UnitOfWork.SaveChangesAsync();
    }
    public static string GetLocalIPAddress()
    {
        string visitorIPAddress = GetVistorIp(HttpContext.Current.Request.ServerVariables);
        return visitorIPAddress;
    }
    static string GetVistorIp(NameValueCollection headers)
    {
        if (!string.IsNullOrWhiteSpace(headers["HTTP_X_FORWARDED_FOR"]))
            return headers["HTTP_X_FORWARDED_FOR"];
        if (!string.IsNullOrWhiteSpace(headers["HTTP_CF_CONNECTING_IP"]))
            return headers["HTTP_CF_CONNECTING_IP"];
        return headers["REMOTE_ADDR"];
    }
}

Please suggest me if this solution is right or require any modification or any good solution for suggestion for my implementation.


texts:
I created a R package to calculate Pi with a Monte Carlo simulation.

My goal is to optimize the parallel function SnowPi as much as possible. This is the SnowPi.R code:

FSnowPi <- function(DARTS, ROUNDS, proc_num, numprocs) {
  retvals <- .Fortran("snowpi", avepi = as.numeric(1),
                      DARTS =  as.integer(DARTS),
                      ROUNDS =  as.integer(ROUNDS),
                      proc_num = as.integer(proc_num),
                      numprocs = as.integer(numprocs))
  return(retvals$avepi)
}
#'@export
SnowPi  <- function(DARTS, ROUNDS, numprocs){
  cl <- snow::makeCluster(numprocs, type = "MPI")
  r<<-ROUNDS
  d<<-DARTS
  snow::clusterExport(cl, c("r", "d"))
  x<-snow::clusterEvalQ(cl, MyPi::FSnowPi(DARTS = d, ROUNDS = r, proc_num = mpi.comm.rank(), numprocs = mpi.comm.size()-1))
  snow::stopCluster(cl)
  return(mean(unlist(x)))
}

One thing that I think may not be optimal is the use of <<-. Alas, I don't know how to get the code to work without that (I think the problem is how to pass the correct environment to clusterExport)

Finally, these are the 2 relevant Fortran subroutines:

subroutine snowpi(avepi, DARTS, ROUNDS, proc_num, numprocs) bind(C, name="snowpi_")
use, intrinsic                         :: iso_c_binding, only : c_double, c_int
real(c_double), intent(out)            :: avepi
integer(c_int), intent(in)             :: DARTS, ROUNDS, proc_num, numprocs
integer                                :: i, n, mynpts
integer, allocatable                   :: seed(:)
double precision                       :: pi_est

  if (proc_num .eq. 1) then
      mynpts = ROUNDS - (numprocs-1)*(ROUNDS/numprocs)
    else
      mynpts = ROUNDS/numprocs
  endif

  ! initialize the random number generator
  ! we make sure the seed is different for each task
  call random_seed()
  call random_seed(size = n)
  allocate(seed(n))
  seed = 12 + proc_num*11
  call random_seed(put=seed(1:n))
  deallocate(seed)

  avepi=0.0d0
    do i = 0, mynpts-1
      call dboard(darts, pi_est)
      ! calculate the average value of pi over all iterations
      avepi = ((avepi*i) + pi_est)/(i + 1)
  end do

end subroutine snowpi

and

subroutine dboard(darts, dartsscore)
  integer, intent(in)                    :: darts
  double precision, intent(out)          :: dartsscore
  double precision                       :: x_coord, y_coord
  integer                                :: score, n

score = 0
do n = 1, darts
  call random_number(x_coord)
  call random_number(y_coord)

  if ((x_coord**2 + y_coord**2) <= 1.0d0) then
  score = score + 1
  end if
end do

dartsscore = 4.0d0*score/darts

end subroutine dboard

I'm not sure if there is something that I could improve there.


texts:
Problem:

  A non-contiguous substring of string \$s\$ is a sequence of \$k \geq 0\$ characters in \$s\$, in the order in which they occur in \$s\$. For instance, the set of all non-contiguous substring of "abcd" are \$\{a,cd\}, \{ab,d\}, \{a,c\}, \{a,d\}, \{b,d\}\$.

I want to mention this is from an assignment (which I completed and submitted more than a week before asking this) and the reason I'm asking is because I'm curious if there is a better, more elegant method than mine.

This is supposed to be done recursively.

My solution:

Find all possible substring (powerset) of the given string (recursive function). Test each possible substring to see if it is non-contiguous (iterative function).

import java.util.Arrays;

public class HWK3_2_hoodav {

    public static void main(String[] args) {
        /** Parses input and calls powerSet method with input */
        String input = Arrays.toString(args);
        input = input.substring(1, input.length()-1);
        powerSet(input, "", input);
    }

    public static void powerSet(String original, String base, String substring) {
        /** This method recursively finds all possibile combinations of
        substrings and then invokes the nonContiguous method to check
        if a specific combination is non-contiguous */

        if (substring.length() == 1) {
            nonContiguous(original, base + substring);
            nonContiguous(original, base + " ");
        }
        else {
            powerSet(original, base + substring.charAt(0), substring.substring(1));
            powerSet(original, base + " ", substring.substring(1));
        }
    }

    public static void nonContiguous(String original, String candidate) {
        /** This method verifies a given candidate is non-contiguous */
        if (candidate.contains(" ")) {
            for (int i=0; i < original.length(); i++) {
                if (candidate.charAt(i) != ' ') {
                    for (int j=i+1; j < original.length(); j++) {
                        if (candidate.charAt(j) == ' ') {
                            for (int k=j+1; k < original.length(); k++) {
                                if (candidate.charAt(k) != ' ') {
                                    printSet(candidate);
                                    return;
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    public static void printSet(String orgString) {
        /** This method takes in a string containing whitespaces seperating
        non-whitespace charcters and output a string enclosed by braces and
        with whitespaces replaced by commas */
        String[] splitString = orgString.split(" ");
        String string = "{";
        for (int i=0; i < (splitString.length-1); i++) {
            if (!splitString[i].equals("")) {
                string += splitString[i] + ", ";
            }
        }
        string += splitString[splitString.length-1] + "}";
        System.out.println(string);
    }
}

The input is any string, where ALL characters are treated equally.

The output of the input "abcde" is:

{abc, e}
{ab, de}
{ab, d}
{ab, e}
{a, cde}
{a, cd}
{a, c, e}
{a, c}
{a, de}
{a, d}
{a, e}
{bc, e}
{b, de}
{b, d}
{b, e}
{c, e}


texts:
Essentially the Collatz Conjecture.

Challenge requirements are here.

And here is my implementation in Java:

/* User: koray@tugay.biz Date: 21/03/15 Time: 19:40 */

public class ThreeNOneForRangeSolver {

    public int solveFor(int inputOne, int inputTwo) {
        int maximumCycleLength = 0;

        do {
            if (threeNOneValueFor(inputTwo) > maximumCycleLength) {
                maximumCycleLength = threeNOneValueFor(inputTwo);
            }
            inputTwo = inputTwo - 1;
        } while (inputTwo >= inputOne);

        return maximumCycleLength;
    }

    private static int threeNOneValueFor(int inputNumber) {
        int counter = 1;
        while (inputNumber != 1) {
            if (inputNumber % 2 == 0)
                inputNumber = inputNumber / 2;
            else
                inputNumber = 3 * (inputNumber) + 1;
            counter++;
        }
        return counter;
    }
}

and the test class:

/* User: koray@tugay.biz Date: 21/03/15 Time: 20:54 */

public class TestClass {

    public static void main(String[] args) {
        int one = 1;
        int two = 10;

        int result = new ThreeNOneForRangeSolver().solveFor(one, two);

        System.out.println(one + " " + two + " " + result);
    }

}

Any feedback is welcome.


texts: Decorator to add key parameter support to an existing sort function

texts:
Preface

sorted built-in function has key keyword-only parameter. Most of the custom implementations like the following for heapsort algorithm

import heapq
import itertools
from typing import (Iterable,
                    TypeVar)

Domain = TypeVar('Domain')

def heapsort(iterable: Iterable[Domain]) -> Iterable[Domain]:
    heap = []
    for element in iterable:
        heapq.heappush(heap, element)
    for _ in itertools.repeat(None, len(heap)):
        yield heapq.heappop(heap)

has no key parameter support. I thought of a decorator that will add key parameter support in the next fashion

from functools import wraps
from operator import itemgetter
from typing import (Callable,
                    Iterable,
                    Optional,
                    TypeVar)

Domain = TypeVar('Domain')
Sortable = TypeVar('Sortable')

def with_key(plain: Callable[[Iterable[Sortable]], Iterable[Sortable]]
             ) -> Callable[..., Iterable[Domain]]:
    @wraps(plain)
    def implementation(iterable: Iterable[Domain],
                       *,
                       key: Optional[Callable[[Domain], Sortable]] = None
                       ) -> Iterable[Domain]:
        if key is None:
            yield from plain(iterable)
            return
        yield from map(itemgetter(2),
                       plain((key(element), index, element)
                             for index, element in enumerate(iterable)))

    return implementation

and after that used like

>>> heapsort_with_key = with_key(heapsort)
>>> list(heapsort_with_key(range(10), key=lambda x: -x))
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

Problem

I wonder if there is a better way (e.g. in terms of memory efficiency) of adding key parameter? Does anyone know how it is implemented in sorted?


texts: Binary Reflected Gray Code generation recursively

texts:
I tried to write BRGC recursively. I've really recognized that intrinsic of recursion helps for some problems in which I think BRGC is included. is the way I wrote it recursively adequate solution? Can it be improved w.r.t recursion?

Do both methods have same complexity Theta(n), right?
T(n) = T(n-1) + n, T(n) = T(n/2) + n respectively.

import java.util.ArrayList;
import java.util.List;

class Test {
    public static void main(String[] args) {
        System.out.println(genGray(List.of("0", "1"), 3));
        System.out.println(genGrayV2(List.of("0", "1"), (int)Math.pow(2, 3)));
    }

    public static List<String> genGray(List<String> list, int n) {
        if (list.size() == (int)Math.pow(2, n+1))
            return list;

        List<String> combinedList = new ArrayList<>();

        for (String elem : list) {
            combinedList.add("0" + elem);
        }

        for (String elem : list) {
            combinedList.add("1" + elem);
        }

        return genGray(combinedList, n);
    }

    public static List<String> genGrayV2(List<String> list, int n) {
        if (n == 1)
            return list;

        List<String> combinedList = new ArrayList<>();

        for (String elem : list) {
            combinedList.add("0" + elem);
        }

        for (String elem : list) {
            combinedList.add("1" + elem);
        }

        return genGray(combinedList, n / 2);
    }
}


texts:
I am working on 957. Prison Cells After N Days
 but getting timeout error for my code. as I assume my code should be 14+O(n-14) about O(n) am I right since after 14 run pattern will be repeated? and how can I improve my code?
        from collections import defaultdict
        step_map = defaultdict(list)
        for k in range(N):
            if tuple(cells) in step_map:
                cells = step_map[tuple(cells)]
            else:
                tmp = list()
                for i in range(1, 7):
                    tmp += [int(cells[i - 1] == cells[i + 1])]
                tmp = [0] + tmp + [0]
                step_map[tuple(cells)] = tmp
                cells = tmp
        return cells


texts:
As far as I can tell, there is no network access happening at this stage in the code. I am accessing Reddit's API via the PRAW module. However, it is crawling, and I think it should be faster, considering I am hardly doing any work (unless Python heavily penalizes object access?).

This is the entire short script:

import sys, os, pprint, praw

class Scanner(object):
    ''' A scanner object. '''
    def __init__(self):
        self.user_agent = 'debian.blah8899889.agent'
        self.r = praw.Reddit(user_agent=self.user_agent)
        self.nsfw = ('funny', 'nsfw')
        self.nsfw_posters = set()
        self.content = []

    def getSub(self, subreddit):
        ''' Accepts a subreddit. Adds subreddit posts object to self.content'''
        url = 'http://www.reddit.com/r/{sub}/'.format(sub=subreddit)
        print 'Scanning:', subreddit
        subreddit_posts = self.r.get_content(url, limit=5)
        self.addContent(subreddit_posts)

    def addContent(self, subreddit):
        print 'Adding subreddit posts to content.'
        self.content.append(subreddit)

    def addNSFWPoster(self, post):
        print 'Parsing author and adding to posters.'
        self.nsfw_posters.add(str(post.author))

    def scanNSFW(self):
        ''' Scans all NSFW subreddits. Makes list of posters. '''
#       Get content from all nsfw subreddits
        print 'Executing map function.'
        map(self.getSub, self.nsfw)
#       Scan content and get authors
        print 'Executing list comprehension.'
        [self.addNSFWPoster(post) for sub in self.content for post in sub]

def main():
    scan = Scanner()
    scan.scanNSFW()

main()

All of the network access should happen at map(self.getSub, self.nsfw). This actually runs quite fast considering I am rate limited by Reddit's servers.

I cannot work out why the list comprehension is so slow. All it should be doing is iterating through some objects and extracting a simple attribute: it should merely get str(post.author).

 [self.addNSFWPoster(post) for sub in self.content for post in sub]

Can someone help me understand why it seems so slow to execute?

I am new to the OOP approach, and I can only assume I have made a big mistake somewhere.
It is slower than the network access portion of the code!


texts:
For a project I'm working on, I need to calculate the age of users based on their birthday (which is a DateTime object). with a few requirements:

the output must be in french (the entire project is in french)
the output is needed to be all caps
the output must follow these rules:

if the person is a newborn (less than 1 month old) return the age in days only
else if the person is an young child (less than 3 years old) return the age in years and months
else return just the years

So I wrote this CalculateAge method
Here's the code
using System;
using System.Linq;
using System.Runtime.InteropServices;

namespace Project.Common
{
    public static class Utility
    {
        private const float YearDays = 365.25f;
        private const float MonthDays = YearDays / 12f;
        private const float ChildThresholdDays = MonthDays * 36f;

        /*
        ... (Other non-relevant utility methods)
        */

        public static string CalculateAge(DateTime birthday, [Optional] DateTime current)
        {
            if (current == null || current == DateTime.MinValue)
            {
                current = DateTime.Now;
            }
            TimeSpan diff = current.Date.Subtract(birthday.Date);
            double days = diff.Days;

            // age less than zero is not accepted
            if (days < 0) { return "Date incorrecte"; }

            // age less than 1 month
            if (days < MonthDays) { return $"{days} JOUR{(days > 1 ? "S" : "")}"; }

            // age over 1 month but less than ChildThresholdDays
            if (days >= MonthDays && days < ChildThresholdDays)
            {
                double years = Math.Floor(days / YearDays);
                double months = Math.Floor(days % YearDays / MonthDays);

                string yearsText = $"{years} AN{(years > 1 ? "S" : "")}";
                string monthsText = $"{months} MOIS";

                return years >= 1 ? months > 0 ? $"{yearsText} {monthsText}" : yearsText : monthsText;
            }

            // age over ChildThresholdDays or unknown (just in case)
            return days >= ChildThresholdDays ? $"{Math.Round(days / YearDays)} ANS" : "Inconnue";
        }
    }
}

The code runs and outputs the desired values, but I want to know how can it be improved.


texts:
This code is meant to sort a list of integers using merge sort.

I'm doing this to improve my style and to improve my knowledge of fundamental algorithms/data structures for an upcoming coding interview.

def merge_sort(l):
    if len(l) == 0 or len(l) == 1:
        return

    mid = len(l) // 2
    left = l[:mid]
    right = l[mid:]
    merge_sort(left)
    merge_sort(right)
    merge(l, left, right)

def merge(l, left, right):
    l_ind, r_ind, ind = 0, 0, 0
    left_len, right_len, l_len = len(left), len(right), len(l)

    while l_ind < left_len and r_ind < right_len:
        if left[l_ind] < right[r_ind]:
            l[ind] = left[l_ind]
            l_ind += 1
            ind += 1
        else:
            l[ind] = right[r_ind]
            r_ind += 1
            ind += 1

    if l_ind < left_len and r_ind >= right_len:
        while ind < l_len:
            l[ind] = left[l_ind]
            l_ind += 1
            ind += 1
    elif l_ind >= left_len and r_ind < right_len:
        while ind < l_len:
            l[ind] = right[r_ind]
            r_ind += 1
            ind += 1


texts: Tiny Encryption Algorithm implementation in C

texts:
I was just looking for a general feedback about this code, which encrypts a file with the Tiny Encryption Algorithm. I'm currently studying C, and I wanted to know if there was anything I could improve in my coding style or anything. Sorry for my english.

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>

#define BASE_DELTA 0x9e3779b9
#define KEY_VALUE 0x7A24432646294A404E635266556A586E //128bits value

void encrypt (u_int32_t* v, u_int32_t* k) {
  u_int32_t delta = BASE_DELTA * 1;
  for (int i = 1; i <= 32; i++) {
    v[0] += (v[1] * delta) ^ ((v[1] << 4) + k[0]) ^ ((v[1] >> 5) + k[1]);
    v[1] += (v[0] * delta) ^ ((v[0] << 4) + k[2]) ^ ((v[0] >> 5) + k[3]);
    delta += BASE_DELTA;
  }
}

void encryptFile(const char file_to_encrypt_path[], u_int32_t key[4]){

  u_int32_t block[2];

  int nb_bytes_read = 0;
  int fd_to_encrypt = open(file_to_encrypt_path, O_RDONLY, 0655); //RDONLY permissions are 0655
  int fd_result_file = open("encrypted_file.dec", O_CREAT|O_TRUNC|O_WRONLY, 0666);

  while(1){
    memset(block, 0x0, sizeof(u_int64_t));

    nb_bytes_read = read(fd_to_encrypt, block, sizeof(u_int64_t));
    if(nb_bytes_read == -1){
      perror("read");
      exit(errno);
    }
    if(nb_bytes_read == 0){
      break; //EOF
    }
    encrypt(block, key);

    if(write(fd_result_file, block, sizeof(u_int64_t)) ==-1){
      perror("write");
      exit(errno);
    }
  }
}

int main(int argc, char const *argv[]) {
  if (argc < 2){
        printf("usage : %s <file to encrypt> \n", argv[0]);
        exit(EXIT_FAILURE);
  }

  u_int32_t key[4];
  u_int32_t block[2];
  memset(key, 0x0, sizeof(u_int32_t) * 4);
  memset(block, 0x0, sizeof(u_int32_t) * 2);

  __uint128_t key_val = KEY_VALUE; //Note that __uint128_t requiers gcc version > 4.4
  *key = key_val;

  encryptFile(argv[1], key);

  return 0;
}


texts:
How can I improve this code? It computes the Ackermann function as long as m<4 and n<13.

#include <iostream>
#include <limits>

// Ackermann function calculations
unsigned int ackermann(unsigned int m, unsigned int n){
    if(m == 0)
        return n+1;
    if(n == 0)
        return ackermann(m-1,1);
    return ackermann(m-1,ackermann(m,n-1));
}

// Check for non-integer input
bool inputCheck(){
    if(!std::cin.fail())
        return false;

    std::cout << "Invalid input!" << std::endl;
    return true;
}

// Check for negative or overflow errors
bool numCheck(int i, char name){
    if(i < 0){
        std::cout << "Negative error!" << std::endl;
        return true;
    }

    if(name == 'm' && i > 3){
        std::cout << "Overflow error (m > 3)!" << std::endl;
        return true;
    }

    if(name == 'n' && i > 12){
        std::cout << "Overflow error (n > 12)!" << std::endl;
        return true;
    }

    return false;
}

// Run input and num checks
bool check(int x, char y){
    bool result = inputCheck() || numCheck(x, y);

    std::cin.clear();
    std::cin.ignore();

    return result;
}

int main(){

    int m, n;
    bool valM, valN;

    do{
        std::cout << "m = ";
        std::cin >> m;
        valM = check(m, 'm');
    } while(valM);

    do{
        std::cout << "n = ";
        std::cin >> n;
        valN = check(n, 'n');
    } while(valN);

    std::cout << "\nM = " << m << "\nN = " << n
            << "\n\nCALCULATING..." << std::endl;

    std::cout << "A(" << m << ',' << n << ") = "
            << ackermann(m,n) << std::endl;

    return 0;
}

A majority of the code is for detecting errors (such as invalid or negative input) and for preventing overflow errors (such as Ackermann(4,2)). A minority of the code actually calculates the Ackermann function.


texts:
Notes

I'm working my way through SICP, and as I got very confused by the section on folds, I decided to try to implement foldr in scheme and javascript to understand how it works differently with immutable and mutable variables.

I'm mostly looking for advice on whether or not what I've done makes sense idiomatically in each language, but any other feedback would be very much appreciated.

Scheme

;Foldr implemented so I can understand it
(define (foldright function initial collection)
        (if (not (pair? collection))
             initial
            (foldright function (function initial (car collection)) (cdr collection))))

;Test Case (should return 10)
(foldright (lambda (x y) (+ x y)) 0 (list 1 2 3 4))

Javascript

function foldr(func, initial, collection) {
    if (collection.length === 0) {
        return initial
    };
    initial = func(initial, collection[0]);
    collection.shift();
    return foldr(func, initial, collection);
};

//Test case (should return 10)
var result = foldr(function (a, b) {
    return a + b;
}, 0, [1, 2, 3, 4]);

console.log(result);


texts:
is being first and unique.

Challenge:

  Write a program which finds the first non-repeated character in a string.

Specifications:

  The first argument is a path to a file.
  The file contains strings, one per line.
  Print out the first non-repeated character of each string.

Solution:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Map;
import java.util.LinkedHashMap;
import java.util.Scanner;

public class NoRepeat {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner input = new Scanner(new File(args[0]));

        while (input.hasNextLine()) {
            System.out.println(
                retrieveFirstNonRepeatedLetter(input.nextLine())
            );
        }
    }

    public static char retrieveFirstNonRepeatedLetter(String input) {
        Map<Character, Boolean> letters = new LinkedHashMap<>();
        char firstNonRepeated = ' ';

        for (int i = 0; i < input.length(); i++) {
            char current = input.charAt(i);

            if (letters.containsKey(current)) {
                letters.put(current, false);
            } else {
                letters.put(current, true);
            }
        }

        for (Map.Entry<Character, Boolean> entry : letters.entrySet()) {
            if (entry.getValue() == true) {
                firstNonRepeated = entry.getKey();
                break;
            }
        }

        return firstNonRepeated;
    }
}

This solution is \$O(n)\$ but I get the feeling that it's far from the best possible way to accomplish this.

I thought maybe I should set it to account for upper and lower cases, but it wasn't specified (and 100% passed with this implementation).

Tests:

public class MyFirstUnitTest {
    @Test
    void toothyTest() {
        assertEquals('h', NoRepeat.retrieveFirstNonRepeatedLetter("tooth"));
    }

    @Test
    void smellyTest() {
        assertEquals('d', NoRepeat.retrieveFirstNonRepeatedLetter("odor"));
    }
}


texts:
I have a class, and it does one thing, It adds numerals to the numerals array.

In doing so it uses a number of private methods and has ended up looking a little bit sickening...

brace yourself...

require './lib/number_interpreter'
require './lib/numeral_adders/m_adder'
require './lib/numeral_adders/cm_adder'
require './lib/numeral_adders/cd_adder'
require './lib/numeral_adders/d_adder'
require './lib/numeral_adders/c_adder'
require './lib/numeral_adders/xc_adder'
require './lib/numeral_adders/xl_adder'
require './lib/numeral_adders/l_adder'
require './lib/numeral_adders/x_adder'
require './lib/numeral_adders/ix_adder'
require './lib/numeral_adders/iv_adder'
require './lib/numeral_adders/v_adder'
require './lib/numeral_adders/i_adder'

# A class for adding individual numerals
class NumeralAdder
  attr_reader :num_to_convert,
              :num_interpreter,
              :numeral

  def initialize(num_to_convert)
    @num_to_convert = num_to_convert
    @num_interpreter = NumberInterpreter.new(num_to_convert)
    @numeral = []
  end

  def add_numerals
    @numeral << m_adder.add_numerals.split('')
    @numeral << cm_adder.add_numerals.split('')
    @numeral << cd_adder.add_numerals.split('')
    @numeral << d_adder.add_numerals.split('')
    @numeral << c_adder.add_numerals.split('')
    @numeral << xc_adder.add_numerals.split('')
    @numeral << xl_adder.add_numerals.split('')
    @numeral << l_adder.add_numerals.split('')
    @numeral << x_adder.add_numerals.split('')
    @numeral << ix_adder.add_numerals.split('')
    @numeral << iv_adder.add_numerals.split('')
    @numeral << v_adder.add_numerals.split('')
    @numeral << i_adder.add_numerals.split('')
    flatten_numeral
  end

  private

  def flatten_numeral
    @numeral = @numeral.flatten
  end

  def m_adder
    MAdder.new(@num_interpreter.thousands)
  end

  def cm_adder
    CMAdder.new(@num_interpreter.hundreds)
  end

  def cd_adder
    CDAdder.new(@num_interpreter.hundreds)
  end

  def d_adder
    DAdder.new(@num_interpreter.hundreds)
  end

  def c_adder
    CAdder.new(@num_interpreter.hundreds)
  end

  def xc_adder
    XCAdder.new(@num_interpreter.tens)
  end

  def xl_adder
    XLAdder.new(@num_interpreter.tens)
  end

  def l_adder
    LAdder.new(@num_interpreter.tens)
  end

  def x_adder
    XAdder.new(@num_interpreter.tens)
  end

  def ix_adder
    IXAdder.new(@num_interpreter.units)
  end

  def iv_adder
    IVAdder.new(@num_interpreter.units)
  end

  def v_adder
    VAdder.new(@num_interpreter.units)
  end

  def i_adder
    IAdder.new(@num_interpreter.units)
  end
end

I'm thinking I need to separate the private class creations into their own class, but i'm not sure how.

Any tips?


texts:
I have a "cumulative" lookup array for a custom collection view layout.

The idea is that I have an array of rectangles, each with an index. The index is not unique, and is monotonically increasing. I need to create a lookup table, such that given a cell index, it returns the accumulated height of all rects lower than that index.

Here is my implementation. I am wondering if it can be improved (for maintainability) using functional programming, or an established algorithm. Nested loops always raises a flag for me:

var offsets: [CGFloat] = [0]

while metas.count > 0 {
    // meta is a struct that holds an index and rect.
    let meta = metas.removeAtIndex(0)

    while offsets.count <= meta.index {
        // copy the previous value, to maintain accumulation
        offsets.append(offsets[offsets.count - 1])
    }

    offsets[meta.index] += meta.rect.height
}

let cellCount = self.collectionView?.numberOfItemsInSection(0) ?? 0

// need to pad the array at the end
while offsets.count < cellCount {
    offsets.append(offsets[offsets.count - 1])
}

Background:

I am implementing my own collection view layout. It has sticky headers, custom supplementary views, and other customizations. To implement a custom layout, 4 critical methods must be implemented:

override func collectionViewContentSize() -> CGSize {
    let width = self.collectionView?.bounds.width ?? 0
    let height = allLayoutAttributes.last?.frame.maxY ?? 0

    return CGSize(width: width, height: height)
}

override func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? {
    return allLayoutAttributes.filter {
        $0.frame.intersects(rect)
    }
}

override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes! {
    return cellLayoutAttributes[indexPath.item]
}

override func layoutAttributesForSupplementaryViewOfKind(elementKind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes! {
    return supplementaryLayoutAttributes[indexPath.item]
}

As you can see from the implementation, I am preferring computing everything ahead of time, and then just returning the attributes when the methods are called. Now, since supplementary views are inlined with the cells, here is how I was computing things:

Since cell height is fixed, calculate the position of all supplementary view. I know all their offsets, but they vary in height.
cells need to be offset by all the cell heights before them + supplementary heights.

The approach I took above was to compute supplementary view in isolation, get it over with, create a lookup table for the offsets they represent, then iterate the cells and apply the offset as required.


texts:
I'm new to C, want to know if I'm doing this right.

//repstring.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char **argv)
{
    //Initialize variables and pointers
     int i;
     int loop;
     char *deststr;
     char *str;

     //Change second argument to integer
     loop = atoi(argv[2]);

    //If user requests to repeat string more than 9999 times, terminate
    if(loop > 9999)
    {
        printf("Error: Asked to repeat too many times.\n");
        printf("Hardcoded maximum: 9999\n");
        return 1;
    }

    if(argc == 3)
    {

        //Dynamically allocate memory to strings
        deststr = malloc(1024 * 1024 * 1024  * sizeof(char));
        str = malloc(1024 * 1024 * 1024  * sizeof(char));

        if(str == NULL || deststr == NULL)
        {
            printf("Error allocating memory!\n");
            free(deststr);
            free(str);
            return 1;
        }

        //Copy string in first argument to str
        strncpy(str, argv[1], 50);

        //Append str to deststr for amount of times specified in second argument
        for(i = 0; i < loop ; i++)
        {
            strcat(deststr, str);
        }

        //Print repeated string to stdout
        printf("%s\n", deststr);

        //Free allocated memory
        free(deststr);
        free(str);

    }
    else
    {
        printf("Usage: repstring <string> <amount of times to repeat>\n");
        return 1;
    }

 return 0;
}

Is there anything that could be otherwise improved? Am I handling memory correctly?
Review would be very appreciated.


texts: Server-side processing data table best and secure code using ajax

texts:
I am using PHP and Server-side processing data tables. I have more than 30k records on my table and I have to display the records on my page when reload so I used the below code.
Is this code is the best and secure? Please help me out with this.
HTML

      Project Names
      Created By
      Date of Added
      Action

Script
$(document).ready(function() {
  $('#projectList').DataTable({
    "processing": true,
    "serverSide": true,
    "lengthMenu": [
      [25, 50, -1],
      [25, 50, "All"]
    ],
    "ajax": {
      url: "fetch.php",
      data: {
        action: "projectList"
      }
    },
  });
})

fetch.php
<?php
ob_start();
session_start();
require_once 'connection.php';
///Project List
if ($_REQUEST['action'] == 'projectList')
{
    // DB table to use
    $table = 'tbl_projectnamelist';
    // Table's primary key
    $primaryKey = 'project_id';

    $columns = array(
        array(
            'db' => 'project_name',
            'dt' => 0
        ) ,
        array(
            'db' => 'created_by',
            'dt' => 1
        ) ,
        array(
            'db' => 'date_of_added',
            'dt' => 2
        ) ,
        array(
            'db' => 'project_id',
            'dt' => 3,
            'formatter' => function ($d, $row)
            {
                return 'Edit Archieve';
            }
        ) ,

    );
    require ('lib/datatables/ssp.class.php');
    $where = "project_is_active='1'";
    echo json_encode(SSP::complex($_GET, $pdo, $table, $primaryKey, $columns, $where));
}

?>


texts:
I want to write a function to produce an inclusive range of Day such that Saturdays are excluded.

import Data.Time.Calendar
import Data.Time.Calendar.WeekDate

let sel3 (_, _, x) = x
let dateRange d1 d2 = takeWhile (<= d2) [ d | d <- map (flip addDays d1) [1..], (sel3 . toWeekDate) d /= 6]

I believe the code is correct as written, but I'd like to know if there's anything non-idiomatic.


texts: Disjoint set implementation as linked list

texts:
I have just 'wrote' a linked list implementation of Disjoint Sets. This is the changed version of Bob Tian's implememnation. Can you take a look and tell me if there is something missing ? For instance memory leaks while destroying nodes. And please judge it also in performance matter.

I would like to change the long NodeAddress[9999] = {0}; to something better but:
this implementation is used for Connected-component labeling so every time I examine the pixel that needs to be added to labels array I add it. But in the end I do not know how many of them will be there and I need some way to access them (in case i would need to use them later on - for instance union it with another label)

#include <iostream>

using namespace std;

long NodeAddress[9999] = {0};
int n=0;

class ListSet {
private:
    struct Item;
    struct node {
        int val;
        node *next;
        Item *itemPtr;
    };
    struct Item {
        node *hd, *tl;
    };

public:
    ListSet() { }
    long makeset(int a);
    long find (long a);
    void Union (long s1, long s2);
};

long ListSet::makeset (int a) {
    Item *newSet = new Item;
    newSet->hd = new node;
    newSet->tl = newSet->hd;
    node *shd = newSet->hd;
    NodeAddress[a] = (long) shd;
    shd->val = a;
    shd->itemPtr = newSet;
    shd->next = 0;
    return (long) newSet;
}

long ListSet::find (long a) {
    node *ptr = (node*)a;
    return (long)(ptr->itemPtr);
}

void ListSet::Union (long s1, long s2) {
    node *ptr1 = (node*)s1;
    node *ptr2 = (node*)s2;

    Item *set2 = ptr1->itemPtr;
    node *cur = set2->hd;

    Item *set1 = ptr2->itemPtr;

    while (cur != 0) {
        cur->itemPtr = set1;
        cur = cur->next;
    }
    //join the tail of the set to head of the input set
    (set1->tl)->next = set2->hd;
    set1->tl = set2->tl;
    delete set2;
}

int main () {

    ListSet a;
    long s1, s2, s3, s4;
    s1 = a.makeset(13);
    s2 = a.makeset(25);
    s3 = a.makeset(45);
    s4 = a.makeset(65);
    cout<<s1<<' '<<s2<<' '<<s3<<' '<<s4<<endl;
    cout<<"a.find(NodeAddress[65]): "<<a.find(NodeAddress[65]) <<endl;
    cout<<"a.find(NodeAddress[45]): "<<a.find(NodeAddress[45]) <<endl;
    cout<<"a.Union(NodeAddress[65], NodeAddress[45]) "<<endl;

    a.Union(NodeAddress[65], NodeAddress[45]);

    cout<<"a.find(NodeAddress[65]): "<<a.find(NodeAddress[65]) <<endl;
    cout<<"a.find(NodeAddress[45]): "<<a.find(NodeAddress[45]) <<endl;
}


texts:
Here is a naive implementation of a kernel density regression algorithm in Julia.

The code works, but there is quite a bit of room for improvement though. First, there is not an optimal bandwidth selection implemented and second; it's really slow. Nevertheless, it took me a while to implement and I am really looking forward to any suggestions on how to improve the precision and performance of the code.

function kernelRegression(x, y, h)
    #length of the actual data
    n = length( x )

    #if length of the data is smaller then 100,
    #use 100 for the length of the sequence to make sure the curve
    #can be plotted smoothly
    l = min( n, 100 )
    seq = linspace(minimum(x), maximum(x), l)

    #bandwidth for the gaussioan kernel approx to:
    h = 1.06 * std( x ) * n ^(-.2)

    #store the result in
    est = zeros(Real, l)

    #gaussian kernel
    function kernel( u )
        exp ( -.5 * u^2 )
    end

    #compute the estimate over the entire sequence of values
    #basic algorithm:
    #for every x in sequence from min ( data ) to max ( data )
        #   for every observation in data
        #       calulate the kernel density function at this particular point
        #       which is the sum of all the kernels on the x axis devided by n * binwidth
        #       multiply the kernel at this point with the respective y value
        #       and devide by the sum of kernels
    for (index, sequence) in enumerate( seq )

        #reset the weights
        weight = 0.0

        for ( i, ob ) in enumerate( x )

            temp = 0.0
            #inner loop: calculate the mean
            #of the kernels at X_i = x
            for obs in  x
                u = ( sequence - obs ) / h
                temp += kernel ( u )
            end
            temp /= ( n * h )

            #use temp to calculate the estimate of y at X_i = x
            v = ( sequence - ob ) / h
            weight += ( kernel ( v ) / temp ) * y[i]
        end

        est[index] = weight / ( n * h )
    end
    est
    #scatter(x, y)
    #plot(seq, est, color="red")
end

(() ->
begin
    x = rand(Uniform(-6, 6), 1000)
    y = cos(x) + rand(Normal(0, 0.2), 1000)
    kernelRegression(x, y)
    scatter(x,y)
    plot(linspace(-6,6,1000), y_est)
end)()


texts: SQL report of subscribers and their associated revenue

texts:
A user can have many subscriptions, and a subscription belongs to one plan.  The plans table tells us a subscription's cost.  Is the query below the correct one for figuring out the number of subscriptions purchased by a user with an "ongoing" status and the total revenue brought in each day  between Jan 1 and Mar 4, 2016?

Essentially, I'm creating a business report via SQL.  Each "day" bucket should contain the number of ongoing subscriptions created that day and the the total revenue brought in by those subscriptions that day.

select
    extract(MONTH from subscriptions.created_at) as mth,
    extract(DAY from subscriptions.created_at) as dy,
    count(subscriptions.id) as subs,
    round(sum(plans.cost)::numeric, 2) as revenue
from users
JOIN subscriptions ON subscriptions.user_id = users.id
JOIN plans ON subscriptions.plan_id = plans.id
where subscriptions.subscription_status = 'ongoing'
and subscriptions.created_at >= '01/01/16'
and subscriptions.created_at <= '03/04/16'
group by MTH, DY order by MTH, DY


texts: Rails API for communication between two Rails app where the former app posts data to the latter and the latter return a response

texts:
The Controller code for the first app to post data to another app

 module Api
 module V1
 class OrderApiController < ApiController
   def send_invoice_data
        response = Hash.new
        result = Hash.new
        debugger
        order = Order.includes(:status, :user, payment:
         [:status]).where(txnid: params[:txnid]).first
        if order
            if (['Notary', 'Attestation','Franking'].include?
        order.service.name)
                no_of_copies = ((order.answers.where(question_id:
             [37,15]).length > 0) ? order.answers.where(question_id:
            [37,15]).first.body : 0).to_i
            else
                no_of_copies = ((order.answers.where(question_id:
                [37,15]).length > 0) ? order.answers.where(question_id:
                [37,15]).first.body : 0).to_i + 1
            end
             response.merge! ApiStatusList::OK
             response =
                 HTTParty.post('http://localhost:3001/api/v0/generate_invoice?
                 key=docket', :body => { "order" => {
                      "id" => order.id,
                      "txnid" => order.txnid,
                      "service_name" => order.service.name,
                      "payment_date" => order.payment ?
                       order.payment.created_at.strftime('%d/%m/%Y') :
                       order.created_at.strftime('%d/%m/%Y'),
                                :
                                :
                      "delivery_amount" => order.delivery_amount || '',
                      "no_of_copies" => no_of_copies}}.to_json, :headers => {
                     'Content-Type' => 'application/json'})
        else
            response.merge! ApiStatusList::INVALID_REQUEST
        end
        render :json => response
    end
   end
   end
   end

The second controller api code accepts data from the former app, creates and generates the invoice pdf using wicked_pdf, uploads it to aws and returns the link of the stored pdf as response to latter app

 module Api
module V0
    class InvoiceApiController < ApiController

        def order_invoice
            response = Hash.new
            result = Hash.new
            debugger
            if params[:order] && params[:order][:txnid]
                @order = params[:order]
                @order['stamp_amount'] = params[:order][:stamp_amount] || ''
                @order['txnid'] = params[:order][:txnid]
                @order['service_name'] = params[:order][:service_name] || ''
                @order['payment_date'] = params[:order][:payment_date]
                @order['payment_mode'] = params[:order][:payment_mode] || ''
                    :
                    :
                @order['discount'] =  params[:order][:discount] || ''
                @no_of_copies = params[:order][:no_of_copies]
                pdf = WickedPdf.new.pdf_from_string(
                render_to_string(template:
                'invoices/generate_invoice.pdf.erb', filename: params[:order]
                 [:txnid] + ".pdf" ,
                                type: 'application/pdf', disposition:
                 'attachment', print_media_type: true))
                save_path = Rails.root.join('pdfs', @order['txnid'] + ".pdf")
                File.open(save_path, 'wb') do |file|
                  file << pdf
                  filename = @order['txnid'] + ".pdf"
                end
               file_name =  @order['txnid'] + ".pdf"
               upload = Invoice.upload(save_path, file_name)
               response['result'] = upload
               response.merge! ApiStatusList::OK
            else
                response.merge! ApiStatusList::INVALID_REQUEST
            end
            render :json => response
        end


texts:
I want my QuickSort class to have a static sort method that sort any List for any object that extends Comparable. Have I coded my class correctly? Can I make the use of generics a bit cleaner or is this the only way to code the signatures of the methods?

import java.util.List;

public class QuickSort{

    private QuickSort() {
        // prevent instantiation
    }

    public static <T extends Comparable<? super T>> void sort(List<T> list) {
        quickSort(list, 0, list.size());
    }

    private static <T extends Comparable<? super T>> void quickSort(List<T> array, int start, int arrayLength){
        if(start < arrayLength){
            int q = partition(array, start, arrayLength);
            quickSort(array, start, q);
            quickSort(array, q+1, arrayLength);
        }
    }

    private static <T extends Comparable<? super T>> int partition(List<T> array, int end, int arrayLength){
        T last = array.get(arrayLength-1);
        int i = end-1;
        for(int j = end; j < arrayLength-1; j++){
            if(array.get(j).compareTo(last) <= -1 || array.get(j).compareTo(last) == 0){
                i = i+1;
                exchange(j, i, array);
            }
        }
        exchange(arrayLength-1, i+1, array);
        return i + 1;
    }

    private static <T extends Comparable<? super T>> void exchange(int j, int i, List<T> array){
        T temp = array.get(j);
        array.set(j, array.get(i));
        array.set(i, temp);
    }
}


texts: I want to take away WebService call from UIViewController

texts:
I am using Moya to make network calls in Swift.

In my ViewController I am calling the WebService and creating a model from response.

import UIKit
import Moya

class LoginViewController: UIViewController {
  let provider = MoyaProvider<Api>()

  override func viewDidLoad() {
    super.viewDidLoad()
    generateAccessToken()
  }

  private func generateAccessToken() {
    provider.request(.generateAccessToken(
        mobile: phoneTextField.text!,
        countryCode: "91",
        name: "Saurabh",
        otp: "9612")
    ) { result in
        switch result {
        case .success(let response):
            let data = response.data
            let user = try? JSONDecoder().decode(User.self, from: data)
            if let authToken = user?.authToken {
                AuthManager.setToken(token: authToken)
            }
        case .failure(let error):
            print(error.response?.statusCode as Any)
        }
    }
  }

I want to move the WebService call to other file, say NetworkManager.swift

import Foundation
import Moya

struct NetworkManager {
  public static let shared = NetworkManager()
  private let provider = MoyaProvider<Api>()

  func generateAccessToken(with mobile: String, countryCode: String, name: String, otp: String)  {
    // Get result and return to calling class
  }
}

But it is strongly recommended not to use Singleton Class.

How should I call my WebService and return the response to the LoginViewController?


texts: Splitting two ObservableCollections lightning fast

texts:
I'm working on wiring up a bindable Map for Xamarin Forms, and I need a fast way of dividing up the ObservableCollections (collection of map markers) as quickly as possible. Collections are a weak area for me, and I find myself doing too many foreach's when they're not necessary.

Here's what I have now.

private static void MarkerSourceCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
    var markers = ((IEnumerable<XfxMarker>) sender).ToList();

    var comparer = new MapMarkerComparer();
    var offScreen = new List<XfxMarker>();
    var markersToAdd = markers.Where(m => _map.MapBounds.Contains(m.CenterPoint), out offScreen)
        .Except(_oldMarkers, comparer);

    var markersToRemove = _oldMarkers.Except(markers, comparer).Union(offScreen);
    _map.HandleMarkersChanged(markers, new MapMarkersChangedEventArgs(markersToAdd, markersToRemove));
    _oldMarkers = markers;
}

With the comparer

internal class MapMarkerComparer : IEqualityComparer<XfxMarker>
{
    public bool Equals(XfxMarker x, XfxMarker y)
    {
        if (ReferenceEquals(x, y)) return true;
        if (ReferenceEquals(x, null) || ReferenceEquals(y, null)) return false;
        var result = x.CenterPoint.Latitude.ToString() == y.CenterPoint.Latitude.ToString()
                     && x.CenterPoint.Longitude.ToString() == y.CenterPoint.Longitude.ToString();
        return result;
    }

    public int GetHashCode(XfxMarker obj)
    {
        unchecked
        {
            var hash = 0;
            if (obj.CenterPoint == null) return hash;
            hash = hash + 17;
            hash = hash*23 + obj.CenterPoint.Longitude.GetHashCode();
            hash = hash*23 + obj.CenterPoint.Latitude.GetHashCode();
            return hash;
        }
    }
}

And my custom Where extension.

    public static IEnumerable<T> Where<T>(this IEnumerable<T> input, Func<T, bool> predicate, out List<T> remainder)
    {
        var leftover = new List<T>();
        var output = new List<T>();
        foreach (var item in input)
        {
            if (predicate.Invoke(item))
            {
                output.Add(item);
            }
            else
            {
                leftover.Add(item);
            }
        }
        remainder = leftover;
        return output;
    }
}

Now I'm sure there has to be a more efficient way to split these lists, but I'm just not sure what.


texts: Automata theory, state reachability in Haskell

texts:
I wrote a small library to learn Haskell while studying Automata theory. I have some concerns on my algorithm to evaluate state reachability. That is, I think it might be improved if I can avoid checking paths already excluded in other branches of the search for a valid path. This one recursively checks each path separately.

I hope I didn't forget anything. Other suggestions are obviously welcome!

Automaton data type

-- | Represents an automaton in the form
--   /G = (X, E, f, Gamma, x_0, X_m)/
--
--   NB: we're not including Gamma in the definition of Automaton
data Automa st ev = Automa {
    states     :: [st],             -- ^ /X/, set of states
    events     :: [ev],             -- ^ /E/, set of events
    mapTrans   :: M.Map (st,ev) st, -- ^ not /f/, but a map of
                                    --   transitions (see 'trans')
    initial    :: st,               -- ^ /x_0/, initial state
    marked     :: [st]              -- ^ /X_m/, set of marked states
} deriving (Show, Read)

Reachability function

-- | True if a state can reach another for some string of events.
canReach :: (Ord st, Ord ev)
    => st                   -- ^ starting state 's'
    -> st                   -- ^ arrival state 's''
    -> Automa st ev
    -> Bool
canReach s s' au = canReachExcluding s s' au []

-- | True if a state can reach another for some string of events,
--   excluding passing from specified states.
canReachExcluding :: (Ord st, Ord ev)
    => st                   -- ^ starting state 's'
    -> st                   -- ^ arrival state 's''
    -> Automa st ev
    -> [st]                 -- ^ the states to be excluded
    -> Bool
canReachExcluding s s' au ex = s == s' || any (== s') rs
    || any (\x -> canReachExcluding x s' au (s:ex)) rs
        where rs = reach1From s au \\ ex

-- | Returns states reachable from specified state in one step.
reach1From :: (Ord st, Ord ev) => st -> Automa st ev -> [st]
reach1From s au = [ trans' (s,e) au | e <- gammaL s au ]

Accessory functions

-- | Indicator function of active states for an automaton
gamma :: (Ord st, Ord ev)
    => (st,ev)                 -- ^ state-event pair of interest
    -> Automa st ev
    -> Bool                    -- ^ 'True' if 'ev' is active for 'st'
gamma (s,e) au = M.member (s,e) $ mapTrans au

-- | Returns a list of active events for a state of a given 'Automa'
gammaL :: (Ord st, Ord ev) => st -> Automa st ev -> [ev]
gammaL s au = [ e | e <- events au, gamma (s,e) au ]

-- | Transition function: where do I get if 'ev' happens when in 'st'?
trans :: (Ord st, Ord ev) => (st, ev) -> Automa st ev -> Maybe st
trans (s,e) au = M.lookup (s,e) $ mapTrans au

-- | Like 'trans', but to be used if you're sure it's a valid
--   transition (i.e. saves you a 'fromJust').
trans' :: (Ord st, Ord ev) => (st, ev) -> Automa st ev -> st
trans' (s,e) au = fromJust $ M.lookup (s,e) $ mapTrans au


texts:
I have some lines that form triangles. I'd like to challenge the fastest way to find all triangles.

In particular the code should take an ArrayList of Line2D object and return an ArrayList of Triangle2D. The only constrain is to use p1.distanceToSquared(p2) < 1) as equal function.
Note:
My code does not work because it contains some triangles more time (10 triangles instead of 8), i.e. I didn't managed to write the triangle comparator.
This is my Java code (using this lib that has some standard 2D objects):
private ArrayList<Triangle2D> findTrinaglesTromLines(ArrayList<Line2D> lines) {

    class TriangleComparator implements Comparator<Triangle2D>{
        @Override
        public int compare(Triangle2D t1, Triangle2D t2) {
            TreeSet<Vec2D> pts1 = new TreeSet<Vec2D>();
            pts1.add(t1.a); pts1.add(t1.b); pts1.add(t1.c);

            TreeSet<Vec2D> pts2 = new TreeSet<Vec2D>();
            pts2.add(t2.a); pts2.add(t2.b); pts2.add(t2.c);

            if (pts1.containsAll(pts2)) return 0;
            else return 1;
        }
    }

    TreeSet<Triangle2D> triangles = new TreeSet<Triangle2D>(new TriangleComparator());
    for(int i=0; i<lines.size(); i++) {
        Line2D l1, l2, l3;
        l1 = lines.get(i);
        for (int j=0; j<lines.size(); j++) {
            Line2D m = lines.get(j);
            if(l1==m)continue;
            if(shareVertex(l1, m)) {
                l2 = m;
                for(int k=0; k<lines.size(); k++) {
                    Line2D n = lines.get(k);
                    if(l1==n || l2==n) continue;
                    l3 = n;
                    if( shareVertex(l1, l3) || shareVertex(l2, l3) ) {
                        Triangle2D t = getTraingle(l1, l2, l3);
                        if( t!= null ) {
                            triangles.add(t);
                            println(t.toString());
                        }
                    }
                }
            }
        }
    }
    return new ArrayList<Triangle2D>(triangles);
}

private boolean shareVertex(Line2D l1, Line2D m) {
    if( l1.a.distanceToSquared(m.a) < 1) return true;
    if( l1.a.distanceToSquared(m.b) < 1) return true;
    if( l1.b.distanceToSquared(m.b) < 1) return true;
    return false;
}

private Triangle2D getTraingle(Line2D a, Line2D b, Line2D c) {
    TreeSet<Vec2D> pts = new TreeSet<Vec2D>();
    pts.add(a.a); pts.add(a.b);
    pts.add(b.a); pts.add(b.b);
    pts.add(c.a); pts.add(c.b);
    if(pts.size()!=3) return null;
    Iterator<Vec2D> iterator = pts.iterator();
    Triangle2D t = new Triangle2D();
    t.a = iterator.next();
    t.b = iterator.next();
    t.c = iterator.next();
    return t;
}

Here the lines (begin point, end point):
[ {x:568.051, y:286.209}, {x:505.477, y:411.501} ]
[ {x:505.477, y:411.501}, {x:696.271, y:462.066} ]
[ {x:696.271, y:462.066}, {x:568.051, y:286.209} ]
[ {x:696.271, y:462.066}, {x:672.033, y:213.228} ]
[ {x:672.033, y:213.228}, {x:568.051, y:286.209} ]
[ {x:145.374, y:290.304}, {x:176.77, y:455.729} ]
[ {x:176.77, y:455.729}, {x:332.868, y:284.48} ]
[ {x:332.868, y:284.48}, {x:145.374, y:290.304} ]
[ {x:332.868, y:284.48}, {x:191.991, y:192.966} ]
[ {x:191.991, y:192.966}, {x:145.374, y:290.304} ]
[ {x:176.77, y:455.729}, {x:505.477, y:411.501} ]
[ {x:505.477, y:411.501}, {x:332.868, y:284.48} ]
[ {x:261.672, y:132.32}, {x:574.957, y:159.359} ]
[ {x:568.051, y:286.209}, {x:574.957, y:159.359} ]
[ {x:332.868, y:284.48}, {x:568.051, y:286.209} ]
[ {x:261.672, y:132.32}, {x:332.868, y:284.48} ]
[ {x:332.868, y:284.48}, {x:574.957, y:159.359} ]


texts:
I am using two more helper stacks to sort. Kindly suggest improvements in terms of space and time.

import java.util.ArrayDeque;
import java.util.Deque;

public class SortStackAscendingOrder {

    Deque<Integer> stackhelper1 = new ArrayDeque<>();
    Deque<Integer> stackHelper2 = new ArrayDeque<>();

    public Deque<Integer> sortStack(Deque<Integer> mainStack) {
        if (mainStack.isEmpty()) {
            return null;
        }

        while (!mainStack.isEmpty()) {
            int mainItem = mainStack.pop();
            int helperItem1 = -1;
            if (!stackhelper1.isEmpty()) {
                helperItem1 = stackhelper1.peek();
            }
            if (mainItem > helperItem1) {
                // push all helperItem1 to helperItem2, till it is in ascending
                // order
                while (!stackhelper1.isEmpty() && mainItem > helperItem1) {
                    stackHelper2.push(stackhelper1.pop());
                    helperItem1 = stackhelper1.peek();
                }
                // push mainItem.
                stackhelper1.push(mainItem);
                // bring back all the helperItem2
                while (!stackHelper2.isEmpty()) {
                    stackhelper1.push(stackHelper2.pop());
                }
            } else {
                // directly push in stackhelper1
                stackhelper1.push(mainItem);
            }
        }

        return stackhelper1;

    }

}


texts: Takes in two sorted lists and outputs a sorted list that is their union

texts:
Write a function that takes in two sorted lists and outputs a sorted
  list that is their union

Could anyone help me to improve this code and make it more user-friendly? We are not supposed to use any built-in Python functions, but rather develop our own efficient algorithms.

def answer(list1, list2):

    len1 = len(list1)
    len2 = len(list2)

    final_list = []
    j = 0
    k = 0

    for i in range(len1+len2):

        if k == len1:
            final_list.append(list2[j])
            j += 1
            continue

        if j == len2:
            final_list.append(list1[k])
            k += 1
            continue

        if list1[k] < list2[j]:
            final_list.append(list1[k])
            k += 1

        else:
            final_list.append(list2[j])
            j += 1

    return final_list

print answer([1, 2 , 17, 18, 100], [3, 3, 4, 5, 15, 19, 20, 101])


texts: Copying and pasting from MS Project to MS Excel

texts:
This copies data from a project into Excel to be calculated into a final report. The code runs pretty slowly at this point and I would like it to be a little bit faster. Are there any blatant coding mishaps that are slowing the calculations down?

Sub Update_Schedule()
Dim appProj As MSProject.Application
Dim aProg As MSProject.Project
Dim sel As MSProject.Selection
Dim ts As Tasks
Dim t As Task
Dim rng As Range
Dim rng2 As Range
Dim ws As Worksheet
Dim ws2 As Worksheet

Application.DisplayAlerts = False

'Clear current contents

Set ws2 = Worksheets("Final Report")

Set ws = Worksheets("Master")
Set rng = ws.Range("A:F")
rng.ClearContents
Set ws = Worksheets("Resource List")
Set rng = ws.Range("A:B")
rng.ClearContents

'Open the Project file when it asks to open resource pool, press yes

Set appProj = CreateObject("Msproject.Application")

appProj.DisplayAlerts = False

appProj.FileOpen "File_1.mpp" 'also opens file 2

Set aProg = appProj.Projects("File_1.mpp")

appProj.Visible = True

WindowActivate WindowName:=aProg

'Copy the project columns and paste into Excel

Set ts = aProg.Tasks
SelectTaskColumn Column:="Name"
OutlineShowAllTasks
OutlineShowAllTasks
EditCopy
Set ws = Worksheets("Master")
Set rng = ws.Range("A:A")
ActiveSheet.Paste Destination:=rng
SelectTaskColumn Column:="Duration"
EditCopy
Set rng = ws.Range("B:B")
ActiveSheet.Paste Destination:=rng
SelectTaskColumn Column:="Start"
EditCopy
Set rng = ws.Range("C:C")
ActiveSheet.Paste Destination:=rng
SelectTaskColumn Column:="Finish"
EditCopy
Set rng = ws.Range("D:D")
ActiveSheet.Paste Destination:=rng
SelectTaskColumn Column:="Resource Names"
EditCopy
Set rng = ws.Range("E:E")
ActiveSheet.Paste Destination:=rng
SelectTaskColumn Column:="Project"
EditCopy
Set rng = ws.Range("F:F")
ActiveSheet.Paste Destination:=rng
WindowActivate WindowName:="\\File_2.mpp"
SelectResourceColumn Column:="Name"
EditCopy
Set ws = Worksheets("Resource List")
Set rng = ws.Range("A:A")
ActiveSheet.Paste Destination:=rng
SelectResourceColumn Column:="Category"
EditCopy
Set rng = ws.Range("B:B")
ActiveSheet.Paste Destination:=rng

'Populates formula in Master sheet
Application.Visible = True

Set ws = Worksheets("Master")
Set rng = ws.Range("G2")
Set rng2 = ws.Range("G2:G9223")
rng.AutoFill Destination:=rng2, Type:=xlFillDefault
Set rng = ws.Range("H2")
Set rng2 = ws.Range("H2:H9223")
rng.AutoFill Destination:=rng2, Type:=xlFillDefault

Calculate

ws2.Visible = True

Application.DisplayAlerts = True
appProj.DisplayAlerts = True
End Sub


texts: Replacing for loop in pandas Python search and replace

texts:
I have 2 pandas dataframes. I want to do a find and replace between 2 dataframes. In the df_find dataframe, in the current_title column, i want to search in every row for any occurrence of values from 'keywrod' column in the df_replace dataframe and if found replace it with corresponding value from 'keywordlength' column.

I have been able to get rid of the loop for df_find dataframe since i need to iterate over every row in this dataframe by using str.replace which is a vectorized form of replace function.

Performance matters in my case, as both the dataframes run into GB's. So, i want to get rid of the loop for df_replace here and use any other efficient way of iterating through all rows of df_replace dataframe.

import pandas as pd
df_find = pd.read_csv("input_find.csv")
df_replace = pd.read_csv("input_replace.csv")

#replace
for i,j in zip(df_replace.keyword,df_replace.keywordLength):
    df_find.current_title=df_find.current_title.str.replace(i,j,case=False)

df_replace This dataframe has the data we need for find and replace

keyword       keywordLength
IT Manager    ##10##
Sales Manager ##13##
IT Analyst    ##12##
Store Manager ##13##

df_find is where we need to do the transformation.

Before executing find and replace code:

current_title
I have been working here as a store manager since after I passed from college
I am sales manager and primarily work in the ASEAN region. My primary rolw is to bring new customers.
I initially joined as a IT analyst and because of my sheer drive and dedication, I was promoted to IT manager position within 3 years

After executing find and replace through above code

current_title
I have been working here as a ##13## since after I passed from college
I am ##13## and primarily work in the ASEAN region. My primary rolw is to bring new customers.
I initially joined as a ##12## and because of my sheer drive and dedication, I was promoted to ##10## position within 3 years


texts: Searching for a string in a downloaded PDF

texts:
This code goes to the website containing the PDF, downloads the PDF, then it converts this PDF to text. Finally, it reads this whole file (Over 5000 lines) into a list, line by line, and searches for my name in it.

import mechanize
import os
br = mechanize.Browser()
br.open("http://sttm.org/Bulletin/Bulletins2015/tabid/483/LinkClick.aspx?fileticket=WkjzL8SuMQQ%3d&tabid=483&portalid=0&mid=979")
print br.title()
pdfs = []
for i in br.links():
    if "Sunday," in i.text:
        pdfs.append("http://sttm.org/Bulletin/Buletins2015/" + i.url)
br.retrieve(pdfs[0], "file.pdf")
input = "file.pdf"
output = "out.txt"
os.system(("ps2ascii %s %s") %(input, output))
with open("out.txt") as f:
    list = f.readlines()
scheduled = False
for i in list:
    if "My Name Here" in i:
        scheduled = True;
if scheduled == True:
    print "Yes"
else:
    print "No"

It's a heck of a lot of code to complete this simple task. Also, as it is taking in 5000 lines and reading them one by one, it takes quite a long time to run this.


texts:
I wrote a small generic implementation of a simple generic double buffer pattern, and I was wondering if it's actually thread safe or can be improved in any way.

Note: The specific part that I'm worrying about thread safety is the Swap() function.

/// <summary>
///     Simple generic double buffer implementation class
/// </summary>
public class DoubleBuffer<T> where T : class
{
    private T _current;

    public DoubleBuffer(T current, T next)
    {
        _current = current;
        Next = next;
    }

    /// <summary>
    ///     Next buffer waiting in line (no active usage should be here)
    /// </summary>
    public T Next { get; private set; }

    /// <summary>
    ///     Currently active buffer (active usage should be here)
    /// </summary>
    public T Current
    {
        get { return _current; }
    }

    /// <summary>
    ///     Swaps between the buffers
    /// </summary>
    /// <returns>Returns the buffer previously used before the swap</returns>
    public T Swap()
    {
        var swappedBuffer = _current;
        Interlocked.Exchange(ref _current, Next);
        Next = swappedBuffer;
        return swappedBuffer;
    }
}


texts: Science Buddies derived password cracker

texts:
I am trying to improve the performance of this password cracking method:

def search_method_2(num_pass_wheels):
    global totalguesses
    result = False
    starttime = time.time()
    tests = 0
    still_searching = True
    print("Using method 2 and searching with "+str(num_pass_wheels)+" password wheels.")
    wheel = " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
    # we only allow up to 8 wheels for each password for now
    if (num_pass_wheels > 8):
        print("Unable to handle the request. No more than 8 characters for a password")
        still_searching = False
    # set all of the wheels to the first position
    pass_wheel_array=array('i',[1,0,0,0,0,0,0,0,0])

    while still_searching:
        ourguess_pass = ""
        for i in range(0,num_pass_wheels):  # once for each wheel
            if pass_wheel_array[i] > 0:
                ourguess_pass = wheel[pass_wheel_array[i]] + ourguess_pass
        #print ("trying ["+ourguess_pass+"]")
        if (check_userpass(which_password, ourguess_pass)):
            print ("Success! Password  "+str(which_password)+" is " + ourguess_pass)
            still_searching = False   # we can stop now - we found it!
            result = True
        #else:
            #print ("Darn. " + ourguess + " is NOT the password.")
        tests = tests + 1
        totalguesses = totalguesses + 1

        carry = 1
        for i in range(0,num_pass_wheels): # once for each wheel
            pass_wheel_array[i] = pass_wheel_array[i] + carry
            carry = 0
            if pass_wheel_array[i] > 62:
                pass_wheel_array[i] = 1
                carry = 1
                if i == (num_pass_wheels-1):
                    still_searching = False

    seconds = time.time()-starttime
    report_search_time(tests, seconds)
    return result

This is a modified version of the Science Buddies password cracker (found here: http://www.sciencebuddies.org/science-fair-projects/project_ideas/CompSci_p046.shtml#materials

You can see the full file here if you would like to: https://files.fm/u/bg9ppx77

Basically, I need a way to run this method faster, I can currently do about 200,000 tests (or runs of this method) per second. I would like to double or triple that number so that I can "crack" longer passwords in a reasonable period of time.

If anyone could point me in the right direction that would be great, if anyone has any code ideas that would be amazing.


texts: Calculating time deltas between rows in a Pandas dataframe

texts:
I am trying to compute the difference in timestamps and make a delta time column in a Pandas dataframe. This is the code I am currently using:

# Make x sequential in time
x.sort_values('timeseries',ascending=False)
x.reset_index(drop=True)

# Initialize a list to store the delta values
time_delta = [pd._libs.tslib.Timedelta('NaT')]

# Loop though the table and compute deltas
for i in range(1,len(x)):
    time_delta.append(x.loc[i,'timestamp'] - x.loc[i-1,'timestamp'])

# Compute a Pandas Series from the list
time_delta = pd.Series(time_delta)

# Attach the Series back to the original df
x['time_delta'] = time_delta

It seems like there should be a more efficient / vectorized way of doing this simple operation, but I can't seem to figure it out.

Suggestions on improving this code would be greatly appreciated.


texts: JS code that search through every property in a nested object

texts:
I wrote code to search by keyword, and it will check all of the values from the object property, including an array in the object.  But apparently the code is not optimized as it takes some time to execute the function, and it is subject to client PC processing power.

Here is the sample of the object:

{
    clientId: "-LFQ1ojwCF8lSRq4J9sQ",
    desc: "description lorus ipsum etc",
    document: [
      {
        doc: "photo",
        status: "ok",
        url: "https://www.google.com"
      }
    ],
    dt: "2018-06-24",
    dtactual: "2018-06-26",
    dtcreate: 1529905260612,
    dtexpected: "2018-06-25",
    dtmodify: 1529905260612,
    dtreceive: "2018-06-26",
    engineer: "engineer 001",
    equipment: [
      { brand: "ruckus", imei: 123, imsi: 312, model: "R230-1220v6HW", serialNo: 123},
      { brand: "", imei: "", imsi: "", model: "", serialNo: ""},
      { brand: "", imei: "", imsi: "", model: "", serialNo: ""},
      { brand: "", imei: "", imsi: "", model: "", serialNo: ""},
      { brand: "", imei: "", imsi: "", model: "", serialNo: ""}
    ],
    iwoNum: "iwo num 2",
    key: "-LFpT2ajia6Wgnrd8lQH",
    onSiteSupport: { isSupport: true, supportTerm: "" },
    pm: "project manager 001",
    poNum: "po no 002",
    preventMaintenance: true,
    projectType: "site installation",
    remark: "iwo remark",
  }

Imagine there are 50 or 100, or 1000 of the object in an array, and the user wishes to list the object that contains a specific keyword. So the code need to search every property to find the value.

So below is my code (written in Typescript, but almost same with JS):

iwoLit = []
objectArray = [{...},{...},{...},...]
//the details of the object in this array please refer to above object as it is too long to place at here.
//Feel free to change any value in there.
keyword = 'ruckus'

searchFunction(){
  objectArray.forEach(element => {
    let object = Object.assign({}, element);
    object['key'] = element.key;
    let keys = Object.keys(object)
    for (let i = 0; i < keys.length; i++) {
      let prop = keys[i]
      let item = object[prop]
      if (typeof item == 'string') {
        let item2 = item.toString()
        let item3 = item2.toLowerCase()

        if (item3.indexOf(this.keyword.toLowerCase()) !== -1) {
          if (this.iwoList.length == 0) {
            this.iwoList.push(object);
          }
          else {
            for (let l = 0; l < this.iwoList.length; l++) {
              if (object.key !== this.iwoList[l].key) {
                this.iwoList.push(object);
                return false
              }
            }
          }
        }

      }
      //to handle the array in the object
      let equipValue3
      if (Array.isArray(item)) {
        item.forEach(element2 => {
          let itemKeys = Object.keys(element2)
          for (let j = 0; j < itemKeys.length; j++) {
            let prop2 = itemKeys[j]
            let equipValue = element2[prop2]
            if (typeof equipValue == 'string' || typeof equipValue == 'number') {
              let equipValue2 = equipValue.toString()
              equipValue3 = equipValue2.toLowerCase()
              if (equipValue3.indexOf(this.keyword.toLowerCase()) !== -1) {
                if (this.iwoList.length == 0) {
                  this.iwoList.push(object);
                }
                else {
                  for (let k = 0; k < this.iwoList.length; k++) {
                    if (object.key !== this.iwoList[k].key) {
                      this.iwoList.push(object);
                      return false
                    }
                  }
                }
              }
            }
          }
        })
      }
    }
  });
  console.log(this.iwoList)
}

Would be appreciated if someone can help me optimize the code. It is ok to separate in few functions, as long as the performance can be increased.

Side info: Why do I want to make such a nested object? Because I am using noSQL, and this is the DB design.


texts: Fetching SQL table names and dynamicly insert values

texts:
I need to make a UI where I can edit/insert/remove records of my SQL tables through my app. Edits and deletes of records works fine except of insertions when it comes to tables with auto-incremented PKs.
I created a combobox populated with the names of tables and by using the sql schema I try to generate dynamic code for each table.

This method returns the model for the box.

public static String[] getPartType() {
        ResultSet rs = null;
        List<String> list = new ArrayList<String>();
        list.add("None");
        try {
            stmt = ccd_db_connection.getConnection().prepareStatement(
                    "SELECT table_name FROM information_schema.tables t WHERE table_catalog = 'xxxx' AND t.TABLE_TYPE='BASE TABLE' ");
            rs = stmt.executeQuery();
            while (rs.next()) {
                list.add(rs.getString(1));
            }
            stmt.close();
            rs.close();
        } catch (SQLException e) {
            new ConnectionMessage(e);
        }
        return list.toArray(new String[0]);
    }

After selecting the table I populate my custom JTable and project the corresponding records customizing just the FROM part of the query. To keep this post sort I'll jump right on insertion since everything else seems to be working.

This is the method where I do the insertion

public static void insertParts(String tableName, Vector<String> colNames, Vector<Object> data) throws SQLException {
    StringBuilder query = new StringBuilder("INSERT INTO " + tableName + " (");
    for (int j = 0; j < colNames.size(); j++) {
        query.append(colNames.get(j));
        if (j != (colNames.size() - 1)) {
            query.append(", ");
        } else {
            query.append(") VALUES(");
        }
    }
    for (int i = 0; i < colNames.size(); i++) {
        query.append("?");
        if (i != (colNames.size() - 1)) {
            query.append(", ");
        } else {
            query.append(")");
        }
    }
    stmt = ccd_db_connection.getConnection().prepareStatement(query.toString());
    for (int j = 0; j < colNames.size(); j++) {
        stmt.setObject(j + 1, data.get(j));
    }
    stmt.execute();
    stmt.close();
}

And here is the big Question(s) of mine.

Am I trying to reinvent the wheel?
Is this dynamic usage of queries bad practice and should I code specific methods for each and every table separately?
If this code is acceptable ... The insertion works fine except on tables where there is a primary key with auto incrementation. and i think thats cause setObject sets null while the query should only have the explicit values. Is there any way to bypass that.


texts: Getting the unique factors of a number recursively

texts:
I have written the below code to get the unique factors. Please offer suggestions for better results.

#Python program to print out all ways to multiply smaller integers
#that equal the original number, without repeating sets of factors

def print_factors_list(dividend, factorstring, predivisor):
"""This function takes a number and prints the factors"""

   divisor = dividend - 1
   #Looping to get the factors
   for i in range(divisor, 1, -1 ):

      if dividend % i != 0:
        continue

      if i > predivisor:
        continue
      #Get the quotient for the multipying number
      quotient = dividend / i

      if quotient <= i:
         if quotient <= predivisor:
            print factorstring + str(i) + "*" + str(quotient)
      print_factors_list(quotient, str(factorstring) + str(i) + "*", i)

#Check if the number is greater than 0
def print_factors(x):
# Check if the number is greater than 0
    if (x < 0):
        print "Enter a positive integer"
    #Check if the number is 0
    elif (x == 0):
        print "Enter a positive integer"
    #Go to the function print_factors_list for further evaluation
    else:
    #Print the default factors(the number itself and 1)
       print str(x) + "*" + str(1)
       print_factors_list(x, "", x )

#Take input from the user
num = int(input("Enter a number: "))
#Call the function with the number given by the user
print_factors(num)


texts: Iteration over "zipped" tuples (for_each_in_tuples)

texts:
I want to implement for_each_in_tuples that takes a functor and one or more tuples of the same size and applies this functor to i'th elements of each tuple for i = 0, ..., size - 1.

Example:

#include <iostream>
#include <tuple>

std::tuple t1(1, 2.2, false);
std::tuple t2(3.3, 'a', 888);

std::cout << std::boolalpha;
for_each_in_tuples(
    [](auto a1, auto a2)
    {
        std::cout << a1 << ' ' << a2 << '\n';
    }, t1, t2);

// Outputs:
// 1 3.3
// 2.2 a
// false 888

Implementation:

#include <cstddef>
#include <tuple>
#include <type_traits>

namespace impl
{
template<typename T, typename... Ts>
struct First { using Type = T; };

template<typename... Ts>
using First_t = typename First<Ts...>::Type;

template<auto value, auto... values>
inline constexpr auto all_same = (... && (value == values));

template<class Tuple>
inline constexpr auto tuple_size = std::tuple_size_v<std::remove_reference_t<Tuple>>;

template<std::size_t index = 0, class Function, class... Tuples>
constexpr void for_each_in_tuples(Function func, Tuples&&... tuples)
{
    constexpr auto size = tuple_size<First_t<Tuples...>>;

    func(std::get<index>(std::forward<Tuples>(tuples))...);
    if constexpr (index + 1 < size)
        for_each_in_tuples<index + 1>(func, std::forward<Tuples>(tuples)...);
}
}

template<class Function, class... Tuples>
constexpr void for_each_in_tuples(Function func, Tuples&&... tuples)
{
    static_assert(sizeof...(Tuples) > 0);
    static_assert(impl::all_same<impl::tuple_size<Tuples>...>);

    impl::for_each_in_tuples(func, std::forward<Tuples>(tuples)...);
}

At Compiler explorer: https://godbolt.org/g/cYknQT

Main questions:

Is this implementation correct and can it be simplified?
Which name is better, for_each_in_tuple or for_each_in_tuples (or ...)?