texts: Entity Framework with two databases (with UoW, Repository and Service Layer)

texts:
I have two databases: one for a warehouse, second for the office (The db design is out of the scope of this question). There are MANY cross-database funtions. One of those functions is IsPurchaseOrderClosed. I need data from TWO databases to determine this.

I was trying to build a DAL using UnitOfWork and Repository pattern (I always created UoW and Repository classes and interfaces. I knew DbContext already implements both patterns.. but I wanted to abstract EF layer). Anyway.. in this case, I decided to remove both elements and stick with DbContext and Service layer.

Here's my solution:

public class WarehouseContext : DbContext
{
    public WarehouseContext()
        : base("name=WarehouseContext")
    {
        this.Configuration.LazyLoadingEnabled = false;
    }

    public virtual DbSet<PurchaseOrder> PurchaseOrders { get; set; }
    public virtual DbSet<Inventory> Inventories { get; set; }
    public virtual DbSet<Orders> Orders { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        Database.SetInitializer<WarehouseContext>(null);
        base.OnModelCreating(modelBuilder);
    }
}

public class OfficeContext : DbContext
{
    public OfficeContext()
        : base("name=OfficeContext")
    {
        this.Configuration.LazyLoadingEnabled = false;
    }

    public virtual DbSet<Invoice> Invoices { get; set; }
    public virtual DbSet<Supplier> Suppliers { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        Database.SetInitializer<OfficeContext>(null);
        base.OnModelCreating(modelBuilder);
    }
}

public class ContextFactory : IContextFactory
{
    public WarehouseContext CreateWarehouseContext()
    {
        return new WarehouseContext();
    }

    public OfficeContext CreateOfficeContext()
    {
        return new OfficeContext();
    }
}

public class PurchaseOrderService
{
    IContextFactory ContextFactory { get; set; }

    public PurchaseOrderService(IContextFactory contextFactory)
    {
        ContextFactory = contextFactory;
    }

    //Service method, that interact with two databases:
    public bool IsPurchaseOrderClosed(int poId)
    {
        bool toReturn = false;

        using(var WarehouseContext = ContextFactory.CreateWarehouseContext())
        {
            PurchaseOrder purchaseOrder = WarehouseContext.PurchaseOrders.Find(poId);

            if (!purchaseOrder.IsClosed)
            {
                using(var OfficeContext = ContextFactory.CreateOfficeContext())
                {
                    int invoiceId = purchaseOrder.InvoiceId;

                    Invoice invoice = OfficeContext.Invoices.Find(invoiceId);

                    if (invoice.WasSent)
                    {
                        toReturn = true;
                    }
                }
            }
            else
            {
                toReturn = true;
            }
        }
        return toReturn;
    }
}

I have two questions:

Is this solution good? (By good I mean, does it meet every good-practice advice, SOLID principles etc)
In IsPurchaseOrderClosed method I get tables using OfficeContext.Set<Invoice>().Find(invoiceId); to get particular Invoice object from the database. Isn't it too.. complex/not readable? I was thinking how can I make it more simple? Should I create some kinda generic Service, with all basic/CRUD methods?
I have also third question: Currently ContextFactory is the part of .Data subproject (where my Contexts and Entities resides). Do you think it should be in .Business layer, which is the Service Layer (I prefer using Business or Logic words - because many people confuse it with WCF or Windows Service)?


texts: Given time intervals, find the minimum number of conference rooms required

texts:
The task is taken from LeetCode

  Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), find the minimum number of
  conference rooms required.

  Example 1:

Input: [[0, 30],[5, 10],[15, 20]]
Output: 2

  Example 2:

Input: [[7,10],[2,4]]
Output: 1

  NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.

My solution

/**
 * @param {number[][]} intervals
 * @return {number}
 */
var minMeetingRooms = function(intervals) {
  if (intervals.length <= 1) { return intervals.length; }

  const startTimes = [];
  const endTimes = [];
  intervals.forEach(x => {
    startTimes.push(x[0]);
    endTimes.push(x[1]);
  });
  startTimes.sort((a, b) => a - b);
  endTimes.sort((a, b) => a - b);

  let startPointer = 0;
  let endPointer = 0;
  let rooms = 0;
  while(startPointer < intervals.length) {
    if (startTimes[startPointer++] >= endTimes[endPointer]) {
      ++endPointer;
    } else {
      ++rooms
    }
  }
  return rooms;
};


texts: Find Start/Stop Indices Where Array Is True

texts:
If I have a list that contains True and False values, how can I find the start and stop indices of where there are blocks of True values?

x = [True, False, False, True, True, True, False, True, False, False, False, True, True, False, True]

The output that I am looking for is:

[[0,  0],
 [3,  5],
 [7,  7],
 [11, 12],
 [14, 14]
]

Here, the value in the first column is the start index and the value in the second column is the stop index.

One solution that I have is:

start = []
stop = []
if y[0]:
    start.append(0)
for i in range(len(y)):
    if y[i] and not y[i-1]:
        start.append(i)
    if i > 0 and (not y[i] and y[i-1]):
        stop.append(i-1)
if y[len(y)-1]:
    stop.append(len(y)-1)

print(list(map(list, zip(start, stop))))


texts:
I don't work much in Word VBA so I approached this similar to how I'd approach it in excel, which may not have been optimal. I also didn't see any places for errors to be handled.

This takes a Word document that has a list of URLs (pointing to .jpg), takes the URLs, places them as images on another sheet and then scales them to as large as they can get on an 8.5x11 while maintaining aspect ratio.

Option Explicit

Public Sub URLToImage()
    Application.ScreenUpdating = False
    Dim sourceDocument As Document
    Set sourceDocument = ThisDocument
    Dim imageURLs() As String
    imageURLs = GetURLArray(sourceDocument)
    Dim targetDocument As Document
    Set targetDocument = Documents.Add
    PrintImages imageURLs, targetDocument
    ResizeImages targetDocument
    Application.ScreenUpdating = True
End Sub

Private Function GetURLArray(ByVal sourceDocument As Document) As String()
    Dim imageURLs() As String
    ReDim imageURLs(1 To 2)
    Dim imageURL As String
    Dim beginCharacter As Long
    Dim endCharacter As Long
    Dim i As Long
    Dim j As Long
    j = 1
    For i = LBound(imageURLs) To sourceDocument.Paragraphs.Count
        imageURL = sourceDocument.Paragraphs(i).Range.Text
        beginCharacter = InStr(1, imageURL, "http", vbTextCompare)
        endCharacter = InStr(1, imageURL, "jpg")
        If beginCharacter > 0 And endCharacter > 0 Then
            imageURL = Mid(imageURL, beginCharacter, endCharacter + 3 - beginCharacter)
            ReDim Preserve imageURLs(1 To j)
            imageURLs(j) = imageURL
            j = j + 1
        End If
    Next
    GetURLArray = imageURLs
End Function

Private Sub PrintImages(ByRef imageURLs() As String, ByVal targetDocument As Document)
    Dim imageURL As String
    Dim i As Long
    With targetDocument
        For i = LBound(imageURLs) To UBound(imageURLs)
            imageURL = imageURLs(i)
            With Dialogs(wdDialogInsertPicture)
                .Name = imageURL
                .Execute
            End With
        Next
    End With
End Sub

Private Sub ResizeImages(ByVal targetDocument As Document)
    '72 points per inch
    Const EIGHT_AND_HALF_INCHES As Long = 72 * 8 + 72 / 2
    Const NO_MARGIN As Long = 0
    Dim i As Long
    With targetDocument
        .PageSetup.LeftMargin = NO_MARGIN
        .PageSetup.RightMargin = NO_MARGIN
        .PageSetup.TopMargin = NO_MARGIN
        .PageSetup.BottomMargin = NO_MARGIN
        For i = .InlineShapes.Count To 2 Step -1
            '.InlineShapes(i).Range.InsertBreak Type:=7
            .InlineShapes(i).Width = EIGHT_AND_HALF_INCHES
        Next
        .InlineShapes(1).Width = EIGHT_AND_HALF_INCHES
    End With
End Sub


texts: Bucketizing time (e.g., 4 min => 0-5 min)

texts:
Specification:

Given a string (e.g., the content of an article), print the estimated reading time by bucketizing time into increasingly large chunks in the form "5-10 min" or "48 min-2 hr".

Notes:

Distribution of time into buckets is arbitrary, to make it "look nice" for the default 5-minute time chunks. This is okay.

60 minutes exactly is special-cased, so that it should be "30-60 min" instead of "30 min-1 hr".

The "real" application of this code is inside a plugin for something else; rather than printing verbose information like in the code below, it actually returns $time_label.

I don't normally work in PHP, so any "idiomatic" feedback is also welcome.

Sample Input:
print_reading_time("This is a test.");

print_reading_time(str_repeat("test ",   100));
print_reading_time(str_repeat("test ",  1000));
print_reading_time(str_repeat("test ", 10000));
print_reading_time(str_repeat("test ", 20000));

print_reading_time(str_repeat("test ", 10000), 8);

Sample Output:

estimated reading time: 0 min (0-5 min), based on 4 words at 180 WPM
estimated reading time: 1 min (0-5 min), based on 100 words at 180 WPM
estimated reading time: 6 min (5-10 min), based on 1000 words at 180 WPM
estimated reading time: 56 min (30-60 min), based on 10000 words at 180 WPM
estimated reading time: 111 min (2 hr), based on 20000 words at 180 WPM
estimated reading time: 56 min (48 min-2 hr), based on 10000 words at 180 WPM

Original:
<?php

function print_reading_time($content, $minimum_time_bucket = 5 /* minutes */) {
  $wpm = 180; // arbitrary value, based on adult averages
  $word_count = str_word_count($content);
  $minutes = round($word_count / $wpm);
  $time_label = minutes_to_time_label($minutes, $minimum_time_bucket);

  print("estimated reading time: $minutes min ($time_label), " .
      "based on $word_count words at $wpm WPM");
}

function minutes_to_time_label($minutes, $minimum_time_bucket) {
  // Buckets: <5, 5-10, 10-15, 15-30, 30-60, then 1-hour increments,
  // for the default 5-minute minimum bucket size.
  $buckets = array(0, 1, 2, 3, 6, 12);

  for ($i = 0; $i < count($buckets) - 1; $i++) {
    $lowerBound = $buckets[$i] * $minimum_time_bucket;
    $upperBound = $buckets[$i+1] * $minimum_time_bucket;

    if ($lowerBound <= $minutes && $minutes < $upperBound) {
      $lowerOptions = array();
      // If the amounts are both in minutes or both in hours, don't display
      // the units for the first amount (ie, show "5-10 min", not "5 min-10 min".
      if (($lowerBound <= 60 && $upperBound <= 60) || ($lowerBound > 60 && $upperBound > 60)) {
        $lowerOptions["no_units"] = true;
      }
      return minutes_to_time_str($lowerBound, $lowerOptions) . "-"
          . minutes_to_time_str($upperBound);
    }
  }

  // If we get to here, then the time is longer than our largest explicit bucket.
  // Divide everything beyond into hour-long buckets.
  return minutes_to_time_str($minutes, array("treat_60_min_as_an_hour" => true));
}

function minutes_to_time_str($minutes, $options = array()) {
  $options = array_merge(default_options(), $options);
  $amount = $minutes;
  $units = "min";

  if ($minutes > 60 || ($minutes === 60 && $options["treat_60_min_as_an_hour"])) {
    $amount = round($minutes / 60);
    $units = "hr";
  }

  return $amount . ($options["no_units"] ? "" : " $units");
}

