texts:
Using the following code, I am able to neatly draw a color wheel, however, performance is barely acceptable on a high end machine. Now, I know some tricks I could employ to make it run far more smoothly, at the cost of a lot of flexibility, but I am especially interested in optimizing the code itself (thus keeping the flexibility). And of course in any generic feedback.

// Utility functions (ignore mostly)
function hsv2rgb(h, s, v) {
    var c = v * s;
    var h1 = h / 60;
    var x = c * (1 - Math.abs((h1 % 2) - 1));
    var m = v - c;
    var rgb;

    if (typeof h == 'undefined') rgb = [0, 0, 0];
    else if (h1 < 1) rgb = [c, x, 0];
    else if (h1 < 2) rgb = [x, c, 0];
    else if (h1 < 3) rgb = [0, c, x];
    else if (h1 < 4) rgb = [0, x, c];
    else if (h1 < 5) rgb = [x, 0, c];
    else if (h1 <= 6) rgb = [c, 0, x];

    return [255 * (rgb[0] + m), 255 * (rgb[1] + m), 255 * (rgb[2] + m)];
}
function hsv2rgbString(h,s,v){
    var rgb = hsv2rgb(h,s,v);
    rgb = rgb.map(Math.round);
    return "rgb("+rgb[0]+","+rgb[1]+","+rgb[2]+")";
}

// Code
var canvas = document.getElementById("picker");
var context = canvas.getContext("2d");
var rangeEl = document.getElementById('range');
var x = canvas.width / 2;
var y = canvas.height / 2;
var borderWidth = 2;
var totalRadius = canvas.width / 2 - borderWidth;
var type = "hsv";

// To trigger anti aliasing, performance is poor even without it
context.moveTo(x, y);

var drawPicker = function(){
    context.clearRect (0, 0, 150, 150);
    context.lineWidth = 1;

    for(var i=0;i<totalRadius;i++){
        var radius = totalRadius-i;

        if(type == "hsl"){
            var saturation = Math.floor(radius/totalRadius*100)/100;
            var lightness = rangeEl.value;
        }else if(type == "hsv"){
            var saturation = Math.floor(radius/totalRadius*100)/100;
            var value = rangeEl.value;
        }

        for(var angle=0; angle<=360; angle+=1){
            var startAngle = (angle-1) * Math.PI/180;
            var endAngle = (angle+1) * Math.PI/180;
            context.beginPath();
            context.arc(x, y, radius, startAngle, endAngle, false);
            context.closePath();
            if(type == "hsl"){
                context.strokeStyle = 'hsl('+angle+', '+saturation*100+'%, '+lightness*100+'%)';
            }else if(type == "hsv"){
                context.strokeStyle = hsv2rgbString(angle,saturation,value);
            }
            context.stroke();
        }
    }

    // Draw the final black border
    context.strokeStyle = "rgb(0,0,0)";
    context.lineWidth = borderWidth;
    context.beginPath();
    var borderRadius = totalRadius+borderWidth/2;
    context.arc(x, y, borderRadius, 0, 2*Math.PI, false);
    context.closePath();
    context.stroke();
}

drawPicker();
rangeEl.addEventListener("change",drawPicker);
<canvas id="picker" width="150" height="150"></canvas><br/>
<input id="range" type="range" min="0" max="1" value="1" step="0.01">

I am asking for a code review, but if anybody knows what's causing the white lines (the Moiré pattern) appear at a low value (the slider) then I would be forever grateful. Or rather, I get why they appear, I just don't know how to solve it... beyond doubling the resolution and downscaling.


texts:
i=0
while i<=10:
    i+=1
    if i==5:
        continue
    print i*5

It prints the multiplication table of 5 as well as skips the 5th number in the series


texts: Distance checking of normalized vectors?

texts:
I've been learning C#/XNA in an attempt to make a game for the past few weeks so maybe this is an obvious newbie thing, but here goes:

I've been making a fairly simple 2D game, so I have a list of ~1000 objects (NPC's), and I'm iterating through them extremely frequently to do distance checking on each one. The problem is when I increase the distances, everything slows down considerably to the point where the game is unplayable, and I don't really understand why.

It works fine when the distances are short (if all objects are within one 800x480 world size), but when they are increased (say, an 8000x4800 world size), my performance tanks.