function default_options() {
  return array(
    "no_units" => false,
    "treat_60_min_as_an_hour" => false,
  );
}

?>


texts: Unbalanced Binary Search Tree insertion and search with random and sorted values

texts:
I have created this unbalanced binary search tree in C. Can anyone say this is a true approach or not? I have two scenarios for insertion and search: in the first scenario I am inserting 10000 random values to tree, and in the second scenario I am inserting 10000 sorted values from 1 to 10000.

Am I on the right track?

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

struct BSTNode {
    int data;
    struct BSTNode *BSTLeft;
    struct BSTNode *BSTRight;
};

typedef struct BSTNode node;

node *rootNode= NULL;

void BSTInsert(int i, node **n) {
    if (*n == NULL) {
        (*n) = (node*)malloc(sizeof(node));
        (*n)->BSTLeft = NULL;
        (*n)->BSTRight = NULL;
        (*n)->data = i;
    }
    else if (i > (*n)->data)
        BSTInsert(i, &((*n)->BSTRight));
    else
        BSTInsert(i, &((*n)->BSTLeft));
}

void BSTSearch(int i, node **n) {
    if (*n == NULL)
        printf("\nValue does not exist in tree!");
    else if((*n)->data == i)
       return ;
    else if(i > (*n)->data)
        BSTSearch(i, &((*n)->BSTRight));
    else
        BSTSearch(i, &((*n)->BSTLeft));
}

void test_scenario1() {
    node *rootNode = NULL;
    const int SIZE = 10000;
    int *a = malloc(sizeof (int)*SIZE);
    clock_t start, end;
    for (int i = 1; i < SIZE; i++)
    {
        srand(time(NULL));
        a[i] = rand() % 1000;
    }
    printf("Inserting values to BST with %d random nodes...\n", SIZE);
    start = clock();
    for (int i = 0; i < SIZE; i++) {
    BSTInsert(a[i], &rootNode);
    }
    end = clock();
    printf("Done. Took %.8f seconds\n\n", (double) (end - start) / CLOCKS_PER_SEC);

// Search in BST with random Values

    printf("Searching random values in BST...");
    start = clock();
    for (int i = 0; i < SIZE; i++) {
    BSTSearch(a[i], &rootNode);
    }
    end = clock();
    printf("\nDone. Took %.8f seconds\n", (double) (end - start) / CLOCKS_PER_SEC);
    free(a);
}

void test_scenario2(){
    node *rootNode = NULL;
    const int SIZE = 10000;
    clock_t start, end;
    int num;
    printf("\nInserting values to BST with %d sorted nodes...\n", SIZE);
    start = clock();
    for (num=1;num<=10000;num++){
    BSTInsert(num, &rootNode);
    }
    end = clock();
    printf("Done. Took %.8f seconds\n\n", (double) (end - start) / CLOCKS_PER_SEC);

// Search in BST with sorted Values

    printf("Searching sorted values in BST...");
    start = clock();
    for (num=1;num<=10000;num++)
    BSTSearch(num, &rootNode);
    end = clock();
    printf("\nDone. Took %.8f seconds\n\n", (double) (end - start) / CLOCKS_PER_SEC);
}
// Main function for these three scenarios.
int main(int argc, char ** argv)
{
    test_scenario1();
    test_scenario2();
}


texts: Getting the index of a character within the alphabet

texts:
I've made this function to map alphabetic coordinates to their corresponding ordinal number.

var exec = document.querySelector('#exec');

// Maps alphabetic characters to their index
//   within the alphabet.
// --------------------------------------------
// @param { string || array } chars - String
//  consisting of a single alphabetic character
//  or an array which elements are single
//  alphabetic characters.
// @throws Error in case of invalid
//  parameter ( == not a single alphabetic
//  character ).
// --------------------------------------------
// @returns { array } with numbers. The indexes
//  of the characters within the alphabet.
//
// ------- Usage examples ----------
// getIndexInAlphabet('i')); // Result : [9]
// getIndexInAlphabet(['a', 'B', 'c'])[1] // 2
// getIndexInAlphabet(['a', 'G', 'z'])); // [1, 7, 26]

function getIndexInAlphabet( chars ) {
  var alphabet = [ 'a', 'b', 'c', 'd', 'e',
                   'f', 'g', 'h', 'i', 'j',
                   'k', 'l', 'm', 'n', 'o',
                   'p', 'q', 'r', 's', 't',
                   'u', 'v', 'w', 'x', 'y',
                   'z' ];

  if (!Array.isArray(chars)) {
    if (typeof chars === 'string') {
      let tmp = [];
      tmp.push(chars);

      chars = tmp;
    } else {
      throw new Error(
        'Parameter invalid because not of type string.');
    }
  }

  chars.forEach(function(item, i) {
    if (typeof item !== 'string') {
      throw new Error('Element ' + i +
                      ' invalid because not of type string.');
    }
  });

  return chars.map(function(char, i) {
    var ret = alphabet.indexOf(char.toLowerCase()) + 1;

    if (ret === 0) {
      throw new Error('Element ' + i + ' invalid because' +
                      ' not an alphabetic character.');
    }

    return ret;
  });
}

// -- From here on : Just testing ...
exec.addEventListener('click', function() {
  try {
    console.log(getIndexInAlphabet(['a', 'B', 'c'])[1])
    console.log(getIndexInAlphabet('i'));
    console.log(getIndexInAlphabet(['a', 'G', 'z']));

    var charStr = ['a', 'b', 'c', 'd', 'e', 'f'];
    var indexes = getIndexInAlphabet(charStr);
    var charMap = {};

    charStr.forEach(function(char, i) {
      charMap[char] = indexes[i];
    });

    console.log(charMap.f);
  } catch (e) {
    console.log(e.message);
    console.log(e.stack);
  }
});
.wrap {
  width: 800px;
  margin: 50px auto;
}

    Exec!


texts:
I am looking for advice if the below code is a good idea or not. If not, why? I am building a website which allows a user to purchase items. The user account and cart items will be stored in Session. My approach is to create a singleton class that will manage all the sessions. Is this approach good or bad?

public class SessionFactory
    {
        private static SessionFactory instance;
        private String _UserName;
        private long _CartId { get; set; }

        public Cart UserCart {

            get {

                if (HttpContext.Current.Session["Cart"] != null) {

                    return HttpContext.Current.Session["Cart"] as Cart;
                }

                return new Cart();
            }
            set {

                HttpContext.Current.Session["Cart"] = value;

            }
        }

        private SessionFactory(String username, long cartId)
        {
            this._UserName = username;
            this._CartId = cartId;
            // build Session objects here

        }

        public long CartId{

            get {

                return _CartId;
            }

        }

        public static SessionFactory Instance {

            get {

                if (instance == null) {

                    throw new Exception("Session was not created");
                }
                return instance;
            }

        }

        public static void Create(String userName, long cartId) {

            if (instance != null) {

                throw new Exception("Session Instance already created.");
            }

            instance = new SessionFactory(userName, cartId);
        }
    }


texts:
This code implements a binary tree for integers. How can I improve it?

#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
///////////////////////////////
struct node{
    int data;
    struct node *left;
    struct node *right;
};
///////////////////////////////
struct node *newnode(int value)
{
    struct node *temp=(struct node *)malloc(sizeof(struct node));
    temp->data=value;
    temp->left=NULL;
    temp->right=NULL;
    return (temp);
}

void inorder_rec(struct node *temp)
{
    if(temp->left!=NULL)
    inorder_rec(temp->left);

    printf("%d",temp->data);

    if(temp->right!=NULL)
    inorder_rec(temp->right);
}

void preorder_rec(struct node *temp)
{
    printf("%d",temp->data);
    if(temp->left!=NULL)
    preorder_rec(temp->left);
    if(temp->right!=NULL)
    preorder_rec(temp->right);
}

void postorder_rec(struct node *temp)
{
    if(temp->left!=NULL)
    postorder_rec(temp->left);
    if(temp->right!=NULL)
    postorder_rec(temp->right);
    printf("%d",temp->data);
}
////////////////////////////////
int main()
{
    int option;
    option=1;
    struct node *root=newnode(1);
    root->left=newnode(2);
    root->right=newnode(3);
    root->left->left=newnode(4);
    root->left->right=newnode(5);
    root->right->left=newnode(6);
    root->right->right=newnode(7);
    printf("Press:\n1 for inorder\n2 for preorder\n3 for postorder\n0         toQUIT!");
    while(option)
    {
        printf("\nenter your option=");
        scanf("%d",&option);
        switch(option)
        {
            case 1:
                inorder_rec(root);
                break;
            case 2:
                preorder_rec(root);
                break;
            case 3:
                postorder_rec(root);
                break;
        /*  case 4:
                inorder_non_rec(root);
                break;
            case 5:
                preorder_non_rec(root);
                break;
            case 6:
                postorder_non_rec(root);
                break;*/

        }

    }
}


texts:
If I have an array:

var names = ['John', 'Jim', 'Joe'];

and I want to create a new array from names which afterwards will look like:

newNames = ['John John', 'Jim Jim', 'Joe Joe']

What I came up with is the following:

var newNames = [];
var arr = null;
var loop = 0;

$.each(names, function (i, item) {
  arr = [];
  loop = 2;
  while (loop--) {
    arr.push(item);
  }
  newNames.push(arr.join(' '));
});

Seems like there should be a shorter, easier way to do this. As you can see we can repeat the names with a space n times. I'm experimenting with different ideas/concepts, having fun.


texts:
I made this resource queue in Love2D.

function GameState:queue(file, arg)
    self.res.loaded = self.res.loaded + 1;
    self.res.queue[self.res.loaded] = {f = file, t = game.getResourceType(file), id = self.res.loaded, s = arg};
    game.log("Resource Queued: "..file);
    return {f = self.res.loaded, t = game.getResourceType(file), id = self.res.loaded, s = arg};
end

function GameState:loadQueue(loader, post)
    self.post = post or function() self.state = self.prevState end;

    game.log("Loading Resource Queue...");

    queueThread = love.thread.newThread("queue.lua");
    queueChannel = love.thread.getChannel("queue");

    local fonts = {};

    for k, v in pairs(self.res.queue) do
        if (not v or not v.f or not v.t) then goto continue end;
        if (v.t ~= self.RESOURCE_FONT) then
            queueChannel:push(v);
        else
            fonts[k] = v;
        end
        ::continue::
    end

    for k, v in pairs(fonts) do
        self.res.fnt[k] = love.graphics.newFont(v.f, v.s);
        print("Loaded Resource: "..v.f);
    end

    queueChannel:push(table.size(self.res.queue)-table.size(fonts));

    if (table.size(self.res.queue)-table.size(fonts) > 0) then
        queueThread:start();
    else
        queueChannel = nil;
        queueThread = nil;
        return;
    end

    self.state = self.STATE_LOADING
end

The thread:

require "love.image"
require "love.audio"
require "love.sound"
require "love.timer"

queue = {};
img = {};
snd = {};
local queueChannel = love.thread.getChannel("queue");

local pop = queueChannel:pop();

while (type(pop) ~= "number" and pop) do
    queue[pop.id] = pop;
    pop = queueChannel:pop();
end

for k, v in pairs(queue) do
    if (not v or not v.f or not v.t) then print("Resource Load Failed!"); goto continue; end;

    if (v.t == 0) then -- image
        img[k] = love.image.newImageData(v.f);
        queueChannel:supply({data = img[k], t = 0, id = k, s = v.s});
    end
    if (v.t == 1) then -- sound
        snd[k] = love.audio.newSource(v.f, "static");
        queueChannel:supply({data = snd[k], t = 1, id = k, s = v.s});
    end
    ::continue::
    queue[k] = nil;
    print("Loaded Resource: "..v.f);
    love.timer.sleep(0.01);
end

queueChannel:clear();
queueChannel:push(true);

return;

Handling while loading resources:

if (self.state == self.STATE_LOADING) then
    local e = queueThread:getError();
    if (e ~= nil) then
        print("Thread: "..e)
    end

    local r = queueChannel:peek();
    if (type(r) == "table" and r and r.data and r.t) then
        if (r.t == self.RESOURCE_IMAGE) then
            if (r.s) then
                love.graphics.setDefaultFilter(r.s, r.s);
            end
            self.res.img[r.id] = love.graphics.newImage(r.data);
        end
        if (r.t == self.RESOURCE_SOUND) then
            self.res.snd[r.id] = r.data;
        end
        queueChannel:pop();
    end

    if (queueChannel:peek() == true and type(queueChannel:peek()) == "boolean") then
        self.post();
        game.log("Finished Loading Resources.");
    end
end

If there's any bad habits, or anything that could be improved, please let me know.


texts: Time of day based timer - run function at certain time, daily

texts:
I need to call a function exactly at certain hour, daily, my programs runs 24/7.

I wrote the following timer mechanism, which generally works that way:

Calculate time until hour and generate timer with that interval.
When timer elapse, call timer event and generate another 24h timer.
Go back to step 2.

private static void InitTimeBasedTimer(TimeSpan timeToRun, Action funcToRun)
{
    TimeSpan interval = timeToRun.Subtract(DateTime.Now.TimeOfDay);
    double intervalMillis = interval.TotalMilliseconds;
    if (interval.TotalMilliseconds < 0)
    {
        intervalMillis = (new TimeSpan(24, 0, 0)).Add(interval).TotalMilliseconds;
    }
    Timer timer = new Timer(intervalMillis);
    timer.AutoReset = false;
    timer.Elapsed += (sender, e) => TimeBasedCallback(timeToRun, funcToRun);
    timer.Start();
}

public static void TimeBasedCallback(TimeSpan timeToRun, Action funcToRun)
{
    funcToRun();
    TimeSpan interval = timeToRun.Subtract(DateTime.Now.TimeOfDay); //24 h
    double intervalMillis = interval.TotalMilliseconds;
    if (intervalMillis < 0)
    {
        intervalMillis = (new TimeSpan(24, 0, 0)).Add(interval).TotalMilliseconds;
    }
    Timer timer = new Timer(intervalMillis);
    timer.AutoReset = false;
    timer.Elapsed += (sender, e) => TimeBasedCallback(timeToRun, funcToRun);
    timer.Start();
}

EDIT:
There are several functions that each writes to a DB every day in different hours. Can't afford task scheduler / process for each function. Quartz.NET seems a bit overkill for such a simple task.


texts: Yaw (Z-rotation) angle linear interpolation without quaternions

texts:
I need to write a function performing linear interpolating between two Euler angles in 2D, perfectly without the use of quaternions as conversion seems to be an overkill for such a simple task.

Here's what I came up with:

// Calculate difference on a wrapped number line
function difference(a, b, width) {
  const d = a - b;
  const ad0 = Math.abs(d);
  const ad1 = width - ad0;

  if (ad1 < ad0)
    return -Math.sign(d) * ad1;

  return d;
}

Number.prototype.mod = function(n) {
  return ((this % n) + n) % n;
};

const fullAngle = 2 * Math.PI;

// Linear interpolation
function slerp(a, b, t) {
  a = a.mod(fullAngle);
  b = b.mod(fullAngle);

  return (a + difference(b, a, fullAngle) * t).mod(fullAngle);
}

function toRadians(a) {
  return a * Math.PI / 180.0;
}

function toDegrees(a) {
  return a * 180.0 / Math.PI;
}

document.write(toDegrees(slerp(toRadians(20), toRadians(350), .25)));

The expected output is an angle linearly interpolated from one angle to another using specified t value.

In the example above the output is correct:
The smallest angle difference between 350° and 20° is 30° (-30° with a sign).

20° + (-30°) * .25 = 20° - 7.5° = 12.5°

Is the code above correct?
Could it be simplified?


texts: JavaScript Tic Tac Toe - functional but could be DRYer

texts:
I've been working on a simple Tic Tac Toe game in JavaScript.  It runs the way it should, but the Board.checkWin function (check every possible winning combo) could be better, it is very repetitive in its current state.  Any ideas?

Here is my Cell class:

var Cell = function() {
this.value = "|_|";
};

Cell.prototype.setState = function(arg) {
    this.value = arg;
};

Cell.prototype.playable = function() {
    if (this.value == "|_|") {
        return true;
    } else {
        return false;
    }
};

Cell.prototype.render = function() {
    return this.value;
};

Here is my Board class:

var Board = function() {
    this.cells = [];
    this.currentPlayers = ["|X|","|O|","|X|","|O|","|X|","|O|","|X|", "|O|", "|X|"];
    this.winner = this.currentPlayers[1];
};

Board.prototype.startGame = function() {
    for (i = 0; i < 9; i++) {
        this.cells.push(new Cell);
    }
    return this.render();
};

Board.prototype.makePlay = function(position) {
    if (this.checkWin() == false) {

    if (position < this.cells.length) {
        var cell = this.cells[position];
        var currentPlayer = this.currentPlayers.shift();

        if (cell.playable() == true) {
        cell.setState(currentPlayer);
        }
    }
    return this.render();
    }
};

Board.prototype.checkWin = function() {

for(var i = 0; i < this.cells.length; i++)
    if (this.cells[0].value == "|X|" && this.cells[1].value == "|X|" && this.cells[2].value == "|X|"    ||
        this.cells[0].value == "|O|" && this.cells[1].value == "|O|" && this.cells[2].value == "|O|" ||

        this.cells[3].value == "|X|" && this.cells[4].value == "|X|" && this.cells[5].value == "|X|" ||
        this.cells[3].value == "|O|" && this.cells[4].value == "|O|" && this.cells[5].value == "|O|" ||

        this.cells[6].value == "|X|" && this.cells[7].value == "|X|" && this.cells[8].value == "|X|" ||
        this.cells[6].value == "|O|" && this.cells[7].value == "|O|" && this.cells[8].value == "|O|" ||

        this.cells[0].value == "|X|" && this.cells[3].value == "|X|" && this.cells[6].value == "|X|" ||
        this.cells[0].value == "|O|" && this.cells[3].value == "|O|" && this.cells[6].value == "|O|" ||

        this.cells[1].value == "|X|" && this.cells[4].value == "|X|" && this.cells[7].value == "|X|" ||
        this.cells[1].value == "|O|" && this.cells[4].value == "|O|" && this.cells[7].value == "|O|" ||

        this.cells[2].value == "|X|" && this.cells[6].value == "|X|" && this.cells[8].value == "|X|" ||
        this.cells[2].value == "|O|" && this.cells[6].value == "|O|" && this.cells[8].value == "|O|" ||

        this.cells[0].value == "|X|" && this.cells[4].value == "|X|" && this.cells[8].value == "|X|" ||
        this.cells[0].value == "|O|" && this.cells[4].value == "|O|" && this.cells[8].value == "|O|" ||

        this.cells[6].value == "|X|" && this.cells[4].value == "|X|" && this.cells[2].value == "|X|" ||
        this.cells[6].value == "|O|" && this.cells[4].value == "|O|" && this.cells[2].value == "|O|")

        {
            return true;
        } else {
            return false;
    }
};

Board.prototype.render = function() {
    var boardArray = [];
    for (var i = 0; i < this.cells.length; i++) {
        boardArray.push(this.cells[i].value);
    }
    for (var j = 0; j < boardArray.length; j++) {
        var boardString = "TIC TAC TOE " + boardArray[0] + boardArray[1] + boardArray[2] + "\n ";
        boardString += " PICK A BOX " + boardArray[3] + boardArray[4] + boardArray[5] + " \n ";
        boardString += "   0 THRU 8 " + boardArray[6] + boardArray[7] + boardArray[8];
    }

    if (this.checkWin() == true) {
        return boardString + "\n   WE HAVE A WINNER!";
    } else {
    return boardString;
    }
};


texts: Checking a MySQL connection and refreshing it

texts:
I am using the following function to check if a MySQL connection is in an invalid state or if it has reached a predefined maximum operation count:

 /// <summary>
 /// Holds the amount of operations for the currently mysql-connection open
 /// </summary>
 private int connectionUsageCount = 0;

 /// <summary>
 /// The maximum usage count of the connection until it has to be refreshed
 /// </summary>
 private const int MAX_CONNECTION_USAGE_COUNT = 100;

 /// <summary>
 /// Holds the cached MySql Connection to the databse server.
 /// </summary>
 private MySqlConnection mySqlConnection;

 /// <summary>
 /// Checks the status of the sql connection and refreshes it when necessary.
 /// </summary>
 private void CheckSqlConnection()
 {
     // Check if the connection is in an invalid state or
     // the connection has to be refreshed and refresh it
     // when necessary
     if (mySqlConnection == null
         || mySqlConnection.State == System.Data.ConnectionState.Broken
         || mySqlConnection.State == System.Data.ConnectionState.Closed
         || connectionUsageCount >= MAX_CONNECTION_USAGE_COUNT)
     {
         // If the connection was already initialized, close and dispose it
         if (mySqlConnection != null)
         {
             // If connection is open, close it
             if (mySqlConnection.State != System.Data.ConnectionState.Broken
                 && mySqlConnection.State != System.Data.ConnectionState.Closed)
             {
                 mySqlConnection.Close();
             }

             mySqlConnection.Dispose();
             mySqlConnection = null;
         }

         // Create new connection
         mySqlConnection = new MySqlConnection(this.ConnectionString.ToString());
     }
 }

Can anyone review this piece of code and tell provide me with some feedback? I am not sure if I have covered all possibilities that would cause an error when using the mySqlConnection.


texts:
Here is my JavaScript function to manipulate the hash:

var hash = {
    get: function(key){
        var lh = location.hash;

        if(lh.charAt(0) === "#"){
            lh = lh.slice(1);
        }

        var pairs = lh.split("&");
        var obj = [];
        for(var i = 0; i < pairs.length; i++){
            var pair = pairs[i];
            if(pair.indexOf("=") > 0){
                pair = pair.split("=");
                obj[pair[0]] = pair[1];
            }else{
                obj[pair] = 1;
            }
        }
        return typeof key !== 'undefined' ? obj[key] : obj;
    },
    set: function(key, value, cb){
        var newHash = this.removeKey(key);

        if(newHash.length > 1){
            newHash += "&";
        }
        newHash += key + (typeof value != 'undefined' ? "="+value : "");
        var url = location.href.split("#")[0] + (newHash !== "#" ? newHash : "");

        history.pushState(undefined, document.title, url);
        if(cb){
            cb();
        }
    },
    del: function(key){
        var newHash = this.removeKey(key);
        var url = location.href.split("#")[0] + (newHash !== "#" ? newHash : "");

        history.pushState(undefined, document.title, url);
    },
    removeKey: function(key){
        var string = location.hash;

        if(string.charAt(0) !== "#"){
            string = "#" + string;
        }

        var regex = new RegExp("[#&]"+key+"(=[^&]+|)", 'gi');
        string = string.replace(regex, "");

        if(string.charAt(0) === "&"){
            string = "#" + string.slice(1);
        }

        return string !== '' ? string : '#';
    }
};

I am trying to make it as light as possible.


texts: Python Automate the Boring Stuff Collatz exercise