Here is some relevant code (not all of it, obviously, since that would be too much stuff, but this is the gist of what's happening):

List<Human> humans;
List<Enemy> enemies;

public void Update(City city, float gameTime)
{
    humans = city.GetHumans();
    enemies = city.GetEnemies();

    for (int h = 0; h < humans.Count; h++)
    {
        Vector2 human_position = humans[h].position;

        Vector2 nearestEnemyPosition = Vector2.Zero;

        for (int e = 0; e < enemies.Count; e++)
            {
                Vector2 enemy_position = enemies[e].position;
                float distanceToEnemy = Vector2.DistanceSquared(human_position, enemy_position);

                if (distanceToEnemy < distanceToNearestEnemy)
                {
                    distanceToNearestEnemy = distanceToEnemy;
                    nearestEnemyPosition = enemy_position;
                }

                if (distanceToNearestEnemy < 2500f)
                {
                     logic code here (very little performance impact)
                }
            }

        for (int hh = 0; hh < humans.Count; hh++)
            {
                if (h == hh)
                {
                    continue;
                }

                if (humanMoved == true)
                {
                    continue;
                }

                Vector2 other_human_position = humans[hh].position;

                if (Vector2.DistanceSquared(human_position, other_human_position) < 100f)
                {
                   do more stuff here (movement code, no performance impact)
                }

I also have almost identical loops for the enemy list.

The code to make them is here:

foreach (Human human in this.humans)
        {
            Vector2 position = new Vector2(random.Next(800), random.Next(480));
            human.Spawn(position);
        }

This works fine. I get 60FPS and it's totally smooth & everything runs perfectly. However, if I do this:

foreach (Human human in this.humans)
        {
            Vector2 position = new Vector2(random.Next(8000), random.Next(4800));
            human.Spawn(position);
        }

Everything tanks and I get 1FPS. I tried normalizing the vectors, which solved the performance issue, but whenever I checked to find the closest object it gave me inaccurate results.

Is there any way to accurately check for the distance of two objects that have been normalized with Vector2.Normalize()? Am I even asking the right question?


texts: Calculate the number of palindrome numbers in the given ranges

texts:
I've written a program that calculates all of the palindrome numbers in the given range, but the code is slightly slower than needed. I've tried to improve algorithmic complexity to the best of my abilities, but still  overhead over passing solution (1 second). Is it possible to improve the runtime performance (in time) of the code?

  \$n\$ - number of tests

  \$a, b\$ - range in which I need to calculate number of palindromes

Here is the code:

#include<stdio.h>
int ifpalin(int g)
{
    int rev=0;
    int tmp=g;
    while(tmp>0)
    {
        rev=rev*10+(tmp%10);
        tmp=tmp/10;
    }
    if(rev==g)
        return 1;
    else
        return 0;
}
int findpalin(int a1,int b1)
{
    int sm=0;
    for(int i=a1;i<=b1;i++)
    {
      if  (ifpalin(i)==1)
        sm++;
    }
    printf("%d",sm);
    printf("\n");
    return 0;
}
int main()
{
int a,b,n;
    scanf("%d",&n);
    for(int i=0;i<n;i++)
    {
        scanf("%d",&a);
        scanf("%d",&b);
        findpalin(a,b);
    }
    return 0;
}


texts: Setting combined height and width viewport "breakpoints"

texts:
I'm using JavaScript to handle breakpoints in a single page, non-scrollable application. I want to do various things when changing viewports, such as fire off animations with a JavaScript animation library.

I've assigned the viewports like so:

CodePen

HTML:

CSS:

.box {
  width: 300px;
  height: 300px;
  background-color: red;
}

JS:

var winWidth = '';
var newWinWidth = '';
var winHeight = '';
var newWinHeight = '';

function setWidthBreakpoints(windowWidth) { //matches bootstrap's breakpoints
    if (windowWidth >= 1200) {
        newWinWidth = 'lg';
    } else if (windowWidth >= 992) {
        newWinWidth = 'md';
    } else if (windowWidth >= 768) {
        newWinWidth = 'sm';
    } else {
        newWinWidth = 'xs';
    }
}

function setHeightBreakpoints(windowHeight) {

  if (windowHeight >= 1024) { //more or less arbitrary, may add or remove
      newWinHeight = 'lg';
  } else if (windowHeight >= 480) {
      newWinHeight = 'md';
  } else {
      newWinHeight = 'sm';
  }

}

window.onresize = function () {
    'use strict';
    setWidthBreakpoints($(this).width());
    setHeightBreakpoints($(this).height());

    if (newWinWidth !== winWidth || newWinHeight !== winHeight) {
        onSizeChange();
        winWidth = newWinWidth;
        winHeight = newWinHeight;
    }
};

function onSizeChange() {
    switch(newWinWidth + '|' + newWinHeight) {
    case 'xs|sm':
        $('.box').css('background-color', 'yellow')
    case 'xs|md':
    case 'xs|lg':
        $('.box').css('background-color', 'purple')
    case 'sm|sm':
        $('.box').css('background-color', 'orange')
    case 'sm|md':
    case 'sm|lg':
        $('.box').css('background-color', 'purple')
    case 'md|sm':
        $('.box').css('background-color', 'green')
    case 'md|md':
    case 'md|lg':
        $('.box').css('background-color', 'purple')
    case 'lg|sm':
        $('.box').css('background-color', 'blue')
    case 'lg|md':
    case 'lg|lg':
        $('.box').css('background-color', 'purple')
    }
}

In the above code, we want anything above a small height to be purple. But we have to repeat ourselves to set it four different times.

I will be supporting IE9 with this application so I chose to use JS animation library GSAP for performance and fallback reasons. This is why I am handling my media query breakpoints in Javascript.

How can I build such a scheme to minimize code repetition? Is there a more elegant way to handle combined height and width breakpoints? Am I doing it wrong? I don't foresee many more height viewports being added to this application, and the width ones are tied to Bootstrap so they won't be changing at all.


texts: Using user-defined iterators in user defined aggregators

texts:
suppose i have a class called Sequence which accepts Aggregate functions and i have a class Aggregator which does the aggregation

public abstract class Aggregator{
public abstract Object DoAggregate(List<Object>Elements o);
}

I also have the following interface to Accept an aggregator

Interface IAggregator{
Object AcceptAggregator(Aggregator A);
}

The Sequence class implements the interface IAggregator inorder to accept aggregation

public abstract class Sequence implements  IAggregator, Iterable {
protected Scanner Buf ;
protected  List<Object> Elements;
public abstract void Generate();
public abstract void AcceptTransformer(Transformer T);
public  Sequence(){
this.Buf = new Scanner(System.in);
Elements = new ArrayList<Object>();
}
public  void PrintSequence(){
    System.out.println(Elements);
}
public List<Object> Replace(List<Object> temp){
    this.Elements.clear();
    this.Elements.addAll(temp);
    return this.Elements;
} // A method to copy a sequence to another and return it

@Override
public Iterator GetIterator() {
    return new SequenceIterator();
}

public  class SequenceIterator extends Iterator{ // Inner class
    private  int index =  0;
    public  SequenceIterator(){
        index = 0;
    }
    @Override
    public boolean HasNext() {
        return  index < Sequence.this.Elements.size();
    }

    @Override
    public Object GetNext() {
        return Sequence.this.Elements.get(index++);
    }
}

}

and i have a SumAggregator class

    public class SumAggregate extends Aggregator {
    @Override
    public Object DoAggregate(List<Object> Cur) {
    int Summarize = 0;
    for(Object x: Cur){
        Summarize+=(int)x;  // cast object to int
    }
    return Summarize;
   }
 }

and i have a class  numerical sequence which inherits the class sequence

public class Numerical extends Sequence {
public  Numerical(){
   super(); // Base Class  constructor
}

@Override
public void Generate() { // get the  list from  a file
    File file = new File("Numbers.txt");
    try{
        Scanner ff = new Scanner(file);
        while(ff.hasNextInt()) Elements.add(ff.nextInt());
    }catch (FileNotFoundException e){ // in case file is not found
        e.printStackTrace();
    }
}

@Override
public Object AcceptAggregator(Aggregator Ag) {
    return (Ag.DoAggregate((List)this.Elements)); // Cast it to List
}

}

and the main function looks something like this

     public class Main {
     public static void main(String[] args) {
     Sequence CurrentSequence = new Numerical(); //Create Numerical sequence
     CurrentSequence.Generate();//Generate Numerical Sequence off a file
     CurrentSequence.PrintSequence(); // Print Generated Numerical Sequence
     int Sum = (int)CurrentSequence.AcceptAggregator(new SumAggregate()); //
     Get Summation of Sequence through an aggregator
     System.out.println(Sum);// Print Summation
     Iterator It = CurrentSequence.GetIterator();
     while(It.HasNext()) System.out.print(It.GetNext()+" "); // Iterator
     through list using Iterator
}
}

what is the best way to use the user-defined iterator in the DoAggregate method? I thought of making the SumAggregator as an inner class in the Sequence and extending the SequenceIterator class but i think this approach is flawed because if i have a DataStructure for example then i could use the same method SumAggregator on it just with different itertaion process.

Output//

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 3, 5, 1, 63, 63, 3, 13, 61, 3,
12, 56, 1, 3, 5, 6, 2, 66, 93, 1, 3, 678, 7, 3]
1242
1 2 3 4 5 6 7 8 9 10 11 12 13 3 5 1 63 63 3 13 61 3 12 56 1 3 5 6 2 66 93 1 3
678 7 3


texts: Print all anagrams together in a sentence in Java

texts:
I know a lot of memory is being used, but how do I make this more efficient in space(and time) .

   public class AnagramsTogether {

    public static String getAnagramsTogether(String sentence){

        if(sentence == null || sentence.trim().equals("")) return null;

        String[] words = sentence.split(" ");
        HashMap<String,List<String>> map =new HashMap<String,List<String>>();

        for(String word:words)
        {
            char[] wordArray = word.toCharArray();
            Arrays.sort(wordArray);

            List<String> tempList = map.get(new String(wordArray));
            if(tempList == null) tempList = new ArrayList<String>();
            tempList.add(word);
                            map.put(new String(wordArray),tempList);
        }

        StringBuilder result = new StringBuilder();
        for(Map.Entry<String, List<String>> entry : map.entrySet())
        {

            for(String item:entry.getValue()){
                result.append(item+ " ");
            }
        }

        return result.toString();
    }

    public static void main(String[] args) {
         System.out.println(getAnagramsTogether("cat dog act tac god"));
    }

}


texts:
I am trying to solve the question at

:https://leetcode.com/problems/rotate-list/

Question:

  Given a linked list, rotate the list to the right by k places, where k
  is non-negative.

  Example 1:

  Input:  1->2->3->4->5->NULL, k = 2
  Output: 4->5->1->2->3->NULL

  Explanation:

  rotate 1 steps to the right: 5->1->2->3->4->NULL
  rotate 2 steps to the right: 4->5->1->2->3->NULL

//public class ListNode
//{
//    public int val;
//    public ListNode next;
//    public ListNode(int x) { val = x; }
//}

//k = number of places
//head =Given Linked List

    public  ListNode RotateRight(ListNode head, int k) {
        if (k > 0 && head != null) {
            ListNode tail = head,
            RotatedList = null,
            kthnode = head,
            kthPrevNode = head;
            int listLength = 0;
            while (tail != null) {
                listLength += 1;
                tail = tail.next;
            }

            k = k % listLength;
            if (k == 0 || listLength == 0) {
                return head;
            }

            for (int i = 0; i < listLength - k; i++) {

                kthPrevNode = kthnode;

                kthnode = kthnode.next;

            }

            RotatedList = kthnode;
            kthPrevNode.next = null;
            while (kthnode.next != null) {
                kthnode = kthnode.next;
            }

            kthnode.next = head;
            return RotatedList;

        }

        return head;
    }
}
}

I have passed all test cases but I am looking to improve code efficiency and time complexity,Kindly let me know if there are any bad practices as well


texts: A method that calls multiple async tasks with error handling, done the right way?

texts:
I've got a method, CheckForValue(), that uses named pipes to send a message to another process running locally, and then receive a message from that process, returning a bool indicating if it is equivalent with some value.
I'm concerned that I am not handling CancellationTokens and errors correctly. If there any errors (or timeouts), I just want this method to return false.
Again, I am not concerned with different methods of IPC, or using a single duplex named pipe, etc. My concern is the error handling and the usage of CancellationTokens here.
CheckForValue
public async Task<bool> CheckForValue()
{
    int timeout = 300; //300ms should be plenty of time
    try
    {
        using (var getValueCancellationTokenSource = new CancellationTokenSource())
        {
            var valueTask = GetValueUsingNamedPipe(getValueCancellationTokenSource);
            using (var timeoutCancellationTokenSource = new CancellationTokenSource())
            {
                var completedTask = await Task.WhenAny(valueTask, Task.Delay(timeout, timeoutCancellationTokenSource.Token));
                if (completedTask == valueTask)
                {
                    if (timeoutCancellationTokenSource.Token.CanBeCanceled)
                    {
                        timeoutCancellationTokenSource.Cancel();
                    }

                    var result = valueTask.Result;
                    return (result == "WhatIWant");
                }

                if (getValueCancellationTokenSource.Token.CanBeCanceled)
                {
                    getValueCancellationTokenSource.Cancel ();
                }

                return false;
            }
        }

    }
    catch (Exception)
    {
        return false;
    }
}

GetValueUsingNamedPipe
public async Task<string> GetValueUsingNamedPipe(CancellationTokenSource ct)
{
    var response = "";
    try
    {
        Task sendMsg = SendMessage ("MyMessage", ct);
        await sendMsg;
        response = await Listen(ct);
    }
    catch (Exception)
    {
        return "";
    }
    return response;
}

SendMessage
public async Task SendMessage(string message, CancellationTokenSource ct)
{
    try
    {
        using (var _pipeClientStream = new NamedPipeClientStream(".", "MyPipe", PipeDirection.Out, PipeOptions.Asynchronous))
        {
            await _pipeClientStream.ConnectAsync (1000, ct.Token);

            var writer = new StreamWriter (_pipeClientStream) { AutoFlush = true };
            await writer.WriteLineAsync (message);
            await writer.WriteLineAsync (MessageFooter);
        }
    }
    catch (Exception)
    {
        await Task.FromCanceled(ct.Token);
    }
}

Listen
public async Task<string> Listen(CancellationTokenSource ct)
{
    try
    {
        if (ct.Token.IsCancellationRequested)
        {
            ct.Token.ThrowIfCancellationRequested ();
        }
        using (var _pipeClientStream = new NamedPipeClientStream(".", "MyListenPipe", PipeDirection.In, PipeOptions.Asynchronous, TokenImpersonationLevel.Impersonation))
        {
            await _pipeClientStream.ConnectAsync (ct.Token);
            if (!ct.IsCancellationRequested)
            {
                var sb = new StringBuilder ();
                var reader = new StreamReader (_pipeClientStream);
                do
                {
                    string line = await reader.ReadLineAsync ();

                    if (line == MessageFooter || line == null)
                    {
                        break;
                    }
                    sb.AppendLine (line);

                } while (true);

                return sb.ToString ();
            }
            return "";
        }
    }
    catch (Exception e)
    {
        return "";
    }
}


texts:
I was wondering if below is the correct convention for combining Wai with a Database pool.

What I basically do is, create a pool, partially apply a function of type Pool -> Application and use it to pass it to Warp's run. Does it look ok, or shall I refactor it?

{-# LANGUAGE OverloadedStrings #-}
import Network.Wai
import Network.HTTP.Types
import Network.Wai.Handler.Warp (run)
import Database.MySQL.Simple
import Data.Pool (Pool, createPool, withResource)

newConn = connect defaultConnectInfo
    { connectHost = "db"
    , connectUser = "root"
    , connectPassword = "secret"
    , connectDatabase = "test" }

getPool = createPool newConn close 1 10 5

app :: Pool Connection -> Application
app pool _ respond = do
    withResource pool $ \c -> query_ c "SELECT 1" :: IO [Only Int]
    respond $ responseLBS
        status200
        [("Content-Type", "text/plain")]
        "Hello, Web!"

main :: IO ()
main = do
    putStrLn $ "http://localhost:8080/"
    pool <- getPool
    run 8080 $ app $ pool


texts: Python SQLite class that returns resuls as dict

texts:
I'm using the below function for a small project. This works but I know this is not the best way.

Any help in improving performance (or any native ways supported by Sqlite) is highly appreciated.

class SqliteDB(object):
    """
    SqliteDB:
    ===========================================================================
    Connects to the SQLite Database and executes provided statements.
    """
    def __init__(self, database):
        """
        Sets up environment, connects a database file.
        """
        self.parent_directory = os.path.dirname(os.path.dirname(\
                os.path.abspath(__file__)))
        self.db_path = os.path.join(self.parent_directory, database)
        self.db_connection = sqlite3.connect(self.db_path)
        self.db_cursor = self.db_connection.cursor()

    def execute(self, query, args=''):
        return self.db_cursor.execute(query, args)

    def execute_dict(self, query, args=''):
        """
        execute dict
        =======================================================================
        Same as execute but returns results as a dict containing dict
        mapped with column names.
        """
        result = self.execute(query)
        column_names = []
        return_list = []
        for row in result.description:
            column_names.append(row[0])
        result = result.fetchall()
        for res in xrange(len(result)):
            temp_dict = {}
            for col in xrange(len(column_names)):
                temp_dict.update({column_names[col]:result[res][col]})
            return_list.append(temp_dict)
        dict1 = {'result':return_list}
        return dict1


texts: Possible SQL injection vulnerability searching for a product by ID?

texts:
I want to be sure that this isn't vulnerable to SQL injection. If yes, then how can it be improved?

$pid = $_REQUEST['product_id'];
$query1 = "SELECT * FROM products WHERE id = '"
  . $pid . "'";

$result = mysql_db_query($dbname, $query1) or die("Failed Query of " . $query1);
$thisrow=mysql_fetch_row($result);
if ($thisrow) {
  echo "The Product was found.";
}
else
{
  echo "The Product was not found.";
}


texts:
I'm using spritekit, using on touch to detect what the users has tapped, ie., no collisions, etc.

I have an array of sprite nodes which in effect is a multi-state boolean switch for now the user can only select one node to be active at a time so the logic looks like:

Node A,  Node B, Node C .........Node M
off       off      off        initial
on        off      off        user touches node A
off       off      on          user touches node C

This code is my working template and would like to reduce a lot of this boilerplate down to something reasonable.

I'm looking for ways that are either faster, more the "Apple Way", more OOP.

    var temp1:SKSpriteNode = SKSpriteNode()
  override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
  {
    if let touch = touches.first
    {
      let tappedNodes:[sk_Node] = nodes(at: touch.location(in: self) )

      for node in tappedNodes
      {
    switch node.name!
        {
        case "level_1":
          pushd(node: node)
          node.run( sk_Action.animate(with: [sk_Texture(imageNamed: "level_1_selected") ], timePerFrame: K1_4.f64_t) )

          temp1 = childNode(withName: "level_2")!
          temp1.run(sk_Action.animate(with: [sk_Texture(imageNamed: "level_2_normal") ], timePerFrame: K1_4.f64_t) )
          popd(node:temp1)

          temp1 = SKSpriteNode()
          temp1 = childNode(withName: "level_3")!
          temp1.run( sk_Action.animate(with: [sk_Texture(imageNamed: "level_3_normal") ], timePerFrame: K1_4.f64_t) )
          popd(node:temp1)

    case "level_2":
      pushd(node: node)
      node.run( sk_Action.animate(with: [sk_Texture(imageNamed: "level_2_selected") ], timePerFrame: K1_4.f64_t) )

      temp1 = childNode(withName: "level_1")!
      temp1.run( sk_Action.animate(with: [sk_Texture(imageNamed: "level_1_normal") ], timePerFrame: K1_4.f64_t) )
      popd(node:temp1)

      temp1 = SKSpriteNode()
      temp1 = childNode(withName: "level_3")!
      temp1.run( sk_Action.animate(with: [sk_Texture(imageNamed: "level_3_normal") ], timePerFrame: K1_4.f64_t) )
      popd(node:temp1)

    case "level_3":
      pushd(node: node)
      node.run( sk_Action.animate(with: [sk_Texture(imageNamed: "level_3_selected") ], timePerFrame: K1_4.f64_t) )

      temp1 = childNode(withName: "level_2")!
      temp1.run( sk_Action.animate(with: [sk_Texture(imageNamed: "level_2_normal") ], timePerFrame: K1_4.f64_t) )
      popd(node:temp1)

      temp1 = SKSpriteNode()
      temp1 = childNode(withName: "level_1")!
      temp1.run( sk_Action.animate(with: [sk_Texture(imageNamed: "level_1_normal") ], timePerFrame: K1_4.f64_t) )
      popd(node:temp1)

} } } }

pushd and popd are SKActions that do some simple scaling up and down.


texts: Loading dictionary using trie in C very slow with large data set

texts:
The code below works for very small dictionary files I used to test (two words).  However when I run this using a more typical dictionary file, my machine slows to the point of near crash.  I would like a review of what the potential bottleneck may be which I believe to be in the load() function. Of course, general comments are also welcomed if they may help with optimization and overall performance.

typedef struct node

{
    bool is_word;
    struct node* children[27];
}
node;

node* root;

int nwords = 0;

/**
* Returns true if word is in dictionary else false.
*/

bool check(const char* word)
{
    node* current = root;

    int i = 0;

    while(word[i] != '\0')
    {
        int letter = tolower(word[i]);

        if (letter == '\'')
        {
            return false;
        }

        if (current->children[letter-'a'] != NULL)
        {
            current = current->children[letter-'a'];
            i++;
        }

        else
        {
           return false;
        }
    }

    if (current->is_word == true)
    {
       return true;

    }

    return false;
 }

/**
 * Loads dictionary into memory.  Returns true if successful else false.
*/

bool load(const char* dictionary)
{

    FILE* dict = fopen(dictionary, "r");

    if(dict == false)
    {
       return false;
    }

    //initialize nodes

    root = calloc(27,sizeof(node));
    node* current = NULL;

    int c = 0;

    while(fgetc(dict) != EOF)
   {
       fseek(dict, -1, SEEK_CUR); //go back one byte to beginning of word
       current = root; //set index to root

       for(c = fgetc(dict); c != '\n'; c = fgetc(dict)) //iterate through word
       {
            if(current->children[c-'a'] == NULL)
            {
                current->children[c-'a'] = calloc(27,sizeof(node));
                current = current->children[c-'a'];
            }
            else
            {
                current = current->children[c-'a'];
            }
        }
        current->is_word = true; //once line break reached end the word
        nwords++;
    }

    fclose(dict);
    return true;
}

/**
* Returns number of words in dictionary if loaded else 0 if not yet loaded.
*/

unsigned int size(void)
{
    return nwords;
}

/**
 * Unloads dictionary from memory.  Returns true if successful else false.
 */

void freeNode(node* current)
{
    for (int i = 0; i < 27; i++)
    {
        if(current->children[i] != NULL)
        {
            freeNode(current->children[i]);
        }
    }
    free(current);
}

bool unload(void)
{
    freeNode(root);
    return true;
}


texts: Swapping adjacent nodes of a linked list

texts:
I just have a small question.  The code I wrote works well for the problem. But is it the best way, or can we make it better?

struct node * swapAdjacent(struct node * list)
{
   struct node * temp,*curr,*nextNode;
   temp = list;
   curr = temp->next;
   if(curr == NULL)
      return temp;
   nextNode = curr->next;
   curr->next = temp;
   if(nextNode == NULL)
   {
       temp->next = nextNode;
       return curr;
   }
   temp->next = swapAdjacent(nextNode);
   return curr;
}


texts: Fluent interface for manipulating employee records

texts:
I wanted to try experimenting with fluent interface design in the C programming language. That's why I wanted to ask you, Dear Code Review users, comments on the way I have implement this simple employee record interface.

Please note that for maximum simplicity I am resorting to as simple data structures as possible.

#include <stdio.h>
#include <assert.h>
/* if this weren't just an example I'd make a linked list */
#define MAX_EMPLOYEE_COUNT 10

/* global this pointer, there is no way around this */
void* this;

typedef struct Employee {
    struct Employee* (*set_salary)(int);
    struct Employee* (*set_employee_id)(int);
    char* name;
    int salary;
    int employee_id;
} Employee;

Employee* do_set_salary(int s)
{
    ((Employee*)this)->salary = s;
    return this;
}

Employee* do_set_employee_id(int id)
{
    ((Employee*)this)->employee_id = id;
    return this;
}

typedef struct Record {
    Employee* (*add_employee)(char*);
    Employee employees[MAX_EMPLOYEE_COUNT];
    int cnt;
} Record;

Employee* do_add_employee(char *n)
{
    Record* this_record = (Record*)this;
    assert(this_record->cnt < MAX_EMPLOYEE_COUNT);
    this_record->employees[this_record->cnt].set_salary = do_set_salary;
    this_record->employees[this_record->cnt].set_employee_id =
        do_set_employee_id;
    this_record->employees[this_record->cnt].name = n;
    this = &this_record->employees[this_record->cnt];
    this_record->cnt++;
    return this;
}

void init_record(Record* r)
{
    r->cnt = 0;
    r->add_employee = do_add_employee;
}

Record* edit(Record* r)
{
    this = r;
    return r;
}

void print_record(Record* r)
{
    int i;
    for (i = 0; i < r->cnt; i++) {
        printf("%s, salary %d, id %d\n",
               r->employees[i].name,
               r->employees[i].salary,
               r->employees[i].employee_id);
    }
}

int main(void)
{
    Record record;
    init_record(&record);

    /* behold, fluent interface design! */
    edit(&record)->
        add_employee("Alice")->
        set_salary(1500)->
        set_employee_id(10201);

    edit(&record)->
        add_employee("Bob")->
        set_salary(2000)->
        set_employee_id(10202);

    print_record(&record);

    return 0;
}


texts: String substitutions in ruby and coding style

texts:
I wrote a short ruby script to generate various screenshots, and event though I am not completely new to ruby I rarely use it.

Full script (41 LOC): https://gist.github.com/1229115

The string substitutions irritate me. They don't look quite right - much too ugly for a beautiful and concise language like ruby. Am I overdoing it? What alternatives are there?

Here is the lines I am concerned about (for context, please take a look at the gist):

# assemble file name
fname = "#{directory}/#{prefix}-#{timestamp}-#{commit}-#{size[:width]}x#{size[:height]}.png"

# create command line stuff
call = "#{macruby_exe} #{snapper} \
        --width #{size[:width]} --height #{size[:height]} #{url} #{fname}"

# now call it
system call

# just to show the progress (and the file sizes)
puts "#{fname} (#{File.size?(fname) / 1024}kB)"

Just to illustrate the script, the output usually looks like:

screenies/screenshot-1316535022-0b5c7967887481deb17bcd9039cd3fe0ac4540d4-640x960.png (95kB)
screenies/screenshot-1316535022-0b5c7967887481deb17bcd9039cd3fe0ac4540d4-800x480.png (62kB)
screenies/screenshot-1316535022-0b5c7967887481deb17bcd9039cd3fe0ac4540d4-800x600.png (78kB)
   ^          ^          ^                          ^                       ^
   |          |          |                          |               ________|______
   |          |          |                          |              |               |
directory   prefix     timestamp                  commit    size[:width] x size[:height]


texts:
I've created a very small script in vba to parse Title from almost any website. I've checked it with few websites and it is providing with the accurate results. I used split function on responsetext to achieve the result. Websites should be placed in column A and the results will be displayed in column B adjacent to each site. I tried to make it flawless.

Sub Title_Data()
Dim http As New MSXML2.XMLHTTP60

For Each cel In Range("A1:A" & Cells(Rows.Count, 1).End(xlUp).row)
    With http
        .Open "GET", cel.Value, False
        .send

        L = L + 1
        Cells(L, 2) = Split(Split(.responseText, "<title>")(1), "</title>")(0)
    End With
Next cel
Set http = Nothing
End Sub


texts:
Here is my implementation of arg max in Scala. q_table_test.txt contains:
["---------,'0','0','0','0','0','0','0','0','0', "X--------,'0.', '0.1', '0.1', '0.1', '0.1', '0.1', '0.1', '0.1', '0.1'"]

For example the String ---------,'0','0','0','0','0','0','0','0','0' maps to key: "---------" , with values: [0,0,0,0,0,0,0,0,0]
After filtering values which are not valid I return the arg max of values from the list of positions.
Coming from a java background, what is a more functional programming principled method of implementing arg max?
Should the list filtering be contained in a separate function?
The QTable apply() method parses reads a file and returns Map[String , List[Double]] . It is evaluated lazily as it should just be evaluated once.
I think the use of apply in lazy val is not correct ?
Is this a 'good' method of finding the arg max value ?:
val qValues = bindings.get(state).getOrElse(List.fill(8)(0.0)).zipWithIndex
val availableQValueBoardPositions = qValues.filter(f => remainingPositions.contains(f._2))

Complete code:
import java.io.InputStream
import play.api.Environment

case class QTable(bindings: Map[String, List[Double]]) {

  def getArgMaxValue(state: String, remainingPositions: List[Int]) = {
    val qValues = bindings.get(state).getOrElse(List.fill(8)(0.0)).zipWithIndex
    val availableQValueBoardPositions = qValues.filter(f => remainingPositions.contains(f._2))
    availableQValueBoardPositions.maxBy(x => x._1)._2
  }

}

object QTable {

  private def getQTableFromFile(filename: String) = {
    lazy val env = Environment.simple()
    lazy val is: InputStream = Option(env.classLoader.getResourceAsStream(filename)).get
    scala.io.Source.fromInputStream(is).mkString
  }

  private def cleanData(data: String): String = {
    data.replace("\"", "").replace("\'", "").replace("[", "").replace("]", "")
  }

  def apply(filename: String) = {

    val number_attributes_per_instance = 10;

    val qtable = getQTableFromFile(filename)

    lazy val cleanedQtable: String = cleanData(qtable)
    lazy val dataInstances: List[List[String]] = cleanedQtable.split(",").toList.grouped(number_attributes_per_instance).toList
    lazy val stateIdValues: List[String] = dataInstances.map(m => m.head.trim)
    lazy val stateAttributeValues: List[List[Double]] = dataInstances.map(m => m.tail.map(x => x.toDouble))
    lazy val policy: QTable = new QTable(stateIdValues.zip(stateAttributeValues).toMap)

    policy
  }

}

object ArgMain extends App {
  print(QTable("q_table_test.txt").getArgMaxValue("---------", List(1, 2, 3)))
}


texts:
I just want some advice regarding code style and best practices. Also I want to know if I'm using constant declaration and closures properly.

This code is used to get the data from here http://consulta.siiau.udg.mx/wco/sspseca.forma_consulta

which is the schedules for classes on my ex-school.

<?php
require __DIR__ . '/vendor/autoload.php';
use Symfony\Component\DomCrawler\Crawler;
use Goutte\Client;

class Siiau {
  const URL = 'http://consulta.siiau.udg.mx/wco/sspseca.forma_consulta';
  const SCHEDULE_KEYS = ['time', 'days', 'building', 'classroom'];
  const TIME_KEYS = ['start', 'finish'];
  const KEYS = ['nrc', 'key', 'topic', 'section', 'credits',
                'limit', 'available', 'schedule', 'professor'];
  const ENTRY_OFFSET = 3;
  const SCHEDULE_OFFSET = 4;

  private $client;
  public $entries;

  public function __construct() {
    $this->client = new Client();
    $this->entries = [];
  }

  public function parse()
  {
    $submitText = 'Consultar';
    $selector = 'body > style + table > tr';
    $form = $this
      ->client
      ->request('POST', self::URL)
      ->selectButton($submitText)->form();
    $crawler = $this->client->submit($form);
    $entries = $crawler
      ->filter($selector)
      ->slice(self::ENTRY_OFFSET);
    $this->entries = $entries->each(function(Crawler $entry, $i)
    {
      $values = $entry
        ->children()
        ->slice(1)
        ->each($this->parseEntry());
      return array_combine(self::KEYS, $values);
    });
  }

  private function parseEntry()
    {
    return function(Crawler $value, $i)
    {
      if (self::KEYS[$i] == 'schedule') {
        $value = $this->parseSchedule($value);
      } elseif (self::KEYS[$i] == 'professor') {
        $value = $this->parseProfessor($value);
        $value = preg_replace('/(\s)+/', ' ', $value->text());
      } else {
        $value = preg_replace('/(\s)+/', ' ', $value->text());
      }
      return $value;
    };
  }

  private function parseSchedule($schedules)
  {
    $selector = 'table > tr';
    $schedules = $schedules
      ->filter($selector)
      ->each(function(Crawler $row, $i) {
        $row = $row
          ->children()
          ->slice(1, self::SCHEDULE_OFFSET)
          ->each(function(Crawler $cell, $i) {
            $value = $cell->text();
            if (self::SCHEDULE_KEYS[$i] == 'days') {
              $value = str_split(preg_replace('/([\.\s])+/', '', $value));

            } elseif (self::SCHEDULE_KEYS[$i] == 'time') {
              $value = explode('-', $value);
              $value = array_combine(self::TIME_KEYS, $value);
            }
            return $value;
          });
        return array_combine(self::SCHEDULE_KEYS, $row);
      });
    return $schedules;
  }
  private function parseProfessor($professor)
  {
    $selector = 'td:last-child';
    return $professor->filter($selector);
  }
}

$siiau = new Siiau();
$siiau->parse();
var_dump($siiau->entries);
?>


texts:
I've created a library, TomHart/laravel-route-from-model, and looking to get a review on it. As well as the usual code review, I'm also looking for feedback from a users point of view, if you were to use the library, is there anything extra you wish it did, anything different etc.

The key class is:

<?php
namespace TomHart\Routing;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Routing\Router;
use Illuminate\Routing\UrlGenerator;
use Symfony\Component\Routing\Exception\RouteNotFoundException;
class RouteBuilder
{
    /**
     * Get the router instance.
     *
     * @return Router
     */
    private function getRouter(): Router
    {
        return app('router');
    }
    /**
     * Get the UrlGenerator.
     *
     * @return UrlGenerator
     */
    private function getUrlGenerator(): UrlGenerator
    {
        return app('url');
    }
    /**
     * This allows a route to be dynamically built just from a Model instance.
     * Imagine a route called "test":
     *      '/test/{name}/{id}'
     * Calling:
     *      routeFromModel('test', Site::find(8));
     * will successfully build the route, as "name" and "id" are both attributes on the Site model.
     *
     * Further more, once using routeFromModel, the route can be changed. Without changing the call:
     *      routeFromModel('test', Site::find(8));
     * You can change the route to be:
     *      '/test/{name}/{id}/{parent->relationship->value}/{slug}/{otherParent->value}'
     * And the route will successfully change, as all the extra parts can be extracted from the Model.
     * Relationships can be called and/or chained with "->" (Imagine Model is a Order):
     *      {customer->address->postcode}
     * Would get the postcode of the customer who owns the order.
     *
     * @param string  $routeName The route you want to build
     * @param Model   $model     The model to pull the data from
     * @param mixed[] $data      Data to build into the route when it doesn't exist on the model
     *
     * @return string The built URL.
     */
    public function routeFromModel(string $routeName, Model $model, array $data = [])
    {
        $router = $this->getRouter();
        $urlGen = $this->getUrlGenerator();
        $route = $router->getRoutes()->getByName($routeName);
        if (!$route) {
            throw new RouteNotFoundException("Route $routeName not found");
        }
        $params = $route->parameterNames();
        foreach ($params as $name) {
            if (isset($data[$name])) {
                continue;
            }
            $root = $model;
            // Split the name on -> so we can set URL parts from relationships.
            $exploded = collect(explode('->', $name));
            // Remove the last one, this is the attribute we actually want to get.
            $last = $exploded->pop();
            // Change the $root to be whatever relationship in necessary.
            foreach ($exploded as $part) {
                $root = $root->$part;
            }
            // Get the value.
            $data[$name] = $root->$last;
        }
        return rtrim($urlGen->route($routeName, $data), '?');
    }
}


texts: A service that posts JSON to a server and works with responses

texts:
extern crate serde;

use serde::{Deserialize, Serialize};

use serde_json::json;

use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use std::io::{BufReader};
use std::time::Duration;

const NER_SERVER: &'static str = "http://127.0.0.1:5000/parse";

#[derive(Serialize, Deserialize)]
struct Article {
    url: String,
    text: String,
    id: String,
}

#[derive(Serialize, Deserialize)]
struct NER {
    begin: u32,
    end: u32,
}

fn run() -> Result<u64, Box<Error>> {
    let file = File::open("data/test").unwrap();
    let client = reqwest::blocking::Client::builder()
        .timeout(Duration::from_secs(100))
        .build()?;
    let reader = BufReader::new(file);
    let mut count : u64 = 0;
    for line in reader.lines() {
        let article: Article = serde_json::from_str(&line.unwrap_or_default())?;
        let ners: Vec<NER> = client.post(NER_SERVER)
            .json(&json!({"data": article.text}))
            .send()?.json()?; // TODO change to async
        for item in ners.iter() {
            println!("{} {}", item.begin, item.end);
        }
        count = count + 1;
    }
    Ok(count)
}

fn main() {
    match run() {
        Ok(e) => println!("{}", e),
        Err(e) => println!("{:#}", e)
    }
}

Piggyback question: How to set up a general JSON schema for the project. Currently, in this [line][2], the schema is supposed to match this [line][3], which I think is extremely ugly, but could not think of another way to shape it.


texts:
I seek a fast implementation of (x / y).imag, where x, y are complex 2D arrays (PyTorch tensors already on GPU). My approach is to move computation to a CUDA kernel via cupy, interfacing C and Python. Requirements:

Faster than (x / y).imag
Using same or less memory than (x / y).imag
Output is same as (x / y).imag within float precision
#includes must be supported by CuPy (which is largely limited to standard CUDA libraries afaik)

My attempt:
extern "C" __global__
void cdiv_imag(float x[240][240000][2], float y[240][240000][2],
               float out[240][240000]) {
    int i = blockIdx.x * blockDim.x + threadIdx.x;
    int j = blockIdx.y * blockDim.y + threadIdx.y;
    if (i >= 240 || j >= 240000)
        return;

    float A = x[i][j][0];
    float B = x[i][j][1];
    float C = y[i][j][0];
    float D = y[i][j][1];

    out[i][j] = (B*C - A*D) / (C*C + D*D);
}

This uses half the memory, since x / y yields a temp array of reals & imaginary, but is still ultimately slower per my benchmarks on GTX 1070:
0.02320581099999992 sec (avg of 1000 runs)
0.01924530900000002 sec (avg of 1000 runs)

Full code; Win 10 x64, Python 3.7.9, CuPy 8.3.0, PyTorch 1.8.0.
import torch
import numpy as np
import cupy as cp
from collections import namedtuple
from timeit import timeit

def timer(fn, number=1000):
    print(timeit(fn, number=number) / number)

Stream = namedtuple('Stream', ['ptr'])

#%%##################################################################
kernel = cp.RawKernel(r'''
extern "C" __global__
void cdiv_imag(float x[240][240000][2], float y[240][240000][2],
               float out[240][240000]) {
    int i = blockIdx.x * blockDim.x + threadIdx.x;
    int j = blockIdx.y * blockDim.y + threadIdx.y;
    if (i >= 240 || j >= 240000)
        return;

    float A = x[i][j][0];
    float B = x[i][j][1];
    float C = y[i][j][0];
    float D = y[i][j][1];

    out[i][j] = (B*C - A*D) / (C*C + D*D);
}

''', 'cdiv_imag')
#%%##################################################################
shape = (240, 240000)
x = torch.randn(shape, dtype=torch.complex64, device='cuda')
y = torch.fliplr(x.clone().detach())

threadsperblock = (32, 32)
blockspergrid_x = int(np.ceil(y.shape[0] / threadsperblock[0]))
blockspergrid_y = int(np.ceil(y.shape[1] / threadsperblock[1]))
blockspergrid = (blockspergrid_x, blockspergrid_y)

#%%##################################################################
def f1(x, y):
    out = torch.zeros(shape, dtype=torch.float32, device='cuda')
    xv, yv = torch.view_as_real(x), torch.view_as_real(y)
    kernel(
        grid=blockspergrid, block=threadsperblock,
        args=[xv.data_ptr(), yv.data_ptr(), out.data_ptr()],
        stream=Stream(ptr=torch.cuda.current_stream().cuda_stream))
    return out

def f2(x, y):
    return (x / y).imag

# ensure outputs agree within float precision
adiff = torch.abs(f1(x, y) - f2(x, y))
assert adiff.mean() < 1e-8

# dummy run to factor out caching & warm up GPU
for _ in range(2000):
  f1(x, y)
  f2(x, y)

#%%##################################################################
timer(lambda: f1(x, y))
timer(lambda: f2(x, y))


texts:
I have a function like this:

BOOL CGameData::GetCheckSum(BYTE o_byObjCheckSum[32], int *o_pnFileSize, char* pFilePath)
{
memset(o_byObjCheckSum, 0x00, 32);
*o_pnFileSize   = 0;

UINT uiCheckSum = 0;
if(strlen(pFilePath) <=0)
{
return FALSE;
}
FILE *fp;
fp=fopen(pFilePath, "rb");
if(NULL == fp)
{
    return FALSE;
}
fseek( fp, 0L, SEEK_END );
long lFileSize = ftell( fp );
*o_pnFileSize = lFileSize;
fseek( fp, 0L, SEEK_SET );

BYTE *pFileData = new BYTE [lFileSize];
fread(pFileData, lFileSize, 1, fp);
sha256_encode(pFileData, lFileSize, o_byObjCheckSum);

fclose(fp);
delete [] pFileData;

return TRUE;
}

How can I make this faster?

If it will help, this function is called here:

    STRNCPY_MEMSET(szResDirectoryPath, RESOBJ_DIRECTORY_PATH, MAX_PATH);
    if(FALSE == GetAllFileNameList(&vectFileNameList, szResDirectoryPath))
    {
        g_pFieldGlobal->WriteSystemLogEX(TRUE, "[ERROR] LoadResObjCheckList_ error !!, Directory(%s)\r\n", szResDirectoryPath);
        return FALSE;
    }

    nCnt = vectFileNameList.size();
    for(i=0; i < nCnt; i++)
    {
        SRESOBJ_CHECKSUM    resObjCheckSum;
        CGameData           tmMapGameData;
        char                szFileFullPath[MAX_PATH];
        MEMSET_ZERO(&resObjCheckSum, sizeof(resObjCheckSum));

        STRNCPY_MEMSET(resObjCheckSum.szResObjFileName, vectFileNameList[i].c_str(), SIZE_MAX_RESOBJ_FILE_NAME);
        _strupr(resObjCheckSum.szResObjFileName);
        sprintf(szFileFullPath, "%s/%s", szResDirectoryPath, resObjCheckSum.szResObjFileName);

        if(tmMapGameData.GetCheckSum(resObjCheckSum.byDigest, &resObjCheckSum.nFileSize, szFileFullPath))
        {
            m_mapResObjCheckSumList.insert(pair<string,SRESOBJ_CHECKSUM>(resObjCheckSum.szResObjFileName, resObjCheckSum));
        }
    }


texts: Deduplicate << operator implementation on inheritance

texts:
I have the following working code:
person.h
#ifndef PERSON_H
#define PERSON_H

#include <iostream>
#include <string>

class Person {
private:
    std::string firstName;
    std::string middleName;
    std::string lastName;

public:
    Person() = default;
    Person (std::string pFirstName, std::string pMiddleName, std::string pLastName);
    Person (std::string pFirstName, std::string pLastName);

    std::string getFirstName();
    void setFirstName(std::string pFirstName);
    std::string getLastName() const;
    void setLastName(std::string pLastName);
    std::string toString() const;

    friend std::ostream& operator<<(std::ostream& target, Person const & person);
};

#endif

person.cpp
#ifndef __person__
#define __person__

#include <iostream>
#include <string>

#include "person.h"

using std::string;
using std::ostream;

Person::Person (string pFirstName, string pMiddleName, string pLastName)
: firstName(pFirstName), middleName(pMiddleName), lastName(pLastName)
{
}

Person::Person (string pFirstName, string pLastName)
: firstName(pFirstName), middleName(""), lastName(pLastName)
{
}

string Person::getFirstName ()
{
    return firstName;
}

void Person::setFirstName (string pFirstName)
{
    firstName = pFirstName;
}

string Person::getLastName () const
{
    return lastName;
}

void Person::setLastName (string pLastName)
{
    lastName = pLastName;
}

string Person::toString () const
{
    if (middleName == "")
        return firstName + " " + lastName;

    return firstName + " " + middleName + " " + lastName;
}

ostream& operator<< (ostream& target, Person const & source)
{
    target << source.toString();
    return target;
}

#endif

tweeter.h
#ifndef TWEETER_H
#define TWEETER_H

#include <string>

#include "person.h"

class Tweeter
: public Person
{
private:
    static int gid;
    int id;
    std::string twitterHandle;

public:
    Tweeter(std::string pFirstName, std::string pMiddleName, std::string pLastName, std::string pTwitterHandle);
    Tweeter(std::string pFirstName, std::string pLastName, std::string pTwitterHandle);
    std::string toString() const;
    friend std::ostream& operator<< (std::ostream& target, Tweeter const & source);
};

#endif

tweeter.cpp
#ifndef __tweeter__
#define __tweeter__

#include <iostream>

#include "tweeter.h"

using std::ostream;
using std::string;
using std::to_string;

int Tweeter::gid = 0;

Tweeter::Tweeter(string pFirstName, string pMiddleName, string pLastName, string pTwitterHandle)
: Person(pFirstName, pMiddleName, pLastName), id(gid), twitterHandle(pTwitterHandle)
{
    gid++;
}

Tweeter::Tweeter(string pFirstName, string pLastName, string pTwitterHandle)
: Tweeter(pFirstName, "", pLastName, pTwitterHandle)
{
}

string Tweeter::toString() const
{
    return "[" + to_string(id) + "] " + Person::toString() + " (" + twitterHandle + ")";
}

ostream& operator<< (ostream& target, Tweeter const & source)
{
    target << source.toString();
    return target;
}

#endif

As you can see, I have a nearly duplicate implementation for the << operator in the subclass Tweeter. I had to do that, since, if I just use the << operator implementation inherited from Person, C++ would silently cast the Tweeter instance as Person as per the operator function's signature and call Person::tostring() instead of Tweeter::toString().
Is it possible to just have one implementation of the << operator that can be inherited without override and thusly code duplication?


texts:
A few hours ago I posted a similar question but this is a follow-up, I have revised the code and added and removed certain lines of code and hopefully improved it a bit, I just brought it here for a final cleaning, can anyone notice anything than can be improved even more? Some of the code has been totally changed such as the way I wrote the uptime string

var consoleTitleString = string.Format("{0} / {1}, {2}, and {3}",
                    projectName,
                    serverUptime.Days + " day" + (serverUptime.Days != 1 ? "s" : ""),
                    serverUptime.Hours + " hour" + (serverUptime.Hours != 1 ? "s" : ""),
                    (StaticSettings.includeSecondsInUptimeString) ? serverUptime.Minutes +
                    " minute" + (serverUptime.Minutes != 1 ? "s" : "") + " and " +
                    serverUptime.Seconds + " second" + (serverUptime.Seconds != 1 ? "s" : "") :
                    serverUptime.Minutes + " and minute" + (serverUptime.Minutes != 1 ? "s" : "")
                    );

I feel its a bit squeezed in, is there a way to make it a bit more clean without the need of an if statement?

Just a few of the improvements I've made

Removed field comments
Improved long-lined code
Removed useless code

using Faze.Other.App;
using log4net;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Faze.Other.Util.Console
{
    class ConsoleWorker : IDisposable
    {
        private readonly Timer consoleWorkerTimer;
        private readonly int consoleWorkerInterval;
        private readonly ILog classLogger;

        public ConsoleWorker()
        {
            consoleWorkerInterval = 1000;
            classLogger = LogManager.GetLogger(typeof(ConsoleWorker));
            consoleWorkerTimer = new Timer(timerElapsed, null, TimeSpan.FromMilliseconds(consoleWorkerInterval), TimeSpan.FromMilliseconds(consoleWorkerInterval));
        }

        /// <summary>
        /// Handles the timers callback once elapsed.
        /// </summary>
        /// <param name="timerObject">ConsoleWorker timer's object.</param>
        private void timerElapsed(object timerObject)
        {
            var serverInfo = Faze.getServer().getServerInformation();

            if (serverInfo.hasStarted())
            {
                if (StaticSettings.advancedLoggingWhenDebugging && Debugger.IsAttached)
                    classLogger.Info("ConsoleWorker has elapsed -> " + DateTime.Now.ToLongTimeString());

                TimeSpan serverUptime = DateTime.Now - serverInfo.getStartedTime();

                var projectName = serverInfo.getProjectName();

                var consoleTitleString = string.Format("{0} / {1}, {2}, and {3}",
                    projectName,
                    serverUptime.Days + " day" + (serverUptime.Days != 1 ? "s" : ""),
                    serverUptime.Hours + " hour" + (serverUptime.Hours != 1 ? "s" : ""),
                    (StaticSettings.includeSecondsInUptimeString) ? serverUptime.Minutes +
                    " minute" + (serverUptime.Minutes != 1 ? "s" : "") + " and " +
                    serverUptime.Seconds + " second" + (serverUptime.Seconds != 1 ? "s" : "") :
                    serverUptime.Minutes + " and minute" + (serverUptime.Minutes != 1 ? "s" : "")
                    );

                System.Console.Title = consoleTitleString;
            }
        }

        public void Dispose()
        {
            consoleWorkerTimer.Dispose();
        }
    }
}

One final thing, Someone on the old post said use CamalCase because I would seem like I'm coding JavaScript otherwise, is this a do do and a don't don't go against thing or is that just his personal preference?


texts:
Are there any good ways to make this createIndexBlock() method shorter?

It looks wastefully long. I have many tables. I don't like to make these kinds of methods.

import (
    "database/sql"
    _ "github.com/go-sql-driver/mysql"
)

var db, _ = sql.Open("mysql", "xxx:xxx@(database:3306)/xx")

func createIndexBlock(blockHash string) int64 {

    rows, err := db.Query("SELECT id FROM index_blocks WHERE `hash`=? LIMIT 1", blockHash)
    if err != nil {
        panic(err.Error())
    }

    for rows.Next() {
        var id int64
        err := rows.Scan(&id)
        if err != nil {
            panic(err.Error())
        }
        rows.Close()
        return id
    }

    result, err := db.Exec("INSERT INTO index_blocks (`hash`) values (?)", blockHash)
    if err != nil {
        panic(err.Error())
    }

    id, err := result.LastInsertId()
    if err != nil {
        panic(err.Error())
    }

    return id
}


texts:
I have 2 functions used for parsing a house number and I think these can both be improved.

Any suggestions?

input:

45a - 47b

  or

45a bis 47b

output:

45,a,47,b

public static string[] HausnummerAufteilen(string hausNummer)
    {
        string[] result = new string[4];
        string[] resultVon = new string[2];
        string[] resultBis = new string[2];

        resultVon[0]  = string.Empty;
        resultVon[1]  = string.Empty;
        resultBis[0]  = string.Empty;
        resultBis[1]  = string.Empty;

        int pos1, pos2;
        pos2 = 0;
        pos1 = hausNummer.IndexOf("bis");
        if (pos1 != -1)
        {
            pos2 = pos1 + 3;
        }
        else
        {
            pos1 = hausNummer.IndexOf("-");
            if (pos1 != -1)
                pos2 = pos1 + 1;
        }

        if (pos1 > 0)
        {
            resultVon = HausnummerBuchst(hausNummer.Substring(0, pos1).Trim());
            resultBis = HausnummerBuchst(hausNummer.Substring(pos2, hausNummer.Length - pos2).Trim());
        }
        else
            resultVon = HausnummerBuchst(hausNummer);

        List<string> list = new List<string>();
        list.AddRange(resultVon);
        list.AddRange(resultBis);
        result = list.ToArray();

        return result;
    }

    public static string[] HausnummerBuchst(string hauseNummer)
    {
        string[] result = new string[2];

        result[0] = string.Empty;
        result[1] = string.Empty;

        int iPos;
        int testInt;
        bool bFound = false;

        for (iPos = 0; iPos < hauseNummer.Length; iPos++)
        {

            if (!int.TryParse(hauseNummer[iPos].ToString() ,out testInt))
            {
                bFound = true;
                break;
            }
        }

        if (bFound)
        {
            result[0] = hauseNummer.Substring(0, iPos).Trim();
            result[1] = hauseNummer.Substring(iPos, hauseNummer.Length - iPos).Trim();
        }
        else
            result[0] = hauseNummer;

        return result;

    }


texts: Initial stages of MVP, is the bootstrap file efficient coding

texts:
I am attempting to put my new OOP skills to the test and am eventually going to build a simple OOP login/registration system.

However as I am making use of OOP I have decided to make my own simple MVC.

Here is my layout of my directory

root-directory/
   .htaccess
   app/
      Config/
      Controllers/
      Models/
      Views/
      Lib/
        Vendor/
        composer.json
      bootstrap/
         app.php
   public/
      assets/
        js/
        css/
        img/
      index.php
      .htaccess

I have my app file in the Bootstrap folder I have written my code in a manor so it checks if the _GET super variable has anything in it, if it doesn't then set the $this->controller = 'home' and set the $this->method = 'index'

Here is my Bootstrap/app.php file

<?php

namespace App\Bootstrap;

require __DIR__ . '/../Lib/vendor/autoload.php';

class App
{

    private $controller;
    private $method;
    private $requests;

    public function __construct($requests)
    {
        $this->requests = $requests;

        $this->requests = $this->requests['PATH_INFO'];

        $this->requests = explode('/',$this->requests);

        if ($this->requests[0] == '')) {

            $this->controller = 'home';

        } else {

            $this->controller = $this->requests[0];

        }

        if ($this->requests[1] == '' ) {

            $this->method = 'index';

        } else {

            $this->method = $this->requests[1];

        }

        echo $this->controller;
        echo '
';
        echo '
';
        echo $this->method;

        die();

    }
}

Here is my index.php file

<?php
error_reporting(E_ALL);
ini_set('display_errors',1);

require __DIR__ . '/../app/Bootstrap/app.php';

$b = new \App\Bootstrap\App($_GET);

Here is my .htaccess file

<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?PATH_INFO=$1 [L,QSA]

</IfModule>

Is this a correct way of starting this project? As my next step would be to create a base controller and then link the url to the controller.

If this is not a correct/appropriate coding manor for OOP would a good correction include changing the RewriteRule to include to variables for the controller and method.


texts: Determine if a string of characters are unique using quicksort

texts:
This will determine if a string is unique or not using quicksort, so that it should take \$O(nlogn)\$ time and not \$O(n^2)\$ time.

I will call the test function code from main.

This runs successfully, but when I try to write a randomized partition, it will fail. I have written that code separately.

FindUniqueCharInString.h

#define MAX 15
class FindUniqueCharInString
{
public:
    FindUniqueCharInString(void);
    ~FindUniqueCharInString(void);
    void test();

private:
    void swap(int index1, int index2);
    void quickSort(int start, int end);
    int partition(int start, int end);

    char arr[15];
};

FindUniqueCharInString.cpp

#include "FindUniqueCharInString.h"
#include <iostream>

using std::cout;
using std::endl;

FindUniqueCharInString::FindUniqueCharInString(void)
{
    char *tempArr = "SOMESTRING";

    strcpy(arr,tempArr);
}

FindUniqueCharInString::~FindUniqueCharInString(void)
{
}

void FindUniqueCharInString::test()
{
    quickSort(0,strlen(arr));

    for(int i = 0;i<strlen(arr);i++)
    {
        cout<<arr[i] << " ";
    }

    cout<<endl;

    bool isUnique = true;
    for(int i = 0;i<strlen(arr) - 1;i++)
    {
        if(arr[i] == arr[i+1])
            isUnique = false;
    }

    if(isUnique)
        cout<<"Unique" <<endl;
    else
        cout<<"Not unique"<<endl;

}

void FindUniqueCharInString::swap(int index1, int index2)
{
    if(arr[index1] != arr[index2])
    {
        char temp = arr[index1];
        arr[index1] = arr[index2];
        arr[index2] = temp;
    }
}

void FindUniqueCharInString::quickSort(int start, int end)
{
    if(start >= end)
        return;

    int p = partition(start,end);
    quickSort(start, p - 1);
    quickSort(p + 1,end);
}

int FindUniqueCharInString::partition(int start, int end)
{
    int pivot = arr[end - 1];
    int t = start;

    for(int i = start; i< end-1; i++)
    {
        if(arr[i] <= pivot)
        {
            swap(i,t);
            t++;
        }
    }

    swap(t,end - 1); //swap index and pivot pos

    return t;
}

Randomize partition function:

int FindUniqueCharInString::partition(int start, int end)
{
    int m = start + (end - start)/2;
    int pivot = arr[m];
    int t = start;

    swap(m,end -1); //putting pivot element to end

    for(int i = start; i< end-1; i++)
    {
        if(arr[i] <= pivot)
        {
            swap(i,t);
            t++;
        }
    }

    swap(t,end - 1); //swap index and pivot pos

    return t;
}


texts: Incrementing Values inside an if statement

texts:
I found out that I can increase the value of a variable inside an if statement like so:
int limit = 100;
int nrCopies = 2;
int maxValue = 100;
for(int i = 0; i < limit; ++i)
{
    if((nTotal += (nrCopies)) > maxValue)
        break;
}

This works, and I became acostumed to do this, but I want to know if it is a good practice to do so, since I don't want to get bad habits unnecessarily


texts: Extension of PHP `round()` for PHP_ROUND_UP and PHP_ROUND_DOWN

texts:
While looking at PHP.net this afternoon, I saw a comment in round() for two functions for rounding UP and DOWN (as opposed to just HALF_UP and DOWN).  I liked the suggestion, but wanted a solution that was one function instead of 3, so I came up with the following:

define('PHP_ROUND_UP',   11);
define('PHP_ROUND_DOWN', 12);

function fround($number, $precision = 0, $mode = PHP_ROUND_HALF_UP) {
    if(is_string($number)) {
        $number = preg_replace('/,/','',$number);
    }
    if (is_numeric($number) && !empty($number)) {
        switch($mode) {
            case PHP_ROUND_UP:
            case PHP_ROUND_DOWN:
                $invert = (bool) ($number < 0);
                if($invert) {
                    $number *= -1;
                }
                if (!empty($precision)) {
                    $precision = pow(10, (int) $precision);
                    $number *= $precision;
                }
                if ($mode == PHP_ROUND_UP) {
                    $number = ceil($number);
                } else {
                    $number = floor($number);
                }
                if (!empty($precision) && !empty($number)) {
                    $number /= $precision;
                }
                if($invert) {
                    $number *= -1;
                }
                break;
            default:
                $number = round($number, $precision, $mode);
                break;
        }
    }
    return (float) $number;
}

My questions are about overhead/performance, and really anything else you may have to say.  For options other than PHP_ROUND_UP or PHP_ROUND_DOWN it adds minimal overhead, save for stripping commas if the input number is a string (I realize this is additional to what PHP's round() does), so I guess I am asking about the internal logic for PHP_ROUND_UP and PHP_ROUND_DOWN.

The comment that sparked this for me is here.

REVISION


texts:
I am a fan of f"{strings}" in Python,

However some situations could possibly be dangerous when doing f strings from user input, leaking API keys or even code execution!

So I decided to make something to mitigate these attacks. It works by searching with regex over the input string, and will return an empty string if it detects any evil piece of code.

It uses the fmt package

import fmt as f
import re
import os # This is for checking the system call

import doctest

# Setup
SECRET_GLOBAL = 'this is a secret'

class Error:
    def __init__(self):
        passs

def a_function():
    return SECRET_GLOBAL

# Here is where the code begins
DANGEROUS_CODES = [
                    re.compile(r'(\.system\(.*\))'),    # Any call to system
                    re.compile(r'(__[\w]+__)'),         # Any internals
                    re.compile(r'([\w\d]+\(\))')        # Functions
                  ]

def safe_format(st):
    '''
    Safe python f-string formatting
    this will detect evil code from fstring making formatting safe.

    args:
        st (str): The f-string

    returns:
        Empty string, if dangerous code is found
        Executes the fstring normally if no dangerous code is found

    Test globals acces
    >>> safe_format('{Error().__init__.__globals__[SECRET_GLOBAL]}')
    ''

    Test function acces
    >>> safe_format('a_function()')
    ''

    Test code execution via import
    >>> safe_format('{__import__("os").system("dir")}')
    ''

    Test code execution with imported os
    >>> safe_format('{os.system("dir")}')
    ''

    Test no stack trace
    >>> safe_format('{0/0}')
    ''

    Test acceptable fstring
    >>> safe_format('{6 * 6}')
    '36'
    '''
    if any(re.search(danger, st) for danger in DANGEROUS_CODES):
        return ''

    try:
        return f(st)
    except Exception as e:
        return ''

if __name__ == '__main__':
    doctest.testmod()

Did i miss anything?
Is this approach acceptable?


texts:
https://leetcode.com/problems/range-sum-query-mutable/
I am trying to solve this question using dynamic programming.
I guess the guys in leetcode want to limit us to use segment tree or one of the other solutions.
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;

namespace DynamicProgrammingQuestions
{

        /// <summary>
        ///https://leetcode.com/problems/range-sum-query-mutable/
        /// ["NumArray", "sumRange","sumRange","sumRange","update","update","update","sumRange","update","sumRange","update"]
        ///[[[0,9,5,7,3]],[4,4],     [2,4],     [3,3]     ,[4,5],   [1,7]   ,[0,8]    ,[1,2],[1,9],[4,4],[3,4]]
        /// [   null,       3,        15,        7,         null    ,null    ,null      ,12,null,5,null]
        /// </summary>
        [TestClass]
        public class UnitTest1
        {
            [TestMethod]
            public void TestMethod1()
            {
                int[] nums = {0, 9, 5, 7, 3};
                NumArray numArray = new NumArray(nums);
                Assert.AreEqual(3, numArray.SumRange(4, 4));
                Assert.AreEqual(15, numArray.SumRange(2, 4));
                Assert.AreEqual(7, numArray.SumRange(3, 3));
                numArray.Update(4,5);
                numArray.Update(1,7);
                numArray.Update(0,8);
                // 8,7,5,7,5
                Assert.AreEqual(12, numArray.SumRange(1, 2));
            }
        }

        public class NumArray
        {
            int[] _dp;
            int[] _nums;
            public NumArray(int[] nums)
            {
                _dp = new int[nums.Length + 1];
                //0,1,2,3
                //  1,4,9
                for (int i = 0; i < nums.Length; i++)
                {
                    _dp[i + 1] = _dp[i] + nums[i];
                }
                _nums = nums;
            }

            public void Update(int index, int val)
            {
                int old = _nums[index];
                _nums[index] = val;
                for (int i = index; i < _dp.Length - 1; i++)
                {
                    _dp[i + 1] = _dp[i + 1] - old + val;
                }

            }

            public int SumRange(int left, int right)
            {
                return _dp[right + 1] - _dp[left];
            }
        }

}

here is my code. i'm trying to understand if I can optimize it?
can you please suggest runtime performance optimizations?


texts:
It seems that lxml/etree are generally imported as from lxml import etree -- why is that?  It keeps the code tidier, and while the potential namespace ambiguity might not be a concern, I don't have any incentive of doing this as it's generally frowned upon.

I know for a script of this size it doesn't matter much, but I'm going to be using these modules for a lot more. I'm also curious about what others have to say.

#!/usr/bin/python
# Stuart Powers http://sente.cc/

import sys
import urllib
import lxml.html
from cStringIO import StringIO

""" This script parses HTML and extracts the div with an id of 'search-results':
  ex:
...

$ python script.py "http://www.youtube.com/result?search_query=python+stackoverflow&page=1"
The output, if piped to a file would look like: http://c.sente.cc/E4xR/lxml_results.html

"""

parser = lxml.html.HTMLParser()

filecontents = urllib.urlopen(sys.argv[1]).read()

tree = lxml.etree.parse(StringIO(filecontents), parser)

node = tree.xpath("//div[@id='search-results']")[0]

print lxml.etree.tostring(tree, pretty_print=True)


texts: Rendering logos for guitars and basses listed in a database

texts:
Right now I'm still a beginner in databases and still learning all about it. I have a problem with the design of my database and I don't really know where to go from here. Basically I'm building a music store website that has guitars and bass as products. Now, I have a total of six brands in my database, including its corresponding logo images for displaying in a webpage. Both guitar and bass can use this database for retrieving the needed brand.

brandId  name  image
1         Ibanez    xyz.jpg
2         Fender    abc.jpg
3         Gibson    hjk.jpg
4         PRS        wyx.jpg
5         Musicman cde.jpg
6         ESP        ihl.jpg

Now, I would display those brands for guitar using asp repeater. In this case, the guitar webpage has no problem displaying all the brands because it has all products for that brand. Here is the aspx code for the guitar:

<asp:Content ID='Content1' ContentPlaceHolderID='ContentPlaceHolder1' Runat='Server'>

<asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="repeater_ItemDataBound" ItemType="brand" SelectMethod="GetBrandData">
    <ItemTemplate>

             <asp:LinkButton ID="linkButton" OnClick="Repeater1_OnClick" runat="server" CommandArgument='<%# Item.brandId %>'>
                 <asp:Image ID="brandImage" runat="server" height="250px" width="300px" />
             </asp:LinkButton>

    </ItemTemplate>

And here is the code-behind for the guitar:

 protected void Page_Load(object sender, EventArgs e)
{

}

public void repeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    Image img = e.Item.FindControl("brandImage") as Image;
    img.ImageUrl = "../Images/Brands/" + ((brand)e.Item.DataItem).image;
}

public List<brand> GetBrandData()
{
    MusicStoreDBEntities obj = new MusicStoreDBEntities();
    List<brand> list = new List<brand>();
    list = (from g in obj.brands select g).ToList();

    return list;

}

Meanwhile the bass can only display three brands which is Ibanez,Fender and Musicman. This is where the problem starts. It basically has the same aspx code as the guitar but I've made this change to the sql query so that it can return only those three brands.

public List<brand> GetBrandData()
{
    MusicStoreDBEntities obj = new MusicStoreDBEntities();
    List<brand> list = new List<brand>();
    list = (from g in obj.brands where g.name=="Ibanez"||g.name=="Fender"||g.name=="Musicman" select g).ToList();

    return list;

}

I have multiple where clauses in that query so that i can just retrieve those three brands. I really feel like this is not the most efficient way and will cause problems if lets say, i wanted to add a seventh brand and I would need that to display on the bass webpage, then i would need to manually edit query everytime, which is not ideal. I wanted to know if there are other solutions for managing the query or solutions for the design aspect of the database.

I hope you guys can give me some input on this.


texts:
Is it possible to improve the code of this bash script? ... or should I just use another language? (If so, which one would fit the best the situation, according to you?)

Here is the code (simplified, to emphasis the problem):

#!/bin/bash
# mountDDE mount the partitions of the disk b.
# If arguments are passed, it will mount the specific partitions, a, b or c.

if [ -v "$1" ] # If no argument is passed, act on all partitions.
then a=t
    b=t
    c=t
fi

while [ -n "$1" ] ; do
    if [ $1="a" ] # We test the argument(s), to know which partition has to be mounted.
    then a=t
    elif [ $1="b"] # I hate redundunces
    then b=t
    elif [ $1="c"] # Again...
    then c=t
    fi
    shift
done

[ $a="t" ] && sudo mount /dev/sba /media/ba # I'll actually use uuids.
[ $b="t" ] && sudo mount /dev/sbb /media/bb # Not direct paths, like here.
[ $c="t" ] && sudo mount /dev/sbc /media/bc

To me, this code is redundant. Is there any more efficient/better way to do it ?
Which language should I use for this task?


texts: Inputting multiple strings and finding their length

texts:
I need to find the length of elements within a string and return it to the user.

What is the best way of simplifying this code to make the amount of string lengths equate to user input? Also, how can I replace string1 with the user input, such as "The length of string 'Dog' is 3"?

num_of_items = int(input("How many items in your list? "))
def item_list(x):

    items = []
    for i in range(0, x):
        item = input("Enter list %r: " % (i+1))
        items.append(item)
        length_items = ''.join(items)

    return "Itemlist: %r" %(items), "Total length: %s"% len(length_items), \
    "The length of string 1 is %r"%len(items[0]),\
    "The length of string 2 is %r"%len(items[1]),\
    "The length of string 3 is %r"%len(items[2]),\
    "The length of string 4 is %r"%len(items[3])

print(item_list(num_of_items))


texts:
I'm creating a PHP object with an array of data:

$row = array(
  'id' => 123,
  'username' => 'Testing',
  'status' => 1,
  'created_on' => '2014-09-20',
  'created_by' => 1,
  'updated_on' => null,
  'updated_by' => null,
);

and I create a corresponding object using the following code:

$model = new User();
$model->id = (int)$row['id'];
$model->username = $row['username'];
$model->status = (int)$row['status'];
if($row['created_on'] != null) {
  $model->created_on = new DateTime($row['created_on']);
}
$model->created_by = (int)$row['created_by'];
if($row['updated_on'] != null) {
  $model->updated_on = new DateTime($row['updated_on']);
}
if($row['updated_by'] != null) {
  $model->updated_by = (int)$row['updated_by'];
}

Is there any way to simplify it?

P.S. I'm not using any PHP framework and I'm not going to use one.

Note: I'm using PHP 5.5

UPDATE: My current simplified version:

$model = new User();
foreach($row as $k => $v) {
  if(isset($model->$k)) {
    if(is_int($v)) {
      $model->$k = (int)$v;
    } elseif(is_string($v)) {
      if(($k == 'created_on' || $k == 'updated_on') && $v != null) {
        $model->$k = new DateTime($v);
      } else {
        $model->$k = $v;
      }
    }
  }
}

Am I making the codes more complicated?

The reason I made the 2nd version is that I worried the 1st version expands if the $row expands.


texts:
I want an istream that you can safely peek arbitrarily many characters from. This works as far as I can tell, but I am unsure if this is really "the right way" to do it since the iostream library is pretty cryptic to me.

class peekbuf : public std::streambuf
{
    std::streambuf* sbuf_;
    std::vector<char> data_;
    char ch;
public:
    peekbuf(std::streambuf* s)
    : sbuf_(s)
    { }

    std::vector<char> const& peek(int N) {
        data_.clear();
        data_.reserve(N);
        for (int i = 0; i < N; ++i) {
            int next = sbuf_->sbumpc();
            if (next == traits_type::eof()) {
                break;
            }
            data_.push_back(next);
        }

        if (!data_.empty()) {
            setg(data_.data(), data_.data(), data_.data() + data_.size());
        }

        return data_;
    }

protected:
    int_type underflow() override {
        ch = sbuf_->sbumpc();
        setg(&ch, &ch, &ch + 1);
        return ch;
    }
};

Example usage:

int main() {
    peekbuf buf{std::cin.rdbuf()};
    std::cin.rdbuf(&buf);

    auto first5 = buf.peek(5);

    std::string s;
    std::cin >> s;
    std::cout << "Got " << s << '\n';

    std::cout << "Peeked: ";
    for (char c : first5) {
        std::cout << c;
    }
    std::cout << '\n';
}

Where:

$ echo 123456789 | ./a.out

yields:

Got 123456789
Peeked: 12345


texts:
I am creating a miniature bulk email sender. I am using Postfix on Ubuntu with JavaMail. Here is the key part of the code:

public static void main(final String[] args){
    final Connection selectConnection = DriverManager.getConnection(prop.getProperty("select_connection"));
    final Statement stmt = selectConnection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
    stmt.setFetchSize(Integer.MIN_VALUE);
    ResultSet rs = stmt.executeQuery("SELECT email FROM emails");
    while(rs.next()){
        recipient = rs.getString("email");
        session = rs.getString("code");
        unsubscribeParameters = "s="+session+"&c="+campaign+"&r="+recipient;
        openedParameters = "s="+session+"&c="+campaign;
        sendEmail(recipient, campaign, html.replace("unsubscribeParameters", unsubscribeParameters).replace("openedParameters", openedParameters), properties);
    }
}
private static void sendEmail(final String recipient, final String campaign, final String html, final Properties properties){
    final String verp = campaign+"="+recipient.replace("@", "+") + "@example.com";
    properties.put("mail.smtp.from", verp);
    final Session session = Session.getDefaultInstance(properties);
    final MimeMessage message = new MimeMessage(session);
    try {
        message.setFrom(new InternetAddress(SENDER_ADDRESS, SENDER_NAME));
        message.setSubject(subject);
        final MimeBodyPart textPart = new MimeBodyPart();
        textPart.setContent(plainText, "text/plain");
        final MimeBodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(html, "text/html");
        final Multipart mp = new MimeMultipart("alternative");
        mp.addBodyPart(textPart);
        mp.addBodyPart(htmlPart);
        message.setContent(mp);
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
        Transport.send(message);
    } catch (final Exception | OutOfMemoryError e) {
        //handle errors
    }
}

Right now, I'm getting about 7 emails a second on a 512 MB RAM box, 1 core processor, and a 20 GB SSD disk. Does anyone see any ways to speed this up? Is it possible?


texts:
I have completed my homework with directions as follows:

  Declare and implement a class named Binary. This class will have a
  method named printB(int n) that prints all binary strings of length n.
  For n = 3, it will print

000
001
010
011
100
101
110
111

  in this order.

Is there any way to make this shorter or more efficient?

import java.util.Scanner;
class Binary
{

    String B;
    int temp;

    void printB(int n)
    {
        for(int i = 0; i < Math.pow(2,n); i++)
        {
            B = "";
            int temp = i;
            for (int j = 0; j < n; j++)
            {
                if (temp%2 == 1)
                    B = '1'+B;
                else
                    B = '0'+B;
                    temp = temp/2;
            }
            System.out.println(B);
         }
    }
}

class Runner
{
    public static void main(String [] args)
    {
        Scanner in = new Scanner(System.in);

        System.out.print("Enter n:");
        int n = in.nextInt();

        Binary myB = new Binary();

        myB.printB(n);
    }
}


texts:
I'm a beginner at C++; all my previous programming experience is mainly through PLCs in industrial maintenance.

I have to accept 10 integers and a target value, then print all the pairs that sum to the target.

The pairs cannot be of the same integer.  For example, if the target value is 10 then we cannot have a pair of 5 + 5. This code basically executes well enough for me, however I get an overloaded int out at the end; I'm curious why that might be?

Also I understand there are much easier ways to accomplish this task. I feel pretty good with what I was able to come up with given the amount of time I have devoted so I certainly am fine with it, however I wouldn't mind seeing some examples how much more seasoned programmers would have attempted this, if anyone out there is bored.

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

int main()
{
    int run, a, b, ints[11], out[45];

    cout << "\n\t\tAfter inputting 11 integers, this program will evaluate\n\tthe first 10 integers, then will display the pairs of said integers\n\twhich when added together the total will equal the 11th integer.";
    cout << "\n\n\tPlease enter 11 integers: \n\n";

    for (run = 0; run <= 10; run++)
    {
        cout << "\t\t"; cin >> (ints[run]);
    }
    system("cls");
    run = 0;
    for (a = 0; a < 10 && run <= 10; a++)
    {
        for (b = 1; b < 10 && run <= 10; b++)
        {
            if (ints[10] == (ints[a] + ints[b]) && ints[a] != ints[b] && run <= 10)
            {
                out[run] = ints[a];
                run++;
                out[run] = ints[b];
                run++;
            }
        }
    }
    cout << "\n\t\tPerforming critical calculations . . .\n\t\t";
    system("pause");

    cout << "\n\t\t";
    if (*max_element(out, out + 10) == 0)
        cout << "No sum of integers found to equal desired total. ";
    else
    {
        cout << "Pairs of integers that equal the desired total are as follows; ";
        for (int index = 0; index < 11; index++)
        {
            if (out[index] > 0)
            {
                cout << "(" << out[index++] << " , " << out[index] << ")";
                if (index < 11)
                    cout << ", ";
                else if (index == 11)
                    break;
            }

        }
    }
    system("pause");
    return 0;
}
```


texts:
Any idea how to shorten and improve the program?
it's going to take a list included of 22 people and split them into two teams and return the names and teams
import random
# list of teams
teams = ['A', 'B']
# list of players which is inculded of 22 people
players = ['a', 'b', 'c', 'd', 'e',
           'f', 'g', 'h', 'i', 'j',
           'k', 'l', 'm', 'n', 'o',
           'p', 'q', 'r', 's', 't',
           'u', 'v']

# takes the list of names

class Human:
    def __init__(self, name):
        self.name = name

# distribure names and people to teams randomly and it inherits names from Human class

class Player(Human):
    def get_team(self):
        teams = dict()
        random.shuffle(self.name)
        teams['A'] = self.name[0::2]
        teams['B'] = self.name[1::2]
        return teams

my_team = Player(players)
my_team = my_team.get_team()
for team, name in my_team.items():
    print(team, name)


texts: Non-recursive BFS Maze Solving with Python

texts:
I wrote this program to help me understand how BFS and Queues work. (Also DFS if I replace the queue with a stack).

It works, but I'm curious how well I implemented the algorithm.

Are there any obvious improvements?

For example, I notice that there are duplicate values in the Queue. I understand that I should avoid visiting already visited positions. However the queue contains only "prospective" positions which are yet to be visited. Should I modify the algorithm to not enqueue positions which it already contains?

My agenda is to understand Data Structures and Algorithms and write reasonable quality code to implement the basic concepts.

from os import system
from random import randint

class Queue:
    def __init__(self):
        self.list = []

    def enqueue(self, item):
        self.list.append(item)

    def dequeue(self):
        temp = self.list[0]
        del self.list[0]
        return temp

    def isEmpty(self):
        return not self.list

    def empty(self):
        self.list = []

def create_maze(n):
    maze = []
    for row in range(n):
        row = []
        for col in range(n):
            if randint(0,3) == 0:
                row.append(1)
            else:
                row.append(0)

        maze.append(row)

    maze[0][0] = 0
    maze[n-1][n-1] = 2
    return maze

def print_maze(maze):
    for row in maze:
        print((row))

def is_valid_pos(tup):
    (col, row) = tup
    if col < 0 or row < 0 or col >= MAZE_SIZE  or row >= MAZE_SIZE :
        return False
    return maze[row][col] == 0 or maze[row][col] == 2

def solve(maze, start):
    q = Queue()
    (col,row) = start
    print('Enqueueing ({},{})'.format(col,row))
    q.enqueue((col,row))

    while not q.isEmpty():
        print('Queue contents: {}'.format(q.list))
        input('Press Enter to continue: ')
        print('Dequeueing')
        (col, row) = q.dequeue()
        print('Current position: ({}, {})'.format(col,row))

        if maze[row][col] == 2:
            print('Goal reached at ({}, {})'.format(col,row))
            return
        if maze[row][col] == 0:
            print('Marking ({}, {})'.format(col,row))
            maze[row][col] = 3
        print_maze(maze)
        print('Enqueueing coordinates of valid positions in 4 directions.')
        if is_valid_pos((col+1, row)): q.enqueue((col+1, row))
        if is_valid_pos((col, row+1)): q.enqueue((col, row+1))
        if is_valid_pos((col-1, row)): q.enqueue((col-1, row))
        if is_valid_pos((col, row-1)): q.enqueue((col, row-1))

    print("Goal can't be reached.")

while True:
    system('cls')
    maze = create_maze(4)
    MAZE_SIZE = len(maze)
    solve(maze, (0,0))
    input('Press Enter to restart: ')


texts: Report for a restaurant showing hourly sales information for a given timespan

texts:
I have been tasked with creating a report for a high-volume restaurant that shows hourly sales information for a given timespan. When generating this report for a single day, it's very quick, but when generated for even two days, the length of time grows tremendously.

I was originally doing subqueries to get the data that are shown as TempGiftCard and TempPayment in the WITH block at the top of this query. After doing some research online, I was under the impression that placing them in the WITH blocks will make them only execute once and the results would be reused. However, when I look at the Actual Execution Plan that SSMS produces, it doesn't appear that that is the case. According to the execution plan, about 60% of the time for this query to run is in the TempGiftCard portion of the query.

Running the full query for a single day takes about 1 second, but when running it for two days, it takes about 90-100 seconds.

Given this information, I know this is a query issue and not a data issue, but I'm not sure what else to try.

WITH TempGiftCard AS
(SELECT OrderTrackDate, OrderNum, SUM(ItemPrice) AS GiftCardsSold
    FROM RMArchive.dbo.OrderItems
    WHERE ItemName = 'GIFT CARD'
        AND OrderTrackDate BETWEEN '12/7/2015' AND '12/8/2015'
    GROUP BY OrderTrackDate, OrderNum),
TempPayment AS
(SELECT OrderNum, SUM(CASE WHEN PaymentCoupon = - 1 THEN PaymentAmount ELSE 0 END) AS Coupons,
                  SUM(CASE WHEN PaymentPromo = - 1 THEN PaymentAmount ELSE 0 END) AS Promo,
                  OrderTrackDate
    FROM RMArchive.dbo.Payment
    WHERE OrderTrackDate BETWEEN '12/7/2015' AND '12/8/2015'
    GROUP BY OrderNum, OrderTrackDate)
SELECT DATEPART(hour, OrderCloseTime) AS Hour,
       OrderType,
       SUM(OrderGuests) AS GuestCount,
       ROUND(CASE WHEN SUM(OrderGuests) = 0 THEN 0 ELSE SUM(OrderSubTotal) / SUM(OrderGuests) END, 2) AS AvgPerGuest,
       SUM(OrderSubTotal) AS Subtotal,
       ISNULL(SUM(Coupons), 0) * - 1 AS Coupons,
       ISNULL(SUM(Promo), 0) * - 1 AS Promo,
       SUM(OrderSubTotal) - (SUM(CASE WHEN OrderTaxExempt = - 1 THEN OrderSubTotal ELSE 0 END) + SUM(OrderNonTaxableAmount)) AS Taxable,
       SUM(CASE WHEN OrderTaxExempt = - 1 THEN OrderSubTotal ELSE 0 END) + SUM(OrderNonTaxableAmount) AS NonTaxable,
       ROUND(SUM(CASE WHEN OrderTaxExempt = 0 THEN OrderDueTax ELSE 0 END), 2) AS TaxCollected,
       SUM(OrderTaxableInc) AS TaxIncludedSales,
       SUM(OrderTaxInc) AS TaxIncluded,
       ROUND(SUM(OrderSubTotal) + SUM(OrderTaxableInc), 2) AS TotalNetSales,
       ROUND(SUM(CASE WHEN OrderTaxExempt = 0 THEN OrderDueTax ELSE 0 END) + SUM(OrderTaxInc), 2) AS TotalTax,
       ROUND(SUM(OrderSubTotal) + SUM(CASE WHEN OrderTaxExempt = 0 THEN OrderDueTax ELSE 0 END), 2) AS GrossSales,
       ISNULL(SUM(GiftCardsSold), 0) AS GiftCardsSold
FROM RMArchive.dbo.OrderInfo
LEFT JOIN TempPayment ON OrderInfo.OrderNum = TempPayment.OrderNum AND OrderInfo.OrderTrackDate = TempPayment.OrderTrackDate
LEFT JOIN TempGiftCard ON OrderInfo.OrderNum = TempGiftCard.OrderNum AND OrderInfo.OrderTrackDate = TempGiftCard.OrderTrackDate
WHERE OrderInfo.OrderTrackDate BETWEEN '12/7/2015' AND '12/8/2015' AND OrderType IS NOT NULL
GROUP BY DATEPART(hour, OrderCloseTime), OrderType
ORDER BY DATEPART(hour, OrderCloseTime), OrderType
OPTION (RECOMPILE);


texts: Performing a special multiplication on two square matrices

texts:
I have a function called mult2 that takes in two square NumPy matrices and returns a matrix that is the result of a special multiplication:

p=P(1,344)
PI,PIT=[],[]
for i in xrange(344):
    PI.append(p**i)
    PIT.append((p**i).transpose())

def mult2(a,b):
    C=np.sum((a*b)**2,axis=1)
    CE1=np.matrix([[0.0] for _ in xrange(len(a))])
    API,PITB=[],[]
    AB=a*b
    for i in xrange(len(a)):
        API.append(np.diag(np.diag(a*PI[i])))
        PITB.append(np.diag(np.diag(PIT[i]*b)))
        CE1+=np.sum(API[i]*PITB[i]*AB,axis=1)
    CE2=np.matrix([[0.0] for _ in xrange(len(a))])
    BPI,PITA=[],[]
    for i in xrange(len(a)):
        BPI.append(np.diag(np.diag(b*PI[i])))
        PITA.append(np.diag(np.diag(PIT[i]*a)))
        CE2+=np.sum(a*BPI[i]*PITA[i]*b,axis=1)
    CE3=np.matrix([[0.0] for _ in xrange(len(a))])
    for i in xrange(len(a)):
        CE3+=np.sum(AB*API[i]*PITB[i],axis=1)
    CE1E2=np.matrix([[0.0] for _ in xrange(len(a))])
    for i in xrange(len(a)):
        CE1E2+=np.sum(API[i]*PITB[i]*API[i]*PIT[i]*b,axis=1)
    CE2E3=np.matrix([[0.0] for _ in xrange(len(a))])
    for i in xrange(len(a)):
        CE2E3+=np.sum(a*BPI[i]*PITA[i]*BPI[i]*PIT[i],axis=1)
    CE1E3=np.matrix([[0.0] for _ in xrange(len(a))])
    for i in xrange(len(a)):
            for j in xrange(len(a)):
                CE1E3+=np.sum(np.matrix(API[i]*PITB[i]*API[j]*PITB[j]),axis=1)
    CE1E2E3=np.matrix([[0.0] for _ in xrange(len(a))])
    for i in xrange(len(a)):
        CE1E2E3+=np.sum(np.matrix((API[i]*PITB[i])**2),axis=1)
    return C-(CE1+CE2+CE3-CE1E2-CE1E3-CE2E3+CE1E2E3)

p is another matrix of the same dimensions (n by n) as a and b specially a circulant matrix.

My trouble is that these matrices are 344 by 344 and I am looking to run this function lots of times.

Storing the matrices that are used later in the function in the lists actually sped up the computation significantly.

I know this is a very intensive computation so it should take a while to run. That being said, can anyone spot any improvements I can make?


texts: Internal function that determines when to resize by width or height in a Image Resizer utility

texts:
Description:

Given an image X with known dimensions. We call a method CreateThumbnail to make a thumbnail (or not) with a given max-width and max-height (both optional).

CreateThumbnail call ComputeSize method (bad name?) which is responsable for doing the following logic:

If no max-width/max-height, the width and height should return as is.
If only one is provided, then we call a method ResizeWidth on the Dimention2D object to return a new dimension based on the new width size (aspectRation is kept).

Same applies for height.

If both are provided, use the one, that while keeping the aspect ration, won't be bigger than their corresponding maximum.

If the image dimension are smaller than the maximum, no change to the dimensions.

Then, with the new size, the Resize is actually applied (or not) (this is outside the scope of this method).

private Dimention2D ComputeSize(Image image, int maxWidth, int maxHeight)
{
    if (image == null) throw new ArgumentNullException(nameof(image));
    var sourceDimension = new Dimention2D(image.Width, image.Height);

        bool computeWidth = maxWidth > 0 && sourceDimension.Width > maxWidth;
        bool computeHeight = maxHeight > 0 && sourceDimension.Height > maxHeight;

    if (computeWidth && computeHeight)
    {
        if (sourceDimension.Width / maxWidth > sourceDimension.Height / maxHeight)
            computeHeight = false;
        else
            computeWidth = false;
    }

    if (computeWidth)
        return sourceDimension.ResizeWidth(maxWidth);

    else if (computeHeight)
        return sourceDimension.ResizeHeight(maxHeight);

    else return sourceDimension;
}

I'm open to any suggestion.
Variables/methods names, the use (or lack of) { and } on if/else, the if/else. and whatever thing you can think of making it prettier.


texts:
Here is my approach. Do DFS and check in stack whether the new node is already in the Stack or not.

public static boolean isCyclicDFS(int[][] adjMat) {
        int len = adjMat.length;
        boolean[] isVisited = new boolean[len];
        for(int i =0; i<len; i++) {
            isVisited[i] = false;
        }

        Stack s = new Stack<>();
        s.add(0);

        while(!s.isEmpty()) {
            int current = (int) s.pop();
            System.out.println(current);
            isVisited[current] = true;
            for(int i =0; i<len; i++) {
                if(adjMat[current][i] ==1 && isVisited[i] == false) {
                    if(s.contains(i)) {
                        return false;
                    }
                    s.push(i);
                    break;
                }
            }

        }
        return true;

    }

Kindly suggest if any improvement/correction.