texts:
I'm looking for some feedback on my code for the collatz function exercise in the Python book Automate the Boring Stuff. It works, but doesn't feel very elegant to me. Is there a better way to approach it? I'm trying to avoid just looking at someone else's solution so general advice would be preferred.

def collatz(number):
 if (number %2 ==0 ) :#even
     newNumber=number//2
     print(newNumber);
     if newNumber!=1:
         collatz(newNumber);
     else:
         return (newNumber)
 elif (number % 2 == 1) : #odd
     newNumber=3*number+1
     print (newNumber)
     collatz(newNumber)
     return newNumber;

#Input validation loop
while True:
    try:
        number = int(input("Enter number:"))
    except ValueError:
        print("Enter a valid integer")
        continue
    else:
        if number < 1:
            print("enter a valid positive integer")
            continue
        break

collatz(number)


texts:
I need to intercept a URL and go outside the WebView if the URL contains MAPS or DOCUMENTS constants. I must also go outside if url does not contain the value of DOMAIN and LOGIN_SALES_FORCE.

This is working nice, but seems ugly for me. Any ideas?

if ([request.URL.absoluteString rangeOfString:MAPS      ].location != NSNotFound ||
    [request.URL.absoluteString rangeOfString:DOCUMENTS ].location != NSNotFound)
{
    NSURL *url = [NSURL URLWithString:request.URL.absoluteString];
    return [[UIApplication sharedApplication] openURL:url];
} else if ([request.URL.absoluteString rangeOfString:DOMINIO           ].location == NSNotFound &&
           [request.URL.absoluteString rangeOfString:LOGIN_SALES_FORCE ].location == NSNotFound) {
    NSURL *url = [NSURL URLWithString:request.URL.absoluteString];
    return [[UIApplication sharedApplication] openURL:url];
}


texts: Trying to map JSON to different classes in web API

texts:
I have a controller action that takes JSON bodies. I know, that the JSON is either of type A or B, where both classes are of interface IModel.

    [HttpPost]
    [Route("api/post/")]
    public IHttpActionResult MyPost([ModelBinder(typeof(MyModelBinder))]IModel viewModel)
    {
        doSomething(viewModel);
        return Ok("ok");
    }

In order to map the JSON, I created my own model binder, like this one

public class MyModelBinder : IModelBinder
{
    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
    {
        var content = actionContext.Request.Content;
        string json = content.ReadAsStringAsync().Result;

        try
        {
            var DTO = JsonConvert.DeserializeObject<A>(json);
            IModel viewModel = new A()
            {
                // mapping here
            };
            bindingContext.Model = viewModel;
            return true;
        }
        catch(Exception e)
        {

        }
        try
        {
            var DTO = JsonConvert.DeserializeObject<B>(json);
            IModel viewModel = new B()
            {
                // mapping here
            };
            bindingContext.Model = viewModel;
            return true;
        }
        catch (Exception e)
        {

        }
        return false;
    }
}

Edit: It doesn't work, because Newtonsoft Json can apparently always deserialize, so it never jumps out of the first try block. I was wondering, how to improve the code. Right now I have only 2 possible types (A and B), but in the near future I expect to get much more possible types...


texts: Convert String to Integer with default value

texts:
I want to convert a java.lang.String to a java.lang.Integer, assigning a default value of 0 if the String is not convertible. Here is what I came up with.  I would appreciate an assesment of this approach.

To be honest, it feels a little squirrely to me:

String strCorrectCounter = element.getAttribute("correct");
Integer iCorrectCounter = new Integer(0);
try {
    iCorrectCounter = new Integer(strCorrectCounter);
} catch (Exception ignore) { }


texts: Checking if command line input is an integer

texts:
The code below accepts 1 command line argument from the user. The expected input is an integer. Hence, the code checks if the input is purely an integer. Any feedback is appreciated.

atoi() does not provide error-checking, thus the idea is to verify the input before passing the input to atoi().

I considered using strtol(), but it looks way too complex for a simple task.

stoi() considers 1a as valid, which is not valid in my use case.

//abc   ->  Invalid
//1a    ->  Invalid
//a1    ->  Invalid
//1     ->  Valid

#include <iostream>
#include <cstdlib>
#include <string>
#include <cctype>

using namespace std;

int correctInput;
string userInputStr;

int main(int argc, char* argv[])
{
    userInputStr = argv[1];
    for ( int x = 0; x < userInputStr.length(); x++)
    {
        if ( isalpha(userInputStr[x]) )
        {
            cout << "invalid input." << endl;
            return 0;
        }

    }

    correctInput = atoi(userInputStr.c_str());

    cout << correctInput << endl;

}


texts:
The task: user-generated news feed:

User select what data type he wants to add

Provide record type required data

Record is published on text file in special format

Types of data:

News – text and city as input. Date is calculated during publishing.

Private ad – text and expiration date as input. Day left is calculated during publishing.

Your unique one with unique publish rules.

Expected result:
News -------------------------
Something happened
London, 03/01/2021 13.45
------------------------------

News -------------------------
Something other happened
Minsk, 24/01/2021 20.33
------------------------------

Private Ad ------------------
I want to sell a bike
Actual until: 01/03/2021, 21 days left
------------------------------

Joke of the day ------------
Did you hear about the claustrophobic astronaut?
He just needed a little space
Funny meter – three of ten
------------------------------

My code:
from datetime import datetime, date
from sys import exit

class Article:
    def __init__(self, title, text, line_width):
        self.title = title
        self.text = text
        self.line_width = line_width

    @staticmethod
    def publish_article(formatted_text):
        with open("all_news.txt", "a") as file:
            file.write(formatted_text)

class News(Article):
    def __init__(self, title, text, city, date, line_width):
        Article.__init__(self, title, text, line_width)
        self.city = city
        self.date = date

    def format_text(self):
        return f"{self.title}{(self.line_width - len(self.title)) * '-'}\n"\
               f"{self.text} \n"\
               f"{self.city}, {self.date.strftime('%d/%m/%Y %H:%M:%S')} \n"\
               f"{'-'*self.line_width}\n\n\n"

class Ad(Article):
    def __init__(self, title, text, end_date, line_width):
        Article.__init__(self, title, text, line_width)
        self.end_date = end_date

    def format_text(self):
        day, month, year = map(int, self.end_date.split('/'))
        days_left = (date(year, month, day) - date.today()).days
        return f"{self.title}{(self.line_width - len(self.title)) * '-'}\n"\
               f"{self.text} \n"\
               f"Actual until: {date(year, month, day).strftime('%d/%m/%Y')}, {days_left} days left \n"\
               f"{'-'*self.line_width}\n\n\n"

class PersonalNews(Article):
    def __init__(self, title, text, line_width):
        Article.__init__(self, title, text, line_width)

    def format_text(self):
        return f"{self.title}{(self.line_width - len(self.title)) * '-'}\n"\
               f"{self.text} \n"\
               f"{'-'*self.line_width}\n\n\n"

while True:
    user_input = input('Enter a number: '
                       '1 - Publish news;\n'
                       '2 - Publish ad; \n'
                       '3 - Publish personal news\n'
                       'q - Exit\n')
    if user_input == "1":
        new_news = News("News",
                        input('Print your text\n'),
                        input('Print city for the news\n'), datetime.now(), 30)
        new_news.publish_article(new_news.format_text())
    elif user_input == "2":
        new_news = Ad("Private Ad",
                      input("Input your text\n"),
                      input('Print endDate of ad in format DD/MM/YEAR\n'), 30)
        new_news.publish_article(new_news.format_text())
    elif user_input == "3":
        new_news = PersonalNews(input("Input your title\n"),
                                input("Input your text\n"), 30)
        new_news.publish_article(new_news.format_text())
    elif user_input == "q":
        exit(0)
    else:
        print("Incorrect input. Please enter a number (1, 2, 3) or 'q' for exit")


texts: C++ - algebraic expressions calculator by addition

texts:
I'm ultra new to programming. I basically know only IFs, loops, variables. This is first time I used functions in my code and I'm not sure if I understand them correctly.

Basically it is a calculator that requests two natural positive numbers on input, and outputs it's addition, subtraction, multiplication, division and exponentiation. The only rule is: you can use only addition when calculating these expressions. I'm ultra new to programming. I basically know only IFs, loops, variables. This is first time I usentiation. It does not yet support: using '0' as input, using negative numbers as input, using floating point numbers as input, indivisible numbers.

My question is: can you please take a look at my code and just tell me if I made any mistakes that literally burn your eyes? What should I fix? What is especially bad?

#include <iostream>
using namespace std;

int addition(int a, int b)
{
    return a + b;
}

int subtraction(int a, int b)
{
    return a + (-b);
}

int multiplication(int a, int b)
{
    int result = a;
    for (int i = 1; i < b; i++)
        result += a;
    return result;
}

int division(int a, int b)
{
    int counter = 0;
    if (a % b == 0) {
        do {
            a = subtraction(a, b);
            counter++;
        } while (a > 0);
        return counter;
    }
    else
        return false;
}

int exponentiation(int a, int b)
{
    int result = 1;
    for (int i = 1; i <= b; i++)
        result = multiplication(result, a);
    return result;
}

int main()
{
    int numberA, numberB;
    cout << "Insert two positive natural numbers: ";
    cin >> numberA >> numberB;
    cout << "\nAddition: " << addition(numberA, numberB) << '\n';
    cout << "Subtraction: " << subtraction(numberA, numberB) << '\n';
    cout << "Multiplication: " << multiplication(numberA, numberB) << '\n';
    cout << "Division: " << division(numberA, numberB) << '\n';
    cout << "Exponentiation: " << exponentiation(numberA, numberB) << '\n';
    return 0;
}


texts: Synchronization of remote files download

texts:
Preamble: it's a self-assigned and pure syntetic task to learn (and remember what I already knew) C# threads and synchronization and data structures.

The original question was here https://stackoverflow.com/questions/16458937/synchronization-of-remote-files-download

The short task explanation:

Let's say I have a dictionary <string, string> that represents a path (http) to a file by some key, ie:

foo => http://domain.tld/file1
bar => http://domain2.tld/file2

And I'd like to implement a class that will implement an interface with 2 methods:

String Rand();
String Get(String key);

The first method would pick the file randomly from all the available, and the Get would return a particular file, or to be precise - local path to a downloaded file.

The class should be thread-safe, so that if several threads request the same key with Get() or the Rand() picks the same item - then only one thread should actually download a file to a local drive, or the path should be retrieved immediately if a file has already been downloaded.

My proof of concept solution is:

class Downloader
{
    private readonly IDictionary<string, string> _map;
    private IDictionary<string, string> _storage = new Dictionary<string, string>();
    private ConcurrentDictionary<string, Task<string>> _progress = new ConcurrentDictionary<string,Task<string>>();

    public Downloader(IDictionary<string, string> map)
    {
        _map = map ?? new Dictionary<string, string>();
    }

    public string Get(string key)
    {
        if (_storage.ContainsKey(key))
        {
            return _storage[key];
        }

        Task<string> task;
        if (_progress.TryGetValue(key, out task))
        {
            return task.Result;
        }

        task = _retrieveFile(key);

        if (!_progress.TryAdd(key, task))
        {
            return Get(key);
        }

        task.Start();
        _storage[key] = task.Result;
        return task.Result;
    }

    private Task<string> _retrieveFile(string key)
    {
        string path;

        if (!_map.TryGetValue(key, out path))
        {
            throw new ArgumentException("The specified key wasn't found");
        }

        return new Task<string>(k =>
        {
            Console.WriteLine("Started retrieving {0}", k.ToString());
            System.Threading.Thread.Sleep(3000);
            Console.WriteLine("Finished retrieving {0}", k.ToString());
            return k.ToString() + " local path";
        }, path);
    }
}

The copy is at http://pastebin.com/LJnK7FB6

How could I make it better? Any particular problems with the code?

In the comments @I4V pointed out to some problems at https://stackoverflow.com/questions/16458937/synchronization-of-remote-files-download#comment23617420_16460673 but seems like I'm missing the point


texts: Improve Trie manipulation in Haskell code

texts:
I have the following data structure:

data XComposeString = XComposeString { keyEvents :: [Event], s :: Result }
  deriving (Eq, Show)

data XComposeFile = XComposeFile { strings :: [XComposeString] }
  deriving (Eq, Show)

Where Event and Result just String or some combination of several String.

I'm creating a Trie from list of type [(keyEvents x, [s x])]:

constructTrie list = M.fromListWith comp list
  where
    comp = \old new -> old ++ new

I want to check on duplicates and prefix overlaps.

duplicates :: M.TrieMap Map.Map Event [Result] -> String
duplicates m = M.showTrie list ""
  where
    list = M.filter (\v -> length v /= 1) m

prefixOverlap :: M.TrieMap Map.Map Event [Result] -> String
prefixOverlap m = M.showTrie list ""
  where
    list = M.filterWithKey (\k v -> not $ null $ catMaybes [M.lookup x m | x <- reverse (inits (init k))]) m

How can I improve this, so, there would be three functions: one to create, one to check on duplicates and one to check on prefix overlaps.

Useful imports and types definition:

import Data.List(inits)
import Data.Maybe(catMaybes)
import qualified Data.Map as Map
import qualified Data.ListTrie.Map as M

type Event = String
type Result = String

Also, cabal install list-tries is needed for ListTrie data structure.


texts: Optimizing execution time of merging images

texts:
I am using the below code to merge two images, but it take avg of 6-7 sec for creating 16 images. Is there any way I can speed up my process?

$image1=imagecreatefrompng('img/'.$value);
$image2=imagecreatefrompng('img/'.$value1);
$w=imagesx($image1);
$h=imagesy($image1);
imagecopy($image1,$image2,0,0,0,0,$w,$h);
imagejpeg($image1,'final/'.$key.$key1.'.jpg');
imagedestroy($image1);

I also get a black backgroud. I do not want to add an extra layer as it will increase execution time.

Below is basic detail

1: images of size: 1000 * 1000
2: png + png = jpg image
3: different image will combine i had already coded in way to avoid dupliacy

below i what i am trying to do like:

http://www.gemvara.com/jewelry/emerald-isle-ring/emerald-cut-diamond-14k-white-gold-ring-with-diamond/by53

here you can see new product is combination of stone and ring base.
and has 4 different view i am trying to do like that


texts: Load fifty million integers as quickly as possible in Java

texts:
I am working my way through Project Euler. Many of the problems deal with prime number calculations: this is the type of code that can be extracted into a separate class and reused.

While calculating primes can be done quickly using certain methods, I was able to speed up the process of "getting prime numbers" by using a list of primes on disk and loading them. It is an order of magnitude faster than any calculation, but still takes roughly three minutes loading from an SSD.

What I did:

I took a publicly-available list of the first fifty million primes (some problems do use a significant portion of those numbers).
I wrote a program to convert the numbers from their textual representation to binary using Java's DataOutputStream. The file is simply fifty million four-byte integers in a row.
The utility method below loads each integer into an array using DataInputStream. It produces correct results, but it slow.

Is there any way to speed up the process of loading 50,000,000 integers? If I need to preprocess the data differently I am willing to do that.

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;

public class Test {

  public static int[] loadByQuantity(int argNumPrimes) {
    int numPrimes = Math.min(argNumPrimes, 50_000_000);
    int[] primes = new int[numPrimes];
    try (DataInputStream in = new DataInputStream(new FileInputStream("primes.bin"))) {
      for (int i = 0; i < primes.length; ++i) {
        primes[i] = in.readInt();
      }
    }
    catch (IOException ex) {
      throw new RuntimeException(ex);
    }
    return primes;
  }

}


texts:
So, I made a console interface. It prompts users with several options they can enter. 1 for the first option, 2 for the second option, etc. Using the switch statement, each option will bring them to a different screen. Now, after any of the options are entered and the users are brought to a particular screen, how do I get them back to the selection screen with those options? Would it be acceptable for me to do something along the lines of

selectionScreen:

printf("Enter 1 for the First Screen\n");
printf("Enter 2 for the Second Screen\n");
printf("Enter 3 for the Third Screen\n\n");

scanf("%d", &selection);

switch (selection)
{

case 1:

    //do and print stuff here

    for (i = 0 ; ; i ++)
    {

        //do and print stuff here

        while(GetAsyncKeyState(VK_TAB))
        {

            goto selectionScreen;

        }

         printf("Enter the Tab key to go back the selection screen.\n\n");
         printf("Enter any key besides Tab to reload!\n\n");

         getchar();

         system("CLS");

     }

    break;

case 2:

    //do and print stuff here

    for (i = 0; ; i++)
    {

        //do and print stuff here

        while(GetAsyncKeyState(VK_TAB))
        {

            goto selectionScreen;

        }

         printf("Enter the Tab key to go back the selection screen.\n\n");
         printf("Enter any key besides Tab to reload!\n\n");

         getchar();

         system("CLS");

     }

    break;

case 3:

    //do and print stuff here

    for (i = 0 ; ; i++)
    {

        //do and print stuff here

        while(GetAsyncKeyState(VK_TAB))
        {

            goto selectionScreen;

        }

         printf("Enter the Tab key to go back the selection screen.\n\n");
         printf("Enter any key besides Tab to reload!\n\n");

         getchar();

         system("CLS");

     }

    break;

default:

    //do stuff here

}

Or is there a more favorable way of doing this


texts: Identify possible pair of factors from a product

texts:
This is my first C++ program (not counting "hello world") and I'd like to know if there are some semantic mistakes or if I could rewrite the code in a more simple way.

It performs brute-force factorisation of the number provided on standard input.

Here is the code:

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

int main() {
    int f1 = 0;
    int f2 = 0;
    int p;
    int increment = 1;
    cin >> p;
    if ((f1 && f2) == p) {
        cout << f1 << "x" << f2 << "=" << p;
    }
    else if (p < 00) {
        cout << "Insert a positive number";
    }

    while (
        ( (f1 && f2) != p) && (f1 < p) && (f2 <= p) ) {

        f1++;
        if (f1 * f2 == p) {
            cout << f1 << "x" << f2 << "=" << p << "\n";
        }
        f2 = increment;
        if (f1 == p) {
            increment++;
                f1 = 0;
        }
    }
    system("pause");
        return 0;
    }

Thanks for your feedback!


texts: Get collection of objects from CSV string and vise-versa

texts:
A generic class to get object collection from csv string. I would like to know if there's any better way?

Converter class

public class CsvConverter<T>:List<T> where T:class
{
    private readonly string _csvText;
    private readonly string _separetor;

    /// <summary>
    /// Get object collection from CSV string
    /// </summary>
    /// <param name="csvText">CSV string with Title</param>
    /// <param name="separator">CSV line separator</param>
    public CsvConverter(string csvText, string separator= "\r\n")
    {
        this._csvText = csvText;
        _separetor = separator;
        BuildObject();
    }

    /// <summary>
    /// Get CSV string from collection of objects
    /// </summary>
    /// <param name="collection">Pass collection of objects</param>
    public CsvConverter(IEnumerable<T> collection)
    {
        foreach (var item in collection)
        {
            this.Add(item);
        }
    }

    /// <summary>
    /// Create new Instance of T object
    /// </summary>
    /// <returns></returns>
    protected T GetObject()
    {
        return (T)Activator.CreateInstance(typeof(T),true);
    }

    /// <summary>
    /// Build object from CSV string to collection
    /// </summary>
    private void BuildObject()
    {
        if (!string.IsNullOrEmpty(_csvText))
        {
            //Get first line from CSV string, than split by comma to get column names
            var _csvLines = _csvText.Split(_separetor);
            var _columnName =_csvLines[0].Split(',');

            for (int i = 1; i < _csvLines.Length; i++)
            {
                var line = _csvLines[i].Split(',');

                T obj = GetObject();
                Type t = obj.GetType();
                PropertyInfo[] props = t.GetProperties();

                int colIndx = 0;
                foreach (string str in line)
                {
                    PropertyInfo find = props.First(x => x.Name == _columnName[colIndx]);
                    find.SetValue(obj, Convert.ChangeType(str,find.PropertyType),null);

                    //propertyInfo.SetValue(propertyInfo.PropertyType, line[0]);
                    colIndx++;
                }
                this.Add(obj);
            }
        }
        else
        {
            throw new System.NullReferenceException("No CSV string has passed in the parameter");
        }
    }

    /// <summary>
    /// Returns CSV string from collection of T object
    /// </summary>
    /// <returns>string</returns>
    public string GetCsvString()
    {
        StringBuilder sb = new StringBuilder();
        foreach (var item in this)
        {
            Type t = item.GetType();
            PropertyInfo[] props = t.GetProperties();
            string ln = "";
            foreach (PropertyInfo prp in props)
            {
                ln= ln+($"{prp.GetValue(item)},");
            }
            sb.AppendLine($"{ln.TrimEnd(',')}");
        }
        return sb.ToString();
    }
}

get collection of object from csv string

        var csv = await System.IO.File.ReadAllTextAsync("test.csv");
        List<TestC> csvBarcode = new CsvConverter<TestC>(csv.TrimEnd());

get csv string from collection of object

        CsvConverter<TestC> b = new CsvConverter<TestC>(list);
        return Content(b.GetCsvString());


texts:
I have used d3 to draw a sine wave going around a circle. This is the very first time I've used d3 or drawn a SVG and I'm fairly new to JS as well, so I don't know if I've overcomplicated it/if there is a simpler way to achieve this. I'd appreciate some feedback - especially if there's any way to make my code more concise.

See my codepen.

const svg = d3.select('svg');
const margin = { top: 50, right: 50, bottom: 50, left: 50 };
const width = +svg.attr('width') - margin.left - margin.right;
const height = +svg.attr('height') - margin.top - margin.bottom;

// content area of your visualization
const vis = svg
.append('g')
.attr('transform', `translate(${margin.left+width/2},${margin.top+height/2})`);

// show area inside of margins
const rect = vis
.append('rect')
.attr('class', 'content')
.attr('width', width)
.attr('height', height)
.attr('transform', `translate(${-width/2},${-height/2})`);

// show scales
const xScale = d3
.scaleLinear()
.domain([-100, 100])
.range([-width/2, width/2]);
const yScale = d3
.scaleLinear()
.domain([100, -100])
.range([-height/2, height/2]);
vis.append('g').call(d3.axisTop(xScale));
vis.append('g').call(d3.axisLeft(yScale));

// draw circle
const pi = Math.PI
const radius = 63.66
const circle = vis
.append('circle')
.style('stroke-dasharray', '3, 3')
.style('stroke', 'black')
.style("fill", "transparent")
.attr("r", xScale(radius))
.attr("cx", 0)
.attr("cy", 0)

// get coordinates for a sine wave
const getSineWave = ({
  numWaves,
  wavelength,
  amplitude,
  phase,
  numPointsPerWave,
}) => {
  return (
    d3.range(numWaves*numPointsPerWave+1).map(function(k) {
      const x = k * wavelength/numPointsPerWave
      return [x, amplitude * Math.sin(phase + 2 * pi * x/wavelength)];
    })
  )
}

// tranform a coordinate from linear space to circular space
const rotate = (cx, cy, x, y, radius) => {
  const theta = x/radius,
        sin = Math.sin(theta),
        cos = Math.cos(theta),
        nx = cx + (radius + y) * sin,
        ny = cy + (radius + y) * cos
  return [nx, ny];
}

// generate sine wave
const numWaves = 4
const amplitude = 10
const phase = pi/2
const circumference = 2 * pi * radius
const wavelength = circumference / numWaves
const numPointsPerWave = 4
const sineWave = getSineWave({
  numWaves,
  numPointsPerWave,
  wavelength,
  amplitude,
  phase,
  wavelength
})
var rotatedSine = sineWave.map( d => {
  const rotatedCoords = rotate(0, 0, d[0], d[1], radius)
  return rotatedCoords
})
// remove the last point as it would overlap the first point of the circle
rotatedSine.pop()

// get Path commands for given coordinates
const getPath = d3.line()
.x(d => xScale(d[0]))
.y(d => yScale(d[1]))
.curve(d3.curveCardinalClosed)

// draw sine wave going around a circle
const wave = vis
.append('path')
.attr('d', getPath(rotatedSine))
.attr('fill', 'none')
.attr('stroke', 'black')
.attr('stroke-width', '1px')
svg {
        background-color: steelblue;
    }

    .content {
        fill: lightsteelblue;
    }
<script src="https://d3js.org/d3.v4.js"></script>
<svg width="1000" height="1000" </ svg>


texts: Hashing an arbitrary object to a sparse array of bits

texts:
I have this method in one of the java classes I'm working on (an implementation of a counting bloom filter):

private int[] hash(V v){
    Random r=new Random(v.hashCode());
    int l=r.nextInt(size);
    int[] keys=new int[size];
    for(int i=0;i<bpe;i++){
        keys[(r.nextInt(size)+l)%size]=1;
    }
    return keys;
}

Where:

V is one of the type parameters for the enclosing generic class
size is a field set on initialization, defaults to 64 unless specified otherwise from the constructor
bpe is also a field, set on initialization to Math.max(5, Math.min(size/8,(int)Math.sqrt(size)))

Is there a better way to do this?


texts: Using an alternative for a switch/state-based custom parser

texts:
I'm currently developing a small tool that applies a number of regex-based match/replacement-pairs to the contents of a file (or, more generally speaking, a string).
Note that regex-knowledge is not relevant to this answer, which is the reason why I didn't add it to the tags.

Now, this tool also supports saving all of your match/replace-pairs to a file. Since I've made bad experiences when using GSON with lists or arrays in the past, I decided to use my own format - considering it just has to save some kind of match-replace-separator-match-replace-separator-etc-style structure.

Now, my code works so far, but during refactoring, I felt like using a switch-statement with states for parsing my format is ugly and/or bad style.
However, if you believe that this is in fact a good solution, contrary to my assessment, I would of course also be happy with that answer.

The private static final int values in the snippet below will be replaced with an enum eventually, but for this purpose, I figured this would be more readable (by removing the need for an additional class).

private static final String SEPARATOR = "###";
private static final int SEPARATOR_EXPECTED = 0;
private static final int MATCH_EXPECTED = 1;
private static final int REPLACE_EXPECTED = 2;

public static List<MatchReplacePair> readRegexesFromFile(File file) {
    List<MatchReplacePair> list = new ArrayList<>();
    try (BufferedReader br = new BufferedReader(new FileReader(file))) {
        String line = br.readLine();
        int state = SEPARATOR_EXPECTED;
        MatchReplacePair pair = new MatchReplacePair("", "");
        while (line != null) {
            switch (state) {
            case SEPARATOR_EXPECTED:
                if (line.startsWith(SEPARATOR)) {
                    state = MATCH_EXPECTED;
                } else {
                    throw new IllegalStateException("Separator expected, but not found.");
                }
                break;
            case MATCH_EXPECTED:
                pair.setMatch(line);
                state = REPLACE_EXPECTED;
                break;
            case REPLACE_EXPECTED:
                pair.setReplace(line);
                // note: I have overridden the clone() method for this purpose, so it actually does what it's supposed to.
                list.add(pair.clone());
                state = SEPARATOR_EXPECTED;
                break;
            default:
                throw new IllegalStateException("Unknown state. Please contact the developer.");
            }
            line = br.readLine();
        }
        if (state != SEPARATOR_EXPECTED) {
            throw new IllegalStateException(
                    "Incorrect file contents: make sure the file ends with a \"replace\" block.");
        }
    } catch (IOException e) {
        e.printStackTrace(log);
    }
    return list;
}

A sample file to parse:

### //This is where one could write comments if one was so inclined.
match
replace


texts: React app for movie search, making AJAX call with input value from another component

texts:
I am building a movie search React app using themoviedb.org API. To make ajax call to pull the list of movies I need to get input value as a variable and feed to the url, but not sure how to fetch a value that belongs to another component.

I've made an extensive online search, but they mainly refer to the case when it happens inside same component, and using ref is discouraged.

So what would be the best way to organize an app in React way, keeping components uncoupled yet able to feed input value to url of another component?

   import React from 'react';
   import './App.css';
   import axios from 'axios';

class SearchForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: ''};

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    this.setState({value: event.target.value});
  }

  handleSubmit(event) {
    console.log("state value is " + this.state.value);

    var searchValue = this.movieName.value;
    console.log("ref value is "+ searchValue)

    event.preventDefault();
  }

  render() {

    return (
      <form onSubmit={this.handleSubmit}>

          Name:
          <input className="movieName" type="text" ref={(input) => { this.movieName = input; }} value={this.state.value} onChange={this.handleChange} />

        <input type="submit" value="Submit" />

{this.state.value}

      </form>
    );
  }
}

class App extends NameForm{  /* I am extending NameForm to get access to input value, but probably coupling components too tight */
    constructor(props) {
      super(props);
      this.state ={
        movie:[]
      };
    }

componentDidMount() {

  let searchInput = "land"; /* This should be from SearchForm's value */

let sortByPop = "&sort_by=popularity.desc";
let requestUrl = 'https://api.themoviedb.org/3/search/movie?api_key=f8c4016803faf5e7f424abe98a04b8d9&query=' + searchInput + sortByPop;

  axios.get(requestUrl).then(response => {
      this.setState({movie: response.data.results})
  });

}

render() {

 let baseImgURL = "https://image.tmdb.org/t/p/w185_and_h278_bestv2";
 let posterImgPath = this.state.movie.map(movie => movie.poster_path);

 let posterLink = baseImgURL + posterImgPath;

  return(

       <SearchForm />

          {this.state.movie.map(movie =>

           <img className="posterImg" src= {`https://image.tmdb.org/t/p/w185_and_h278_bestv2/${movie.poster_path}`} alt={movie.title} />

{movie.title}

           )}

  )
}

}

export default App;


texts: Angular directive to disable a button when clicked, allowing re-enabling as needed

texts:
I have written an Angular Directive that disables a button after it has been clicked, to prevent double posting / saving of data. This works fine in most of our use cases. However, in some situation we want to re-enable the button. For example: the button-click triggers a form submit, but the server-side validation fails. We want to allow the user to submit again, so we need to re-enable the button.

My solution uses an EventEmitter that is owned by the 'host' Component. This EventEmitter is passed on to the button's Directive. This Directive then subscribes to it. Whenever the host wants to instruct the button to re-enable, is emits an event. The Directive will take care of enabling the button.

As an alternative, one could use the disabled property of the button to control its state. However, I would like to reserve that property for other logic that is part of the host Component (e.g. are all required fields correctly filled, etc.). I would like to keep the code for the double posting safeguard contained to the Directive as much as possible.

I'd like to learn if there might be a cleaner way to accomplish what I'm after. Here's what I do now:

The button as used in the host Component template

<button [appDisableAfterClick]="reenableButton"
        (click)="doStuff()">My button</button>

Inside the host Component

private reenableButton = new EventEmitter<boolean>();

doStuff() {
  // Make some external call.
  // In case of an error, re-enable the button:

  this.reenableButton.emit();
}

The DisableAfterClick Directive

Several null checks and unsubscribe calls omitted for brevity.

@Directive({
  selector: '[appDisableAfterClick]'
})
export class DisableAfterClickDirective implements OnChanges, OnDestroy {
  @Input('appDisableAfterClick') reenableButton: EventEmitter<boolean>;

  ngOnChanges(changes: SimpleChanges) {
    this.reenableButton = changes.reenableButton.currentValue;

    this.reenableButton.subscribe(_ => {
      (<HTMLButtonElement>this.el.nativeElement).disabled = false;
    });
  }

  @HostListener('click')
  onClick() {
    (<HTMLButtonElement>this.el.nativeElement).disabled = true;
  }
}


texts:
I'm attempting to create a function that will give me a "fish" at random, though a bias random depending on the weight value for the "fish".

var FISH = {
    "level1": [
          //["name",      xp, weight]
            ["Shrimp",    10, 95],
            ["Sardine",   20, 85],
            ["Herring",   30, 75],
            ["Anchovies", 40, 65],
            ["Mackerel",  40, 55]
        ]
};

function randomRange(min, max) {
    return Math.random() * (max - min) + min;
}

function getRandomFish(level) {
    var fishForLevel = FISH[level],
        numberOfFish = fishForLevel.length,
        chance = randomRange(0, 100);

    if (numberOfFish > 1) {

        var fish = fishForLevel[Math.floor(randomRange(0, numberOfFish))];

        if (chance <= fish[2]) {
            return fish;
        } else {
            return getRandomFish(level);
        }

    } else {
        return fishForLevel[0];
    }
}

Example of outcome: http://jsfiddle.net/qAvAs/

If this could be made more efficient, how would one do so?


texts:
I am working on a e-shop in ASP.NET MVC, and I just made the listing of product the way I figured out this night. Is it correct? Or should I make it differently? How?

So this is my Product controller, used for displaying the products from Db.

using WebShop.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WebShop.Controllers
{
    public class ProductController : Controller
    {
        private WebShopEntities db = new WebShopEntities();

        public ActionResult Category(int? id)
        {
            int pid = id == null ? 1 : (int)id;  //if requested id is null, set is as 1
            if (db.Categories.Find(pid) == null)  //if category does not exist, return Error
                return View("Error");
            var model = db.Categories.Find(pid).Products.ToList(); //return list of projects in requested category
            return View(model);
        }
    }
}

This is the Category View.

@using WebShop.Models
    @{
        ViewBag.Title = "Category";
        Layout = "~/Views/Shared/_Layout.cshtml";
    }

            @Html.Partial("Partial/_PartialCategoryMenu")  //display partial view for category menu

            @foreach(Product p in Model)
            {
                @Html.Partial("Partial/_PartialProduct", p)  //display partial view
            }

These are partial Views, which are self-explanatory I hope.
Category partial view

@using WebShop.Models

@using (var db = new WebShopEntities()) {
foreach (var category in db.Categories)
{
    @category.name
}
}

Product partial view

@Model.name

@Model.price €

@Model.description

To Cart Details


texts: Word break problem with recursion and memorization

texts:
For practice, I solved Leetcode 139. worbreak question:

  Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.

I have the solution to use the recursive with in-memory hash table to reduced to duplication calculation. but it seems like works for some case but not all. any suggestions?

def wordbreak(self, s, wordDict):
    wordDict = set(wordDict)
    str_map = dict()
    if not s or not wordDict: return False

    def check(s):
        if s in str_map: return str_map[s]
        if s in wordDict:
            str_map[s] = True
            return True
        for i, c in enumerate(s[1:], 1):
            if s[:i] in set(wordDict) and check(s[i:]):
                str_map[s[:i]] = True
        str_map[s] = False
        return False

    return check(s)

if __name__ == '__main__':
    testcase = [
        dict(tc=dict(s='ab', wordDict=['a', 'b']), exp=True),
        dict(tc=dict(s='leetcode', wordDict=['leet', 'code']), exp=True),
        dict(tc=dict(
            s="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab",
            wordDict=["a", "aa", "aaa", "aaaa", "aaaaa", "aaaaaa", "aaaaaaa", "aaaaaaaa", "aaaaaaaaa",
                      "aaaaaaaaaa"]), exp=False),
    ]
    for tc in testcase:
        res = wordbreak(**tc['tc'])
        print(res) # True, True, False


texts:
I have two loops on my page - each with their own category. It works, but I don't know if this is the best practice as I'm pretty new to this stuff.

<?php $my_query = new WP_Query( 'category_name=news&posts_per_page=3' );
        while ( $my_query->have_posts() ) : $my_query->the_post();
                $do_not_duplicate[] = $post->ID; ?>
                <!-- Do stuff... -->
<?php get_template_part( 'content', get_post_format() ); ?>

<?php endwhile; ?>

<?php $second_query = new WP_Query( 'category_name=reviews&posts_per_page=4' );
        while ( $second_query->have_posts() ) : $second_query->the_post();
                $do_not_duplicate[] = $post->ID; ?>
                <!-- Do stuff... -->
<?php get_template_part( 'content', get_post_format() ); ?>

<?php endwhile; ?>


texts: Calculating n-ary Cartesian Product too slow

texts:
The method gets called extensively throughout my programm, is there any way I can speed it up or improve other aspects?

The code calculates the n-ary Cartesian Product of a List containing n Lists, so that for example:
Product([[1],[2,3],[4,5]]) yields [1,2,4],[1,2,5],[1,3,4],[1,3,5]
public static IEnumerable<T[]> Product<T>(T[][] items)
    {
        T[] currentItem = new T[items.Length];
        static IEnumerable<T[]> go(T[][] items, T[] currentItem, int index)
        {
            if (index == items.Length)
            {
                yield return currentItem;
                yield break;
            }
            else
            {
                foreach (T item in items[index])
                {
                    currentItem[index] = item;
                    foreach(var j in go(items, currentItem, index + 1))
                    {
                        yield return j;
                    }
                }
            }

        }
        return go(items, currentItem, 0);
    }

A possible problem i can think of, is the
foreach(var j in go(items, currentItem, index + 1))
       {
           yield return j;
       }

section, since it takes n yields for every (single) array that is part of the n-ary Cartesian Product.


texts:
I have a method which extracts the logged-in user details from a SpringSecurityContext object.

I have read that only utility methods (which does certain calculations) should be static.

Here is my method; it doesn't seem to be a utility method but I don't find any reason why I shouldn't make it static as I am using it in multiple beans.

public static int getSignedUpUser()
    {
        final SecurityContext ctx = SecurityContextHolder.getContext();

        if(ctx != null)
        {
            final Authentication auth = ctx.getAuthentication();

            if(auth != null)
            {
                final Object principal = auth.getPrincipal();

                if(principal instanceof AUser)
                {
                    final AUser au = (AUser)principal;
                    return au.getId();
                }
            }
        }

        return 0;
    }
}


texts: Fetch a department's total, Its percentage of earnings for that site and its percentage of earnings across the company

texts:
I am trying to use the data from one table to produce the result set
| Dept | TotalValue | PercentageOfSite | PercentageOfCompany |

Any improvements or advice on the below would be helpful.

DECLARE @SiteNo INT = 1
DECLARE @SessionDateFrom DATETIME = '2017/02/01'
DECLARE @SessionDateTo DATETIME = '2017/03/01'

    CREATE TABLE #DepartmentSales
(
    DeptName VARCHAR(50),
    DeptNo SMALLINT,
    Value MONEY,
    SiteNo SMALLINT
)

INSERT INTO #DepartmentSales
SELECT DeptName
    ,DeptNo
    ,SUM(Value) AS SalesValue
    ,SiteNo
FROM PLUSalesDetailExtended
WHERE DATE BETWEEN @SessionDateFrom AND @SessionDateTo
AND TermNo = 0
GROUP BY DeptName, DeptNo, SiteNo

SELECT DeptName
    ,DeptNo
    ,Value AS SalesValue
    ,Value / (SELECT SUM(Value) FROM #DepartmentSales WHERE SiteNo = @SiteNo) AS SitePercent
    ,Value / (SELECT SUM(Value) FROM #DepartmentSales) AS CompanyPercent

FROM #DepartmentSales
WHERE SiteNo = @SiteNo
GROUP BY DeptName
    ,DeptNo
    ,Value

If(OBJECT_ID('tempdb..#DepartmentSales') Is Not Null)
Begin
    Drop Table #DepartmentSales
End

Any further questions please ask and I shall try to answer them.


texts: Counting the frequency of certain entries in a list of JSON objects

texts:
I have a list of JSON objects that looks like this:

[{
  url: '/home',
  ...
}, {
  url: '/analytics',
  ...
}]

I'm using the following function to count the frequencies of the URLs in order to pass it to a c3.js chart.

var getSectionFrequencyData = function(data) {
  var frequencies = {};
  data.map(function(entry) {
    var matches = /[a-z]+/g.exec(entry.url);
    var url = 'home';
    if (matches) {
      url = matches[0];
    }
    frequencies[url] = frequencies[url] ? frequencies[url] + 1 : 1;
  });
  var items = Object.keys(frequencies).map(function(section) {
    return [section, frequencies[section]];
  }).sort(function(a, b) {
    return b[1] - a[1];
  }).slice(0, 10);
  return [
    ['sections'].concat(items.map(item => item[0])),
    ['frequency'].concat(items.map(item => item[1]))
  ];
};

This code works, but the frequency counting, sorting, and grouping seems extremely overengineered and clunky. Best practices for this?


texts:
I made a search method because I want to use binary data like PNG files. The point of this is to be able to find strings like IEND in a PNG file. I think it works properly. Any improvements/fixes would be appreciated.

public static int findString(byte[] in, byte[] find) {
        boolean done = false;
        for(int i = 0; i < in.length; i++) {
            if(in[i] == find[0]) {
                for(int ii = 1; ii < find.length; i++) {
                    if(in[i+ii] != find[ii]) break;
                    else if(ii==find.length-1) done = true;
                }
                if(done) return i-1;
            }
        }
        return -1;
    }


texts: Program that guesses your number using bitwise operations

texts:
I got the idea for this program from this site.

functions.cpp:

#include <iostream>
#include <cstdlib>
#include <iomanip>

namespace my
{
    int getOneOrZero()
  {
    return (rand() >> 14);   // >> the bitwise operator
  }

// getArray leaves the numbers ( 0-99 ) that have in their bit position        represented by bigFlag the num ( 0 or 1 )

void printNums(int8_t bitFlag, int num)    // num is from getOneOrZero() so it's 1 or 0;
{
    for (int counter = 0; counter < 100; ++counter)  // there are quite a few implicit conversions to one byte integers
        {
            if ( (counter & bitFlag) != num*bitFlag )
                std::cout << std::setw(8) << " ";
            else
                std::cout << std::setw(8) << counter;

            if ( (counter % 9) == 0)
                std::cout << std::endl;
        }
}

char getAnswer()
{
    while (1)
    {
        std::cout << "\n Is your number shown above ?\n\n 'y' for yes , 'n' for no , 'r' for reset : ";
        char answer;
        std::cin >> answer;
        std::cin.ignore(32767,'\n');

        if (std::cin.fail())
            std::cin.clear();

        if (answer == 'y' || answer == 'n' || answer == 'r')   // I could use switch but nevermind
            return answer;
    }
}

void turnsPassed(int turns)
{
    std::cout << "\n This is turn " << turns << "\n\n";
}

int swapZeroOrOne(int num)
{
    switch (num)
    {
    case 0 :
        return 1;
    case 1 :
        return 0;
    default:
        std::cout << "\nSwapZeroOrOne ERROR !\n";
        break;
    }
}

int getUpdateForGuessNum(int8_t flag, int num, char answer)
{
    switch (answer)
    {
    case 'n' :
        { int newNum = swapZeroOrOne(num);
          return newNum*flag;
        }
    case 'y' :
        return num*flag;
    case 'r' :
        break;
    default  :
        std::cout << "\n ERROR ! In getUpdateForGuessNum\n";
        break;
    }
  }
}

main.cpp:

#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
#include "functions.hpp"
#include "constants.hpp"
#include <stdlib.h>      // for system() commands >.<
int main()
{
srand( static_cast<unsigned int>(time(0)));

Reset :      // goto !
system("cls");

int guessNum = 0;

// guessing loop !

for (int counter = 0; counter < 7; ++counter)
{
    if (counter == 0)
        std::cout << "\n Think of a number between 0 to 99\n";

    my::turnsPassed(counter + 1);  // +1 cause counter starts from 0

    int num {my::getOneOrZero()};  // this gives a randomness to the numbers shown each time you run the programm

    my::printNums(myVar::bitFlag[counter],num);

    char answer { my::getAnswer() };

    if (answer == 'r')
        goto Reset;

    guessNum |= my::getUpdateForGuessNum(myVar::bitFlag[counter],num,answer);

    system("cls");
}

std::cout << "\n Your number is \n";
std::cout << "\n" << std::setfill('-')  << std::setw(81) << "\n";
std::cout << std::setfill(' ') << std::setw(41) << guessNum << "\n";
std::cout << "\n" << std::setfill('-')  << std::setw(81) << "\n";

system("pause");  // I should fix this

return 0;
}

functions.hpp:

#pragma once

namespace my
{
    int getOneOrZero();
    void printNums(int8_t,int);
    char getAnswer();
    void turnsPassed(int);
    int getUpdateForGuessNum(int8_t,int,char);
    int swapZeroOrOne(int);

}

constants.hpp:

#pragma once

namespace myVar
{
    const int8_t bitFlag[] {0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80};
}

Please suggest ways to improve this program. Explain the suggestions you make because I need to know why I should change something.


texts:
I am currently reading through an algorithm book and trying to implement everything as I go. I am also learning python at the same time. This is my implementation of a simple linked-list. I am mainly concerned with whether the code looks "looks python like" any tips on how I can refactor would be greatly appreciated.

class Linked(object):
    # init
    def __init__(self):
        self.head = None
        self.tail = None

    def add(self, data):
        temp = Node(data, None, None)
        if (self.head is None):
            self.head = temp
            self.tail = temp
        else:
            self.tail.setAfter(temp)
            temp.setBefore(self.tail)
            self.tail = temp

    def find(self, data):
        if (self.head is None):
            return "Empty List"
        else:
            current = self.head
            while (current is not None):
                if (current.element() is data):
                    return current
                current = current.next()
        return "Element not in List"

    def remove(self, data):
        if (self.head is None):
            return "Empty List"
        elif(self.find(data).element() is data):
            temp = self.find(data)
            if (temp is self.head and temp is self.tail):
                self.head = None
                self.tail = None
            elif (temp is self.head):
                self.head = temp.next()
                self.head.setBefore(None)
                return
            elif (temp is self.tail):
                temp.before.setAfter(None)
                return
            else:
                temp.before.setAfter(temp.after)
                temp.after.setBefore(temp.before)

    def iterator(self):
        if (self.head is None):
            return "Empty List"
        else:
            current = self.head
            while (current is not None):
                print(current.element())
                current = current.next()

class Node(object):
    # init
    def __init__(self, data=None, before=None, after=None):
        self.data = data
        self.before = before
        self.after = after

    def element(self):
        return self.data

    def setBefore(self, before):
        self.before = before

    def setAfter(self, after):
        self.after = after

    def next(self):
        return self.after


texts: T-SQL Totp (Rfc6238 SHA2_256) Implementation

texts:
Using my previous function as a base I've come up the following:

create function dbo.Totp (
    @key varbinary(8000)
  , @timeStep int = 90
)
returns table
with schemabinding as
return (
    select [Pin].s as Pin
    from dbo.GetUnixTime() UnixEpoch
    cross apply dbo.Hmac(@key, Cast(Floor(1. * UnixEpoch.n / @timeStep) as bigint)) [Hash]
    cross apply (values(Cast(Substring([Hash].Bytes, DataLength([Hash].Bytes), 1) as int) & 0xF)) Offset (n)
    cross apply (values(
        ((Cast(Substring([Hash].Bytes, Offset.n + 1, 1) as int) & 0x7F) * Power(2, 24))
      + ((Cast(Substring([Hash].Bytes, Offset.n + 2, 1) as int) & 0xFF) * Power(2, 16))
      + ((Cast(Substring([Hash].Bytes, Offset.n + 3, 1) as int) & 0xFF) * Power(2, 8))
      + (Cast(Substring([Hash].Bytes, Offset.n + 4, 1) as int) & 0xFF)
    )) [Binary] (n)
    cross apply (values([Binary].n % 100000000)) [Password] (n)
    cross apply dbo.PadLeft([Password].n, 0, 8) [Pin]
);


texts:
I have a class called Duration which has the attributes hours, mins, and secs. These attributes have to stay within acceptable ranges, so I implemented the following in their setters:

public void setHours(int newHours){
    if (newHours >= 0){
        hours = newHours;
    }
    else{
         throw new RuntimeException("Invalid argument values");
    }
}

and so on for the other attributes.

Is there a better design pattern I could be using here? Is this an appropriate use of the RuntineException?


texts:
I am writing a Swift library.  I'm writing unit tests for that library.

I am afraid that some of the code that I am testing will possibly throw exceptions.  In Swift, we can handle errors, but we can not handle exceptions.  Exceptions are considered programmer errors which should be caught and fixed before release.  They shouldn't be handled at run time.

In order to automate the process of catching these exceptions, I wanted to write some Objective-C code which would allow me to catch these exceptions that my Swift code could potentially throw (because someone refactored and broke it).

So, I came up with this solution:

@implementation ObjCTry

+ (NSException * _Nullable)executeBlock:(__attribute__((noescape)) void (^ _Nonnull)(void))block {
    @try {
        block();
        return nil;
    }
    @catch (NSException *exception) {
        return exception;
    }
}

@end

I'm not particularly thrilled about the name, nor do I think calling it from Swift is necessarily the prettiest.

So I wrapped that in this Swift function:

func BCTAssertNoException(@noescape closure: () -> Void) {
    let exception = ObjCTry.executeBlock(closure)
    XCTAssertNil(exception)
}

And that cleaned up the usage in Swift a little bit.

Example usage:

func testExample() {
    BCTAssertNoException {
        let object = NSObject()
        object.performSelector(Selector("fooNotExistSelector"))
    }
}

As a note, I can't seem to get this to catch Swift fatal errors, but my actual use-case concern is unrecognized selector, and it does catch that.


texts: OOP php method - pass parameters in or get from inside object

texts:
I am new to OOP and have written a products class. All is working fine but I am unsure which of the below version of a method within this class is best?

The first gets the variables from within the object and the second passes the variables into the class. Both work. I originally had it as the first version but things seems to be running slow and then changed it to the second.

public function getProductURLstart(){
    $select = "SELECT l.URL, p.id FROM logins AS l
        INNER JOIN Pages AS p ON l.id = p.clientID
        WHERE l.id = '$this->skID' AND p.productPage = 1";

    $res = mssql_query($select);
    $r = mssql_fetch_row($res);

    $url = trim($r[0]);
    $page_id = $r[1];

    return  $url .'/index.aspx?pageID='. $page_id . '&prodID=$this->prodID';
}

OR

static function getProductURLstart($skID, $prodId){
    $select = "SELECT l.URL, p.id FROM logins AS l
        INNER JOIN Pages AS p ON l.id = p.clientID
        WHERE l.id = '$skID' AND p.productPage = 1";

    $res = mssql_query($select);
    $r = mssql_fetch_row($res);

    $url = trim($r[0]);
    $page_id = $r[1];

    return  $url .'/index.aspx?pageID='. $page_id . '&prodID=$prodId';
}


texts:
Is there a more elegant way of doing this? I really think this looks ugly.

private static string InsertMethodNameHere( bool hasCondition1, bool hasCondition, bool hasCondition3)
        {
            if (!hasCondition1 && !hasCondition2 && !hasCondition3)
                return "0";

            if (hasCondition1 && !hasCondition2 && !hasCondition3)
                return "1";

            if (!hasCondition1 && hasCondition2 && !hasCondition3)
                return "2";

            if (hasCondition1 && hasCondition2 && !hasCondition3)
                return "3";

            if (!hasCondition1 && !hasCondition2 && hasCondition3)
                return "4";

            if (hasCondition1 && !hasCondition2 && hasCondition3)
                return "5";

            if (!hasCondition1 && hasCondition2 && hasCondition3)
                return "6";

            if (hasCondition1 && hasCondition2 && hasCondition3)
                return "7";

            throw new Exception("Unable to determine.");
}


texts:
I am working on a problem "3Sum", in which, given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0. I must find all unique triplets in the array which gives the sum of zero.

I wrote my naive implementation which was \$O(n^3)\$ since it was checking for every possible combination:

public List<List<Integer>> threeSum(int[] num) {
    List<List<Integer>> res=new ArrayList<List<Integer>>();

        if(num.length<3) return res;

       Arrays.sort(num);

        for(int i=0;i<num.length;i++)
        {
         if(num[i]>0) break;
            for(int j=i+1;j<num.length;j++)
            {
                if(num[i]+num[j]>0 && num[j]>0) break;
                for(int k=j+1;k<num.length;k++)
                {
                    if(num[i]+num[j]+num[k]==0)
                      {
                          List<Integer> curr=new ArrayList<Integer>();
                          curr.add(num[i]);
                          curr.add(num[j]);
                          curr.add(num[k]);
                          res.add(curr);
                      }
                      while(k+1<num.length && num[k]==num[k+1]) k++;
                }
                 while(j+1<num.length && num[j]==num[j+1]) j++;
            }
            while(i+1<num.length && num[i]==num[i+1]) i++;
        }
        return res;

}

However, I am looking for a solution which is better than \$O(n^2)\$. Rather, is there a way I can bring the time complexity of my solution to \$O(n^2)\$ by removing any of the loops?


texts: Finds a Character based on distance and health

texts:
I need to improve the efficiency of my program and, using the profiler, have narrowed the problem down to 2 key areas, but I am having trouble coming up with ways to make the program run better.

Based on my profiler's report, it seems to be telling me that my if functions are inefficient. Whats a better way to achieve a better result?

Character* FindAttackTarget() const
        {
            float weakestHp = FLT_MAX;
            Character* weakestEnemy = nullptr;
            uint64_t weakestCharId = INT64_MAX;

            //Only attack characters that are within attack range
            auto& gameChars = m_pGame->m_gameCharacters;

            for (size_t i = 0; i < gameChars.size(); ++i)
            {
                auto& c = gameChars[i];
                if (Location.Dist(c.GetLocation()) <= AttackRange &&
                    c.HP > 0 &&
                    c.Team != Team)
                {
                    //We want the weakest with the lowest ID number - this keeps consistent results when re-playing the same part of the game (eg. after a load game)
                    if (c.HP < weakestHp || (c.HP == weakestHp && c.ID < weakestCharId))
                    {
                        weakestEnemy = &gameChars[i];
                        weakestHp = c.HP;
                        weakestCharId = c.ID;
                    }
                }
            }

            return weakestEnemy;
        }


texts:
I am creating a performant C# socket server. I'd like it to be able to accept as many simultaneous connections as possible. I've tested with 100 clients and all clients are fine. With 1000 however, clients begin to stop connecting. Is it possible to improve something to increase the number of simultaneous connections?

Of course, general code review would also be appreciated.

Server:

class Listener
{
    public readonly int Port;
    private readonly TcpListener _tcpListener;
    private readonly Task _listenTask;

    public Listener(int port)
    {
        Port = port;
        _tcpListener = new TcpListener(IPAddress.Any, Port);
        _tcpListener.Start();

        _listenTask = Task.Factory.StartNew(() => ListenLoop());
    }

    private async void ListenLoop()
    {
        for (; ; )
        {
            var socket = await _tcpListener.AcceptSocketAsync();
            if (socket == null)
                break;

            var client = new Client(socket);

            Task.Factory.StartNew(client.Do);
        }
    }
}

class Client
{
    private readonly Socket _socket;
    private readonly NetworkStream _networkStream;
    private readonly MemoryStream _memoryStream = new MemoryStream();
    private readonly StreamReader _streamReader;

    public Client(Socket socket)
    {
        _socket = socket;
        _networkStream = new NetworkStream(socket, true);
        _streamReader = new StreamReader(_memoryStream);
    }

    public async void Do()
    {
        byte[] buffer = new byte[4096];
        int bytesRead = await _networkStream.ReadAsync(buffer, 0, buffer.Length);

        Console.WriteLine("Doing some awesome work that takes 5 seconds.");
        Thread.Sleep(5000);
        Console.WriteLine("Finished doing work.");

        await _networkStream.WriteAsync(buffer, 0, buffer.Length);
        await _networkStream.FlushAsync();
    }
}

Client:

class Program
{
    static void Main(string[] args)
    {
        Thread.Sleep(5000);

        Console.WriteLine("Connecting...");

        TcpClient client = new TcpClient("localhost", 6666);

        Console.WriteLine("Connected.");

        try
        {
            Stream stream = client.GetStream();

            Byte[] messageToSend = new Byte[3];
            messageToSend[0] = 1;
            messageToSend[1] = 3;

            Byte[] messageReceived = new Byte[3];

            stream.WriteAsync(messageToSend, 0, 3);

            stream.Flush();

            stream.Read(messageReceived, 0, 3);

            // Echo
            Console.WriteLine(messageReceived[0] + messageReceived[1]);

            stream.Close();
        }
        finally
        {
            client.Close();
        }
    }
}


texts:
I have a site where there are lots of "jobs" that a user creates. The user has the option to Close any given job. I want a pop up warning dialog whenever the user clicks the Close button, and verify that they actually want to close the job.

There are many ways to do this, and I've implemented it this way (jsfiddle):

function openCloseDialog(item) {
    var jobid = $(item).attr("jobid");
    var closeLink = $(item).attr("value");

    if ($("#closeWarningModal").size() > 0) {
        $("#closeWarningModal").dialog({
            autoOpen: true,
            'modal': true,
            title: "Close Job",
            draggable: true,
            resizable: true,
            'buttons': {
                'Cancel': function () {
                    $(this).dialog('close');
                },
                'Close': function () {
                    // close
                    $(this).dialog('close');
                },
            }
        });
    } else {
        // close
    }
}

This seems to be working perfectly fine. The question I have is, is there any reason to NOT do it this way? At first I was curious if this implementation would cause multiple instantiations of the dialog, or if the user clicked the Close button a second time it would fail to open. But neither of those things are happening and it seems to work perfectly.

Can you see or find anything wrong with this code?