texts:
Whats the best practice for calling a function with a complex set of arguments?

I've seen a 1 and 2 in most codebases, but I haven't seen 3.
Since it's almost impossible to search for **{ in codebases, does anyone know why this pattern isn't used more often?

I'm using Google's Sheet's API v4 as a demonstration, which has a complex API.

1. Calling with arguments (Most commonly observed)

Requires building the inner structure first

body = {
    "body": {
        "requests": [
            {
                "addSheet": {
                    "properties": {
                        "title": "some title"
                    }
                }
            }
        ]
    }
}
request = service.spreadsheets().batchUpdate(
    spreadsheetId=spreadsheetId, body=body)

2. Define a dict first (Similar vertical parsing to 1)

Cleaner to see on invocation
May allow for manipulation of values

params = {
    "spreadsheetId": spreadsheetId
    "body": {
        "requests": [
            {
                "addSheet": {
                    "properties": {
                        "title": "some title"
                    }
                }
            }
        ]
    }
}
request = service.spreadsheets().batchUpdate(**params)

3. Inline a dict (Not seen in practice, why?)

Clear intent (single-source, fixed properties)
Single pass vertical parsing

request = service.spreadsheets().batchUpdate(**{
    "spreadsheetId": spreadsheetId
    "body": {
        "requests": [
            {
                "addSheet": {
                    "properties": {
                        "title": "some title"
                    }
                }
            }
        ]
    }
})


texts: How to improve my auto-reconnection Python script

texts:
I need some feedback here. Due to a weird issue on my server system, the network card disconnects from the network regularly. I'll fix this at a later date. But I wanted to know if the below script can be improved.

It's comprised of two files. A python script (autoConnect.py), and a Bash script (checkOnline.sh).

autoConnect.py:

#!/usr/bin/python
from subprocess import call, Popen, PIPE, STDOUT
import time
cmd = './checkOnline.sh'
while True:
    p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
    if "0" in p.stdout.read():
        print time.ctime() + ": Offline"
        print "Attempting to reconnect..."
        print "Determining network profile..."
        cmdTwo = "wicd-cli -ySl | sed -n '2 p' | grep -i paws -c"
        pTwo = Popen(cmdTwo, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
        if "1" in pTwo.stdout.read():
            print "Network profile is \"1\""
            defNum = 1
        else:
            print "Network profile is \"2\""
            defNum = 2
        print "Connecting to network..."
        p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
        while "0" in p.stdout.read():
            call("wicd-cli -yn " + defNum + " -c")
            p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
            time.sleep(3)
            if "0" in p.stdout.read():
                print "Failed to connect. Trying again..."
        print "Success, connected to network!"
    else:
        print time.ctime() + ": Online"
    time.sleep(5)

checkOnline.sh:

#!/bin/bash

host=google.com

(ping -w5 -c3 $host  > /dev/null 2>&1) && echo "1" || (echo "0" && exit 1)

The former is the main file to be run. checkOnline pings google.com 3 times for 5 seconds, if nothing is returned within 5 seconds, it will return 0. If it gets something, it returns 1 into stdout.

I wanted to know if this can be improved for what I want it to do (check if the network is online, search for networks, connect, repeat). As of right now, I'm away from my server's physical location and am unable to test it on the current system I'm using, but the script should be functional.


texts: Enormous Input Test - reducing program runtime

texts:
This is my solution to SPOJ Problem 442.  How can I make this code run faster? What are some techniques that can be used to make this faster? I am getting a Time Limit Exceed Error here.

import java.util.Scanner;

class main{
   public static void main(String args[]){
      Scanner input = new Scanner(System.in);
      int n,k,m=0;
      n = input.nextInt();
      k = input.nextInt();

      for(int c = 0 ; c < n ; c++){
         if(input.nextInt() % k == 0) m++;
      }

      System.out.println(m);
    }
}


texts: Calculation of trigonometric sine function

texts:
I'm creating a client-side pie chart in XSLT 1.0, without extensions or external dependencies (i.e., cannot use FXSLT, EXSLT, JavaScript, etc.).

The code is slow; at least fifteen iterations are necessary to get the correct precision required for the angles used by the pie chart. (I'm looking for help that doesn't involve loop unrolling, if possible.)

How would you speed calculating the sine function?

<xsl:template name="power">
  <xsl:param name="n"/>
  <xsl:param name="exponent"/>
  <xsl:param name="result" select="1" />
  <xsl:choose>
    <xsl:when test="$exponent = 0">1</xsl:when>
    <xsl:when test="$exponent = 1">
      <xsl:value-of select="$result * $n"/>
    </xsl:when>
    <xsl:otherwise>
      <xsl:call-template name="power">
        <xsl:with-param name="n" select="$n"/>
        <xsl:with-param name="exponent" select="$exponent - 1"/>
        <xsl:with-param name="result" select="$result * $n"/>
      </xsl:call-template>
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>

<xsl:template name="factorial">
  <xsl:param name="n" select="1" />

  <xsl:choose>
    <xsl:when test="$n &lt;= 1">1</xsl:when>
    <xsl:otherwise>
      <xsl:variable name="f">
        <xsl:call-template name="factorial">
           <xsl:with-param name="n" select="$n - 1" />
        </xsl:call-template>
      </xsl:variable>
      <xsl:value-of select="$n * $f" />
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>

<!-- sin(x) = x - x^3/3! + x^5/5! - x^7/7! ... -->
<xsl:template name="sin">
  <xsl:param name="degrees" />
  <xsl:param name="radians" select="$degrees * $PI div 180" />
  <xsl:param name="iter" select="1" />
  <xsl:param name="maxiter" select="15" />
  <xsl:param name="result" select="0" />

  <xsl:variable name="taylor" select="($iter - 1) * 2 + 1" />
  <xsl:variable name="numerator">
    <xsl:call-template name="power">
      <xsl:with-param name="n" select="$radians" />
      <xsl:with-param name="exponent" select="$taylor" />
    </xsl:call-template>
  </xsl:variable>
  <xsl:variable name="denominator">
    <xsl:call-template name="factorial">
      <xsl:with-param name="n" select="$taylor" />
    </xsl:call-template>
  </xsl:variable>

  <xsl:variable name="term">
    <xsl:choose>
      <xsl:when test="$iter mod 2 = 1">
        <xsl:value-of select="$numerator div $denominator" />
      </xsl:when>
      <xsl:otherwise><xsl:value-of select="-1 * $numerator div $denominator" /></xsl:otherwise>
    </xsl:choose>
  </xsl:variable>

  <xsl:choose>
    <xsl:when test="$iter &lt; $maxiter">
      <xsl:call-template name="sin">
        <xsl:with-param name="radians" select="$radians" />
        <xsl:with-param name="iter" select="$iter + 1" />
        <xsl:with-param name="result" select="$result + $term" />
      </xsl:call-template>
    </xsl:when>
    <xsl:otherwise><xsl:value-of select="$result" /></xsl:otherwise>
  </xsl:choose>
</xsl:template>

A similar question exists for C, but loop unrolling is awkward in XSLT due to its immutable variables.


texts:
I have a query that returns records that have duplicate names within a given DBSTATUS. I used to do this with a direct connection to the remote oracle database server with this query. (Names changed to protect the innocent, but otherwise, this is my code.)

SELECT  SUBSTR(NAME, 1, 3) AS CATID,
    TABLE1.NAME,
    TABLE1.DESC1 AS DESCRIPTION,
    TABLE1.DBKEY,
    TABLE1.DBSTATUS,
    ISSUES.NAME_CT
FROM  (SELECT  NAME, DBSTATUS, COUNT(NAME) AS NAME_CT
       FROM  TABLE1
       WHERE  DBSTATUS IN (1,2)
       GROUP BY NAME, DBSTATUS
       HAVING COUNT(NAME) > 1) ISSUES,
       TABLE1
WHERE ISSUES.NAME = TABLE1.NAME
    AND ISSUES.DBSTATUS = TABLE1.DBSTATUS
ORDER BY CATID, NAME, DBKEY

The requirements have changed and now I need to exclude a list of CATIDs from this report, but only when they have a DBSTATUS of 2. This is what I came up with, but I don't much like the duplicated select in the WHERE statement. Since the exclusion table resides on the local server, I have switched to an OPENQUERY instead of a direct connection to the remote server. How can I improve this?

SELECT *
FROM OPENQUERY(REMOTE_ORACLE_SERVER,
'SELECT  SUBSTR(NAME, 1, 3) AS CATID,
    TABLE1.NAME,
    TABLE1.DESC1 AS DESCRIPTION,
    TABLE1.DBKEY,
    TABLE1.DBSTATUS,
    ISSUES.NAME_CT
FROM  (SELECT  NAME, DBSTATUS, COUNT(NAME) AS NAME_CT
       FROM  TABLE1
       WHERE  DBSTATUS IN (1,2)
       GROUP BY NAME, DBSTATUS
       HAVING COUNT(NAME) > 1) ISSUES,
       TABLE1
WHERE ISSUES.NAME = TABLE1.NAME
    AND ISSUES.DBSTATUS = TABLE1.DBSTATUS
ORDER BY CATID, NAME, DBKEY
')drv
WHERE (CATID IN(SELECT CATID FROM RACK_CATIDS) AND DBSTATUS = 1)
OR (CATID NOT IN(SELECT CATID FROM RACK_CATIDS))


texts:
I wrote this code to make sure account numbers (accounting), which are numbers, are stored as text in the range. Replacing r.value by r.text does not seem to work on whole ranges, so I need to loop. Any better idea?

Sub num2text(r As Range, Optional keepFormat As Boolean)
'change numbers to text, optionally leaving the numberFormat unchanged
    Dim oldFormat
    Dim c As Range
    For Each c In r
        If IsNumeric(c) Then
            If keepFormat Then oldFormat = c.NumberFormat   'save num fmt
            c.NumberFormat = "@"
            c.Value = c.Text
            If keepFormat Then c.NumberFormat = oldFormat   'restore num fmt
        End If
    Next c
End Sub

Sub num2text_test()
    num2text Range("b10:b100")
End Sub


texts:
How would you refactor this method to make it more performant?

If you have refactored the code you need to prove the performance gain in numbers to get the solution :)

public static T Find<T>(
    this IEnumerable<T> source,
    Func<T, IEnumerable<T>> childrenSelector,
    Predicate<T> condition)
{
    T t = default(T);
    foreach (T item in source)
    {
        if (condition(item))
        {
            return item;
        }

        t = childrenSelector(item).Find<T>(childrenSelector, condition);

        if (!Equals(t, default(T)))
        {
            return t;
        }
    }
    return t;
}


texts: Summing integers in stream using Fenwick tree

texts:
In short, the input is an ordered list of numbers, and we have to sum the numbers from index a to b quickly. For example, assume array[] = {1, 2, 3}. Please sum from array[0] to array[2] (1 + 2 + 3).

Because the input array can have as much as 200,000 elements, I used a Fenwick tree to save time, but the time limit is still exceeded on UVa.

Here is the problem on UVa.

Which part can I improve?

I built:

lowbit() return low bit for fenwick tree
create() create the fenwick tree
update() update the fenwick tree
sum() return the sum by fenwick tree

update :

add Arrays.fill(FT, 0); to initialize Fenwick tree
create() use update()
add array[x] = y; to update the actual array

import java.util.*;

public class Main {

    static int[] FT = new int[200001];    /* store fenwick tree */
    static int[] array = new int[200001]; /* store input data */
    static int N; /* size of input data  */

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);

        int testCase = 0; /* not important, just for UVa output format*/
        int x, y;

        while ((N = in.nextInt()) > 0) {

            Arrays.fill(FT, 0); /* Initialize Fenwick tree */

            for (int i = 1; i <= N; i++) { /* Initialize input array */
                array[i] = in.nextInt();
            }

            create();

            System.out.printf("Case %d:\n", ++testCase);

            String act;
            while (!(act = in.next()).equals("END")) { /* receive action: print sum, update data or END */
                if (act.equals("M")) { /* to print sum from x to y*/
                    x = in.nextInt();
                    y = in.nextInt();
                    System.out.println(sum(y) - sum(x - 1));
                } else { /* to update the array[x] to y ,also fenwick tree*/
                    x = in.nextInt();
                    y = in.nextInt();

                    update(x, y - array[x]);
                    array[x] = y;
                }
            }
        }
    }

    public static void create() {
        for (int i = 1; i <= N; i++) {
            update(i, array[i]);
        }
    }

    public static void update(int i, int delta) {
        for (int j = i; j <= N; j += lowbit(j)) {
            FT[j] += delta;
        }
    }

    public static int sum(int k) {
        int ans = 0;
        for (int i = k; i > 0; i -= lowbit(i)) {
            ans += FT[i];
        }
        return ans;
    }

    public static int lowbit(int k) {
        return -k & k;
    }
}


texts:
I have the following two unsafe methods that I would like to refactor:

public static unsafe void UnsafeMethod(byte[] array, int pos, short value)
{
    fixed (byte* numRef = &(array[pos]))
    {
        *((short*)numRef) = value;
    }
}

public static unsafe void UnsafeMethod(byte[] array, int pos, int value)
{
    fixed (byte* numRef = &(array[pos]))
    {
        *((int*)numRef) = value;
    }
}

If I want to make the method managed will the following conversion be right ?

public static void UnsafeMethod(byte[] array, int pos, short value)
{
    array[pos] = value;
}


texts: Overloading operators in PhoneCall class

texts:
I am trying to understand the concepts of friend functions, overloaded operators, and inheritance in C++. I am very confused on the specifics used for coding, since I am fairly new in programming, and working in the Visual Studio C++ environment in writing code.

The following is the project details for writing a program in Visual Studio C++:

  Design a PhoneCall class that holds a phone number to which a call
  is placed, the length of the call in minutes, and the rate charged per
  minute. Overload extraction and insertion operators for the class. In
  this program, overload the == operator to compare two PhoneCalls.
  Consider one PhoneCall to be equal to another if both calls are
  placed to the same number. Also, create a main() function that allows
  you to enter ten PhoneCalls into an array. If a PhoneCall has
  already been placed to a number, do not allow a second PhoneCall to
  the same number.

I really need some feedback on the following code:

#include <iostream>
#include <string>

using namespace std;

class PhoneCall {
private:
    string phonenumber;
    double perminuterate;
    double calldurationminutes;
public:
    bool operator==( const PhoneCall &n ) const;
    friend ostream & operator<<( ostream &f, const PhoneCall &n );
    friend istream & operator>>( istream &f, PhoneCall &n );
 };
 bool PhoneCall::operator==( const PhoneCall &n ) const {
    return phonenumber == n.phonenumber;
 };
 ostream & operator<<( ostream &f, const PhoneCall &n ) {
    f << "Phone number: " << n.phonenumber <<
         ", Duration: " << n.calldurationminutes <<
         " minutes, Rate: " << n.perminuterate << endl;
 return f;
 }
 istream & operator>>( istream &f, PhoneCall &n ) {
 f >> n.phonenumber;
 f >> n.calldurationminutes;
 f >> n.perminuterate;
 return f;
 }

int main( ) {
 PhoneCall a[10];
 cout << "Enter 10 phone numbers, duration in minutes, and the per-minute rates." <<
     endl << "Separate each with a space and then hit enter to complete it." << endl;
 for ( int i= 0; i < 10; ) {
     cin >> a[i];
     int j;
     for ( j= 0; j < i; ++j )
         if ( a[i] == a[j] ) {
             cout << "Duplicate number information ignored. Try again." << endl;
             break;
         }
     if ( j == i ) ++i;
 }
 for ( int i= 0; i < 10; ++i )
     cout << a[i];

 system("pause");
 return 0;
 }


texts: SqlAlchemy model for users and timezones

texts:
I have a following schema, I would like to query user and all timezones belongs to it including timezone name. Could you please validate if my schema constructed correctly and most efficient way?

class Timezone(Base):
    __tablename__='timezone'
    id = Column(Integer, primary_key=True)
    name = Column(String(40), unique=True)

class UserTimezone(Base):
    __tablename__='user_timezone'
    id = Column(Integer, primary_key=True)
    user_id = Column(Integer, ForeignKey('users.id', ondelete='CASCADE'))
    timezone_id = Column(Integer, ForeignKey('timezone.id', ondelete='CASCADE'))

    timezone = relationship(Timezone, backref="timezone")

class User(Base):
    __tablename__='users'
    id = Column(Integer, primary_key=True)
    first_name = Column(String(64), index=False, unique=False)
    last_name = Column(String(64), index=False, unique=False)
    email = Column(String(120), index=True, unique=True)
    password = Column(String(120), index=False, unique=False)

    timezones = relationship(UserTimezone, backref="user_timezone")


texts: PHP dynamic insert - mysql. Is there a better way than this?

texts:
I have a dynamic form that users can add extra fields too. The group of fields are added and the input name stays the same but gets a incremental number attached to it. So for my insert php file I just check to see if the next value is set and if so it inserts all the required info. But this code doesn't look very 'streamlined' to me. Is there a better way?

mysql_select_db("inventory", $con);

if( !isset($_POST['productid2']) ) {
$sql="INSERT INTO shipped (id, type, client, product, color, quantity)
VALUES ('$_POST[productid]','$_POST[type]','$_POST[client]','$_POST[product]','$_POST[color]','$_POST[quantity]')";
}

if( isset($_POST['productid2']) ) {
$sql="INSERT INTO shipped (id, type, client, product, color, quantity)
VALUES ('$_POST[productid]','$_POST[type]','$_POST[client]','$_POST[product]','$_POST[color]','$_POST[quantity]'),
('$_POST[productid2]','$_POST[type2]','$_POST[client2]','$_POST[product2]','$_POST[color2]','$_POST[quantity2]')";
}

if( isset($_POST['productid3']) ) {
$sql="INSERT INTO shipped (id, type, client, product, color, quantity)
VALUES ('$_POST[productid]','$_POST[type]','$_POST[client]','$_POST[product]','$_POST[color]','$_POST[quantity]'),
('$_POST[productid2]','$_POST[type2]','$_POST[client2]','$_POST[product2]','$_POST[color2]','$_POST[quantity2]'),
('$_POST[productid3]','$_POST[type3]','$_POST[client3]','$_POST[product3]','$_POST[color3]','$_POST[quantity3]')";
}

    // And I have like this 5 more times, the code gets longer each time!


texts:
I did a few times ago what I called a plasma in plain JavaScript:

jsFiddle

The idea is to use 2 oscillators (LFO) which have their frequency + phase driven by two oscillators each. Then we use those 2 main oscillator output to decide of the r, g, b of each point.

To test the quite new API asm.js, I've ported it to be fully 'typed' and in complete memory isolation.

The big issue I encountered is that it is way slower with asm.js than with plain JavaScript. Worse: When I comment 'use asm' to have the browser interpret the code, I get better results (30% faster) than when the compilation succeeds.

The memory I use is:

A byte array of the size of the canvas: this is the output that I will putImageData on the canvas.
Right after I consider I have a float array that stores the values for the LFOs (base / amplitude / frequency / phase ), for 6 LFO.

I've made two versions, one fp32 and one fp64, none of which is fast (<50 ms per frame, when the plain object version is around 20ms).

Be sure to use a Browser that understands asm.js Firefox is one.

jsFiddle

jsFiddle

After experimenting, a lot of time is spent evaluating the LFO value:

function oscillatorValueAt(heap_f64_Index, x) {
    heap_f64_Index = heap_f64_Index | 0;
    x = +x;
    var base = 0.0,
        amp = 0.0,
        freq = 0.0,
        phase = 0.0;

    heap_f64_Index = heap_f64_Index << 3;
    base = +heap_f64[(heap_f64_Index + 0) >> 3];
    amp = +heap_f64[(heap_f64_Index + 8) >> 3];
    freq = +heap_f64[(heap_f64_Index + 16) >> 3];
    phase = +heap_f64[(heap_f64_Index + 24) >> 3];
    return  +(base + amp * sin(freq * x + phase));
}

This is called several times per pixel in the tickPixels sub, with calls like:

vaty = +oscillatorValueAt(osc1, yD);

Could you help me to find why there isn't a speed boost?

Edit : When the compilation to asm.js is a success, you see in the console :

Successfully compiled asm.js code (total compilation time 0ms; not stored in cache)

On the other hand, if one does not follow asm.js convention, one gets a message like :

TypeError: asm.js type error: must be of the form +x, fround(x), simdType(x) or x|0

If you see this message, the code is interpreted as plain javascript


texts: I made a Rock paper scissors game with Python 3.8

texts:
If you could rate my code, 1-10. What will it be and provide reasoning on why you gave that answer, i feel like i could of written this code better but i don't know what i am missing or what i could have done to make it better

import random
print('Lets play Rock Paper Scissors')

user_point = 0     #To keep track of the points
bot_point = 0

for tries in range (1,4):

    try:
        user_guess = input('Rock Paper Scissors? ')
        choices = ['Rock','Paper','Scissors']

        bot_guess  = random.choice(choices) #Will randomly pick from the list 'choices'

        while user_guess not in choices:#if the user tries to put in anything other then the choices given
            print('Please enter the choices above!')
            user_guess = input('Rock Paper Scissors? ')
    except ValueError:
        print('Please choose from the choices above ')  #Just in case user tries to put a different value type
        user_guess = input('Rock Paper Scissors? ')

    #DEBUG = "The bot did " + bot_guess

    #print(DEBUG)

    if user_guess == bot_guess:
        print('Tie!')
    elif user_guess == "Rock" and bot_guess == "Paper":
        print('The bot earns a point!')
        bot_point += 1
    elif user_guess == 'Paper' and bot_guess == "Rock":
        print('The user earns a point!')
        user_point += 1
    elif user_guess == 'Paper' and  bot_guess == 'Scissors':
        print('The bot earns a point')
        bot_point += 1
    elif user_guess == 'Scissors' and bot_guess == 'Paper':
        print('The user earns a point')
        user_point += 1
    elif user_guess == 'Rock' and  bot_guess == 'Scissors':
        print('The user earns a point')
        user_point += 1
    elif user_guess == 'Scissors' and bot_guess == 'Rock':
        print('The bot earns a point')
        bot_point += 1

print('After ' + str(tries) + ' tries. ' + ' The score is')
print('The User: ' + str(user_point))
print('The Bot: ' + str(bot_point))

if user_point > bot_point:
    print('THE USER IS THE WINNER!!!')
else:
    print('THE BOT IS THE WINNER!!!')


texts: Asking for player name and age using OOP

texts:
I have a text adventure game and I need to use OOP so I've chosen to use it when getting the player's name and age. I need to keep the OOP; but was wondering if there are any ways to clean up the code or simplify it while still getting the overall output.

class Player:
    def __init__(self):
        self.get_name()
        self.verify_age()

    def get_name(self):
        print("If you are ready lets begin!")
        while True:
            print("What is your name?")
            name = input(":> ")
            if not name.istitle():
                print("Please enter a name starting with a capital letter; try again.")
            else:
                self.name = name
                print("Hello " + name + " prepare for battle.")
                break

    def verify_age(self):
        while True:
            print("Before we begin please verify your age. \nWhat is your age?")
            age = input(":> ")
            try:
                if 8 < int(age) <= 110:
                    self.age = age
                    break
                elif int(age) <= 8:
                    print("You are not old enough to play the game! Try again.")
                else:
                    print("You can't be that old, come on! Try again.")
            except:
                print("That is not a valid number! Try again.")


texts: Frequency analysis for counting keywords

texts:
I have a CSV with around 10,000,000 lines. Each line looks like:

keyword1, keyword2, ....keywordn
keyword1, keyword2, ....keywordn
keyword1, keyword2, ....keywordn
keyword1, keyword2, ....keywordn

The script which does a frequency count and outputs to another text file:

from collections import Counter
import csv
import bz2
import sys

csv.field_size_limit(999999999)

all_terms = []

#with open('keywords.csv', 'rb') as f:
with bz2.BZ2File("keywords.csv.bz2", "r") as f:
    reader = csv.reader(f)
    for idx, row in enumerate(reader):
        for term in row:
            terms = term.split(",")
            for x in terms:
                all_terms.append( x.strip().lower() )
            if idx % 100000 == 0:
                print idx

c = Counter(all_terms)

with open("counts.txt", 'w+') as fl:
    for k,v in  c.most_common():
        fl.write( "{} | {}\n".format(k,v) )

I can't think of a way to minimize the memory utilization using generators and I'm not sure I could do a better job with the frequency counting job than the Counter class from the collections module.


texts: Selecting all movies where specified actors worked together

texts:
Here's a query I wrote trying to find all movies that three actors have been in together:

select distinct
    Movie
from
    CastMember
where
    Movie in (
        select Movie
        from CastMember
        where Actor = 1
    )
    and Movie in (
        select Movie
        from CastMember
        where Actor = 2
    )
    and Movie in (
        select Movie
        from CastMember
        where Actor = 3
    )

Movie and Actor are FKs to a Movie and Actor table. CastMember just has two columns: Movie and Actor.

Is there a better way to write this?

Update: thinking of just using INTERSECT

select Movie
from CastMember
where Actor = 1
intersect
select Movie
from CastMember
where Actor = 2
intersect
select Movie
from CastMember
where Actor = 3


texts:
I use this method to check if two reference types are equal

  public static bool AreEquals<T>(T source, object obj) where T : class
  {
     if (ReferenceEquals(source, obj))
        return true;

     var convertedTarget = obj as T;

     if (ReferenceEquals(convertedTarget, null))
        return false;

     List<object> equalityMembers = typeof (T).GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).Where(p => p.GetCustomAttribute<EqualityMemberAttribute>() != null).ToList<object>();
     equalityMembers.AddRange(typeof(T).GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).Where(p => p.GetCustomAttribute<EqualityMemberAttribute>() != null).ToList<object>());

     if (equalityMembers.Count == 0)
        return false; //The references were not equals and there is nothing to compare..

     var enumerator = equalityMembers.GetEnumerator();
     bool areEquals = true;

     while (enumerator.MoveNext() && areEquals)
     {
        var current = enumerator.Current;

        //On sait que FieldInfo et PropertyInfo ont la méthode GetValue
        var methodInfo = current.GetType().GetMethod("GetValue", new [] {typeof (object)});

        object valueSource = methodInfo.Invoke(current, new object[] {source});
        object valueObj = methodInfo.Invoke(current, new object[] {convertedTarget});

        areEquals = valueSource.Equals(valueObj);
     }
     return areEquals;
  }

I use attributes on properties/fields to find which of them are used to decide if the two objects are equals ex :

public class MyClass
{
    [EqualityMember]
    public int ID{get;set;}

    public override Equals(object obj)
    {
        return MyStaticClass.AreEquals(this,obj);
    }
}

It works very well but I am bothered with how I get the properties and fields in a list and use reflection to invoke the GetValue method, would you have any other alternatives? Or is there anything that seems flawed in my method?


texts: WPF async await TcpClient/TcpListener sample

texts:
I want to build a robust and highly scalable client server system. Here what I have so far(an echo server as my base of implementation)

My Server

    private void startServer_Click(object sender, RoutedEventArgs e)
    {
        if (anyIP.IsChecked == true)
        {
            listener = new TcpListener(IPAddress.Any, Int32.Parse(serverPort.Text));
            Logger.Info("Ip Address : " + IPAddress.Any + " Port : " + serverPort.Text);
        }
        else
        {
            listener = new TcpListener(IPAddress.Parse(serverIP.Text), Int32.Parse(serverPort.Text));
            Logger.Info("Ip Address : " + serverIP.Text + " Port : " + serverPort.Text);
        }
        try
        {
            listener.Start();
            Logger.Info("Listening");
            HandleConnectionAsync(listener, cts.Token);
        }
        //finally
        //{
            //cts.Cancel();
            //listener.Stop();
            //Logger.Info("Stop listening");
        //}

        //cts.Cancel();
    }

    async Task HandleConnectionAsync(TcpListener listener, CancellationToken ct)
    {
        while (!ct.IsCancellationRequested)
        {
            Logger.Info("Accepting client");
            //TcpClient client = await listener.AcceptTcpClientAsync();
            TcpClient client = await listener.AcceptTcpClientAsync();
            Logger.Info("Client accepted");
            EchoAsync(client, ct);
        }

    }

    async Task EchoAsync(TcpClient client, CancellationToken ct)
    {
        var buf = new byte[4096];
        var stream = client.GetStream();
        while (!ct.IsCancellationRequested)
        {
            var amountRead = await stream.ReadAsync(buf, 0, buf.Length, ct);
            Logger.Info("Receive " + stream.ToString());
            if (amountRead == 0) break; //end of stream.
            await stream.WriteAsync(buf, 0, amountRead, ct);
            Logger.Info("Echo to client");
        }
    }

    private void stopServer_Click(object sender, RoutedEventArgs e)
    {
        cts.Cancel();
        listener.Stop();
        Logger.Info("Stop listening");
    }

My Client

    private void connect_Click(object sender, System.Windows.RoutedEventArgs e)
    {
        IPAddress ipAddress;
        int port;

        //TODO Check if ip address is valid
        ipAddress = IPAddress.Parse(serverIP.Text);
        //TODO port range is 0-65000
        port = int.Parse(serverPort.Text);

        StartClient(ipAddress, port);
    }

    private static async void StartClient(IPAddress serverIpAddress, int port)
    {
        var client = new TcpClient();
        //can i try/catch to catch await exception?
        try
        {
            await client.ConnectAsync(serverIpAddress, port);
        }
        catch (Exception e)
        {
            Logger.Info(e);
        }
        Logger.Info("Connected to server");
        using (var networkStream = client.GetStream())
        using (var writer = new StreamWriter(networkStream))
        using (var reader = new StreamReader(networkStream))
        {
            writer.AutoFlush = true;
            for (int i = 0; i < 10; i++)
            {
                Logger.Info("Writing to server");
                await writer.WriteLineAsync(DateTime.Now.ToLongDateString());
                Logger.Info("Reading from server");
                var dataFromServer = await reader.ReadLineAsync();
                if (!string.IsNullOrEmpty(dataFromServer))
                {
                    Logger.Info(dataFromServer);
                }

            }
        }
        if (client != null)
        {
            client.Close();
            Logger.Info("Connection closed");
        }

    }


texts:
I'm new to programming; I started about a week ago and started learning python.
Currently, I only know some basic arithmetic operations in addition to some basic knowledge about lists, dictionaries, strings, etc.

I tried testing what I learnt so far. I made this prime number checker, which works except when the numbers are really big.  Please rate it and suggest improvements that I can understand at my current level.

Here is the code:

'''
pr means the number we'll be working on
dl is a dictionary that contains our the dividend and the reaminder
x is the dividend
e is a list that contains all remainders
and what the program does as you might have guessed already
it makes a list of all remainders of the division of our number by every integer before it
and checks for the number 0
if it finds it then the number is not prime
and if it doesn't then it's prime
'''

pr = int(input("Enter your number "))

print("\n")

dl = {}

x = pr - 1
while x < pr and x > 1 :
    r = pr % x
    dl[x]= r
    x -= 1

e = list(dl.values())

if any( z == 0 for z in e ) :
    print(pr," is not a prime number")
else :
    print(pr," is a prime number")

print("\n")

input("Press Enter to close the program")


texts: Removing code smell from Room Booking code

texts:
I am new with coding and I recently read an article about code refactoring, so I have made a console application for booking rooms on a ship. I need help with code refactoring. As far as I understand the refactoring, I think in my project there are only 2 parts where I need refactoring, which are as follows.

One is a block of for statements:

    ship1 = new Ship("Olympic Countess");

    ArrayList groupA = new ArrayList();
    for (int i = 0; i < 10; i++)
    {
        groupA.Add(new room(5000, "A" + (i + 1)));
    }

    ArrayList groupB = new ArrayList();
    for (int i = 0; i < 10; i++)
    {
        groupB.Add(new room(4000, "B" + (i + 1)));
    }

    ArrayList groupC = new ArrayList();
    for (int i = 0; i < 30; i++)
    {
        groupC.Add(new room(3500, "C" + (i + 1)));
    }

    ArrayList groupD = new ArrayList();
    for (int i = 0; i < 36; i++)
    {
        groupD.Add(new room(3400, "D" + (i + 1)));
    }

    ArrayList groupE = new ArrayList();
    for (int i = 0; i < 40; i++)
    {
        groupE.Add(new room(3300, "E" + (i + 1)));
    }

    ArrayList groupF = new ArrayList();
    for (int i = 0; i < 30; i++)
    {
        groupF.Add(new room(3400, "F" + (i + 1)));
    }

    ArrayList groupG = new ArrayList();
    for (int i = 0; i < 36; i++)
    {
        groupG.Add(new room(3300, "G" + (i + 1)));
    }

    ArrayList groupH = new ArrayList();
    for (int i = 0; i < 40; i++)
    {
        groupH.Add(new room(3200, "H" + (i + 1)));
    }

    ship1.addDeck("Balcony Suite", groupA);
    ship1.addDeck("Suite", groupB);
    ship1.addDeck("Deck 3 - Outside Twin", groupC);
    ship1.addDeck("Deck 2 - Outside Twin", groupD);
    ship1.addDeck("Deck 1 - Outside Twin", groupE);
    ship1.addDeck("Deck 3 - Inside Twin", groupF);
    ship1.addDeck("Deck 2 - Inside Twin", groupG);
    ship1.addDeck("Deck 1 - Inside Twin", groupH);
}

and the other one is the if else statement as follows:

public Reservation bookPassage(String cabinclass, Customer booker, int number)
  {
    ArrayList cabins;
    if (cabinclass.Equals("a", StringComparison.OrdinalIgnoreCase))
        cabins = ship1.getDeck("Balcony Suite");
    else if (cabinclass.Equals("b", StringComparison.OrdinalIgnoreCase))
        cabins = ship1.getDeck("Suite");
    else if (cabinclass.Equals("c", StringComparison.OrdinalIgnoreCase))
        cabins = ship1.getDeck("Deck 3 - Outside Twin");
    else if (cabinclass.Equals("d", StringComparison.OrdinalIgnoreCase))
        cabins = ship1.getDeck("Deck 2 - Outside Twin");
    else if (cabinclass.Equals("e", StringComparison.OrdinalIgnoreCase))
        cabins = ship1.getDeck("Deck 1 - Outside Twin");
    else if (cabinclass.Equals("f", StringComparison.OrdinalIgnoreCase))
        cabins = ship1.getDeck("Deck 3 - Inside Twin");
    else if (cabinclass.Equals("g", StringComparison.OrdinalIgnoreCase))
        cabins = ship1.getDeck("Deck 2 - Inside Twin");
    else
        cabins = ship1.getDeck("Deck 1 - Inside Twin");

What I don't understand is that my parameters are changing in both logic, so how can I make a separate method for this logic when my cabin class is changing every time?


texts:
I was working with some complicated generics system, and I found the need to make an abstraction for a typesafe mapping between K[T] and V[T] where T is the same for individual pairs.

In the case where the key or the value is T itself, we use a trick: type Identity[T] = T, and set the parameter to Identity. I have provided type aliases to make this usage more clear.

I would appreciate critiques on how I can make my code more robust, elegant, efficient, or idiomatic

/**
  * A map where the keys and values accept a type parameter, with a bound, and key-value pairs in the map have the same
  * type parameter.
  */
class TypeMatchingMap[K[_ <: B], V[_ <: B], B](private val contents: Map[Any, Any]) {
  def +[T <: B](kv: (K[T], V[T])): TypeMatchingMap[K, V, B] =
    new TypeMatchingMap[K, V, B](contents + kv)

  def -(k: K[_]): TypeMatchingMap[K, V, B] =
    new TypeMatchingMap[K, V, B](contents - k)

  def apply[T <: B](k: K[T]): V[T] =
    contents(k).asInstanceOf[V[T]]

  def get[T <: B](k: K[T]): Option[V[T]] =
    contents.get(k).map(_.asInstanceOf[V[T]])

  type Pair[T <: B] = (K[T], V[T])
  def toSeq: Seq[Pair[_]] =
    contents.toSeq.map(_.asInstanceOf[Pair[_]])

  override def toString: String = contents.toString

  override def equals(obj: scala.Any): Boolean =
    if (obj.isInstanceOf[TypeMatchingMap[Identity, Identity, _]])
      obj.asInstanceOf[TypeMatchingMap[Identity, Identity, Any]].contents == this.contents
    else false

  override def hashCode(): Int = contents.hashCode()
}

object TypeMatchingMap {
  type Identity[T] = T
  type Identified[K[_ <: B], B] = TypeMatchingMap[K, Identity, B]
  type Identifying[V[_ <: B], B] = TypeMatchingMap[Identity, V, B]

  private val _empty = new TypeMatchingMap[Identity, Identity, Any](Map.empty)
  def empty[K[_ <: B], V[_ <: B], B]: TypeMatchingMap[K, V, B] = _empty.asInstanceOf[TypeMatchingMap[K, V, B]]
}

object TypeMatchingMapTest extends App {
  sealed trait NumBox
  type BoxID[T <: NumBox] = UUID

  case class FloatBox(n: Float) extends NumBox
  case class DoubleBox(n: Double) extends NumBox
  case class IntBox(n: Int) extends NumBox

  var map: Identified[BoxID, NumBox] = TypeMatchingMap.empty[BoxID, Identity, NumBox]

  val id5f: BoxID[FloatBox] = UUID.randomUUID()
  map = map + (id5f -> FloatBox(5f))

  val id6d: BoxID[DoubleBox] = UUID.randomUUID()
  map = map + (id6d -> DoubleBox(6.0))

  val id7i: BoxID[IntBox] = UUID.randomUUID()
  map = map + (id7i -> IntBox(7))

  val f5: FloatBox = map(id5f)
  val d6: DoubleBox = map(id6d)
  val i7: IntBox = map(id7i)

  println(map)
  println(map.toSeq)
}

A use case? Say you have a map of entities, which are organized by UUIDs. The problem is that the type system does now acknowledge what kind of Entity an EntityID is pointing to. So, you can make a parametrized alias:

type EntityID[E <: Entity] = UUID

And store your entities in an Identified[EntityID, Entity]. Then, if you have, say an EntityID[Cow], you can pass it to the map and get your Cow.

Thank you, and for your troubles, a related image for your enjoyment:

   https://i.stack.imgur.com/ZT7o0.jpg


texts: Reusability vs simplicity in a small game with a set of interfaces

texts:
I have a small game I'm working on with a set of interfaces:

IHavePosition:

public interface IHavePosition<T>
{
    T Position { get; set; }
}

ICanMove:

public interface ICanMove<T> : IHavePosition<T>
    {
        IEnumerable<IMotor<T>> Motors { get; set; }
    }

ICharacter:

public interface ICharacter<TPos> : IHavePosition<TPos>, ICanMove<TPos>
{
    /// <summary>
    /// Gets or sets the action points.
    /// </summary>
    /// <value>
    /// The action points.
    /// </value>
    int ActionPoints { get; set; }

    /// <summary>
    /// Gets or sets the maximum action points.
    /// </summary>
    /// <value>
    /// The maximum action points.
    /// </value>
    int MaxActionPoints { get; set; }
}

IPlayer:

public interface IPlayer<TPos> : ICharacter<TPos>, IResetable
{
    /// <summary>
    /// Gets or sets the gold in the player's inventory.
    /// </summary>
    /// <value>
    /// The gold.
    /// </value>
    int Gold { get; set; }
}

IEnemy:

public interface IEnemy<TPos> : ICharacter<TPos>
    {

    }

As you can see, they all share a generic parameter TPos, which is the data type used to store an object's position. I keep this generic because I hope to reuse these interfaces in later projects which might have different position storage types (e.g. floating point coordinates versus an integer grid. 3D coordinates versus 2D, etc). The problem, however, is that this means when creating my classes, I need to ferry around this TPos generic construct to places where it doesn't make sense to define it. I'm left creating new Player<Vector3> or Player<Int2> instances all over the place when really I just want to be creating a Player.

An additional problem is that this might not (conceivably) be the only time I need to do this. What if I want to add a Health field that could be an int, or a float, etc? I'm now creating Player<Vector3,int> or Enemy<Int2, float> instances all over the place.

Since TPos is the same project-wide, is there a better way of doing this than lugging around references to TPos everywhere?


texts:
I'm currently creating an OAuth provider in Java using Jersey. To the best of my knowledge Jersey does not provide a method to create oauth tokens so I'm creating my own.

For those unfamiliar with OAuth, the tokens will be used in a somewhat similar fashion to public/private keys to sign and verify all requests to the server.

A String is formed using a token issued by the server (me) and then encrypted with that token secret (which only the server and the application know). The signature is then sent to the server and verified.

Each token must be:

non-sequential
non-guessable
unique (the tokens will be stored in a database so uniqueness can be verified)

This is the code I'm thinking of using to generate the keys:

public String generateToken() {
    SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
    MessageDigest digest = MessageDigest.getInstance("SHA-256");
    secureRandom.setSeed(secureRandom.generateSeed(128));
    return new String(digest.digest((secureRandom.nextLong() + "").getBytes()));
}

I'm generating a Long using Java's SecureRandom with SHA-1-PRNG.
Using a 128 bit seed again generated by SecureRandom.

I'm then using SHA-256 to hash the resulting Long to get a 32 character Unicode String as the token.

Is anyone able to see any issues with this style of token generation?
If multiple tokens were requested in a row, is there a chance of predicting the next one?
I assume that 32 characters is more than enough for this kind of request signing.


texts:
I am fairly new to HTML and CSS and have been trying to make things with whatever knowledge I have. I created a 'loader', but I'm certain that I have done things in ways more complicated than they need to be. Is there an easier solution to centering my elements? Is there an easier solution to add a bounce class to all three elements? How can I simplify my code?

body{
  background: #0BCCCA;
}
.cont {
  position: absolute;
  width: 100px;
  height: 100px;
  top: 50%;
  left: 50%;
  margin: -50px 0 0 -50px;
}

.element, .elem-1, .elem-2, .bounce, .bounce-2, .bounce-3 {
  position: absolute;
  width: 20px;
  height: 20px;
  top: 50%;
  left: 50%;
  opacity: .6;
  background-color: #ffffff;
  border-radius: 50%;
  animation: big 2s infinite ease-in-out;
}
.elem-1, .bounce-2 {
  position: absolute;
  width: 20px;
  height: 20px;
  top: 6%;
  left: 80%;
  background-color: #fff;
}
.elem-2, .bounce-3 {
  position: absolute;
  width: 20px;
  height: 20px;
  top: 6%;
  left: 20%;
  background-color: #fff;
}
.elem-1{
  animation-delay: -0.5s;
}
.elem-2{
  animation-delay: -.75s;
}
.bounce{
  animation-delay: -1s;
}
.bounce-2{
  animation-delay: -1.5s;
}
.bounce-3{
  animation-delay: -1.75s;
}

@keyframes big {
  0%, 100%{transform: scale(0.0)}
  50% {transform: scale(1.75)}
}
<!DOCTYPE html>

I've looked at different works and read articles, but because I haven't practiced much, I find it difficult implementing what I learn into my code. This is one of my first completed code, which almost all of I have done myself, without looking at other people's work or reading articles for help. I want you to evaluate the code and suggest areas of improvement, specifically where the code might be overcomplicated.


texts:
I was coding the problem here. I think I have solved it, but I ran into time limit exceeded issues. I am new in Competitive Programming, so I was looking for a better, time efficient logic for solving the same.

Time limit: 1 secs

My time: 3.01 secs

The problem in short:

  Given the numbers  [1 .. N ]  to be put in a binary search tree and a sequence of  m  searches  (\$s_1\$ , \$s_2\$ , . . . , \$s_m\$ ), solve the optimal BST problem
  with the cost as the sum of the distances between every two
  consecutive searches \$s_i\$ and \$s_{i+1}\$ on the BST.

  Cost(T,S) = Depth(\$s_1\$) + Distance(\$s_1\$, \$s_2\$) + Distance(\$s_2\$, \$s_3\$) + ... +
  Distance(\$s_{m-1}\$, \$s_m\$).

import sys

def getLevel(node, data):
    if (node.key == data) :
        return 1
    downlevel= 1+getLevel(node.left, data)
    if (downlevel != 0) :
        return downlevel
    downlevel = 1+getLevel(node.right,data)
    return downlevel

def pathToNode(node, path, k):
    path.append(node.key)
    if node.key == k :
        return True
    if ((node.left != None and pathToNode(node.left, path, k)) or
            (node.right!= None and pathToNode(node.right, path, k))):
        return True
    path.pop()
    return False

def distance(node, x, y):
    path1 = []
    pathToNode(node, path1, x)
    path2 = []
    pathToNode(node, path2, y)
    i=0
    while i<len(path1) and i<len(path2):
        if path1[i] != path2[i]:
            break
        i = i+1
    return (len(path1)+len(path2)-2*i)

class newNode:
    def __init__(self, item):
        self.key=item
        self.left = None
        self.right = None

def constructTrees(start, end):
    list = []
    if (start > end) :
        list.append(None)
        return list
    for i in range(start, end + 1):
        leftSubtree = constructTrees(start, i - 1)
        rightSubtree = constructTrees(i + 1, end)
        for j in range(len(leftSubtree)) :
            left = leftSubtree[j]
            for k in range(len(rightSubtree)):
                right = rightSubtree[k]
                node=newNode(i)
                node.left = left
                node.right = right
                list.append(node)
    return list

if __name__ == '__main__':
    b1,c1=input().split(' ')
    b1=int(b1)
    c1=int(c1)
    ar = input()  # 1 3 2 1 2
    ar = ar.split(' ')
    ar = [int(x) for x in ar]
    min= sys.maxsize
    totalTreesFrom1toN = constructTrees(1, b1)
    for i in range(len(totalTreesFrom1toN)):
        dist = getLevel(totalTreesFrom1toN[i],1)-1
        for j in range(len(ar)-1):
            dist=dist+distance(totalTreesFrom1toN[i], ar[j], ar[j+1])
        if(dist<min):
            min=dist
    print(min)

Can anyone tell me where I can possibly refine the code?


texts: Sock merchant from hackerrank - idiomatic typescript?

texts:
Sock Merchant

  John works at a clothing store. He has a large pile of socks that he must pair by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are.

  For example, there are \$ n = 7\$ socks with colors \$ar = [1,2,1,2,1,3,2]\$. There is one pair of color \$1\$ and one of color \$2\$. There are three odd socks left, one of each color. The number of pairs is \$2\$.

  Function Description

  Complete the sockMerchant function in the editor below. It must return an integer representing the number of matching pairs of socks that are available.

  sockMerchant has the following parameter(s):

  n: the number of socks in the pile
  ar: the colors of each sock

  Input Format

  The first line contains an integer \$n\$, the number of socks represented in \$ar\$.
  The second line contains \$n\$ space-separated integers describing the colors \$ar[i]\$ of the socks in the pile.

I just started learning typescript, and I don't know if this is good style:

import * as fs from 'fs';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputStringTemp = '';
let inputString: string[] = [];
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputStringTemp += inputStdin;
});

process.stdin.on('end', () => {
    inputString = inputStringTemp.replace(/\s*$/, '')
        .split('\n')
        .map(str => str.replace(/\s*$/, ''));

    main();
});

function readLine() {
    return inputString[currentLine++];
}

function sockMerchant(n: number, ar: number[]): number {
    // https://stackoverflow.com/questions/21070401/how-does-the-hash-variable-syntax-work-in-typescript/21071089#21071089
    // https://www.typescriptlang.org/docs/handbook/interfaces.html#indexable-types
    // https://stackoverflow.com/questions/44337856/check-if-specific-object-is-empty-in-typescript/44338054
    interface NumberMap {
        [index: number]: number;
    }

    // https://stackoverflow.com/questions/45571161/typescript-typing-map-object-and-instantiate-with-empty-object/45571346#45571346
    // https://stackoverflow.com/questions/29043279/how-to-use-string-indexed-interface-of-typescript/29043535#29043535
    let obj: NumberMap = {} as NumberMap;
    for (let key of ar) {
        // https://stackoverflow.com/questions/39590858/how-to-increment-a-value-in-a-javascript-object/39591127#39591127
        typeof obj[key] === 'undefined' ? obj[key] = 1 : obj[key]++;
    }
    let count = 0;
    // https://stackoverflow.com/questions/37699320/iterating-over-typescript-map/50232058#50232058
    for (const [key, value] of Object.entries(obj)) {
        // https://stackoverflow.com/questions/4228356/integer-division-with-remainder-in-javascript/4228376#4228376
        count += Math.floor(value / 2);
    }
    return count;
}

function main() {
    // https://stackoverflow.com/questions/45194964/how-to-assign-string-undefined-to-string-in-typescript/47553970#47553970
    // https://stackoverflow.com/questions/23314806/setting-default-value-for-typescript-object-passed-as-argument/44937766#44937766
    // const ws = fs.createWriteStream(process.env.OUTPUT_PATH!);
    const ws = fs.createWriteStream(process.env.OUTPUT_PATH || "output.txt");

    const n = parseInt(readLine(), 10);
    const ar = readLine().split(' ').map(arTemp => parseInt(arTemp, 10));
    let result = sockMerchant(n, ar);
    ws.write(result + "\n");

    ws.end();
}

https://www.hackerrank.com/challenges/sock-merchant/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=warmup


texts: Check whether a string has all unique characters (time efficiency)

texts:
I don't find this algorithm in Go language here, so I just want to check that it is really most efficient algorithm in Go:

func checkUnique(s *string) bool {

    var a [256]bool
    for _, ascii := range *s {

        if a[ascii] {
            return false
        }

        a[ascii] = true
    }

    return true
}


texts:
I have written the following Query to retrieve some object's ID. If there are objects in the list that have a larger numbinbatch than the saveditems number in the batch, then it should take that. If not, then it should take the first number from the lower number in batches.

I am wondering if this could be shortened. I'd also like to know if my query is bad for performance and how it can be improved.

int NextItemID = 0;
var items =
    rep.FindWhere(i => i.ID == itemID)
    .Select(i => i.Batch)
    .SelectMany(b => b.Items);

    var savedItem = items.First(i => i.ID == itemID);
    var unsavedItems = items.Where(i => i.StatusID == (short) ItemStatus.Pending);

    var higherNumInBatch = unsavedItems.Where(i => i.NumInBatch > savedItem.NumInBatch).OrderBy(i=>i.NumInBatch);
    var lowerNumInBatch = unsavedItems.Where(i => i.NumInBatch < savedItem.NumInBatch).OrderBy(i=>i.NumInBatch);

    if (higherNumInBatch.Any())
    {
       NextItemID = (int)higherNumInBatch.Take(1).First().ID;
    }
    else
    {
       NextItemID = (int)lowerNumInBatch.Take(1).First().ID;
    }

    return NextItemID;


texts: Forcing array of promises to complete before returning

texts:
I'm making one call to a mongoDB database to fetch a list of existing collections and then looping through the collection list and fetching their document count.

All db methods are promises and i'm getting them to fully resolve before responding to an API req. Here's my code

let records = {}
let promises = []

nosqldb.get().listCollections().toArray()
  .then(function(collections) {
    collections.map((coll) => {
      var collectionName = coll.name;
      var collection = nosqldb.get().collection(collectionName);
      promises.push(collection.count().then((count) => {
        records[collectionName] = count;
      }));
    });
    return Promise.all(promises);
  })
  .then(function() {
    return res.status(200).json(records);
  })
  .catch(function(err) {
    return res.status(500).send(err);
  });

As you can see , i'm looping through all collection names and asking the db to return their document count. I push these promises to an Promise array and having all of them resolve before sending the response.

Is this approach correct or is there a more elegant way?

Thanks


texts: JavaScript percentage calculation functions

texts:
I am building a calculator and I'm aware of what these functions do.

What I basically want feedback on is: Do I need to comment this or is there sufficient information to ascertain its purpose:

function percentOfValue(percentage, of) {
    return (percentage / 100) * of;
}

function whatPercentOfValue(small, large) {
    return (small / large) * 100
}


texts: Handling multiple MassTransit response types

texts:
I needed to publish a message across the ESB (MassTransit) that will return a different type of object depending on how the message is processed. I wanted to implement this in a generic way so I could wire up other services with similar requirements in the same way.

Publish a request

public IGenericResponse<TPayload> PublishRequest<TMessage, TPayload>(TMessage message, Type[] potentialResponseTypes)
        where TMessage : class
{
    IGenericResponse<TPayload> commandResult = null;

    _bus.PublishRequest(message, c =>
    {
        foreach (Type responseType in potentialResponseTypes)
        {
            Type genericHandler = typeof(GenericHandler<,>).MakeGenericType(new[]{ responseType, typeof(TMessage)});

            var handler = new Action<object>(result =>
            {
                commandResult = (IGenericResponse<TPayload>) result;
            });

            Activator.CreateInstance(genericHandler, new object[] {c, handler});
        }

        c.SetTimeout(10.Seconds());
    });

    return commandResult;
}

Generic Handler to wire it up

internal class GenericHandler<TPayload, TMessage>
    where TMessage : class
    where TPayload : class
{
    public GenericHandler(InlineRequestConfigurator<TMessage> configurator, Action<object> handler)
    {
        configurator.Handle<GenericResponse<TPayload>>(handler);
    }
}

Thoughts?


texts: Is this a "pythonic" method of executing functions based on the values of a tuple?

texts:
I have a situation where I have six possible situations which can relate to four different results. Instead of using an extended if/else statement, I was wondering if it would be more pythonic to use a dictionary to call the functions that I would call inside the if/else as a replacement for a "switch" statement, like one might use in C# or php.

My switch statement depends on two values which I'm using to build a tuple, which I'll in turn use as the key to the dictionary that will function as my "switch". I will be getting the values for the tuple from two other functions (database calls), which is why I have the example one() and zero() functions.

This is the code pattern I'm thinking of using which I stumbled on with playing around in the python shell:

def one():
    #Simulated database value
    return 1

def zero():
    return 0

def run():
    #Shows the correct function ran
    print "RUN"
    return 1

def walk():
    print "WALK"
    return 1

def main():
    switch_dictionary = {}

    #These are the values that I will want to use to decide
    #which functions to use
    switch_dictionary[(0,0)] = run
    switch_dictionary[(1,1)] = walk

    #These are the tuples that I will build from the database
    zero_tuple = (zero(), zero())
    one_tuple = (one(), one())

    #These actually run the functions. In practice I will simply
    #have the one tuple which is dependent on the database information
    #to run the function that I defined before
    switch_dictionary[zero_tuple]()
    switch_dictionary[one_tuple]()

I don't have the actual code written or I would post it here, as I would like to know if this method is considered a python best practice. I'm still a python learner in university, and if this is a method that's a bad habit, then I would like to kick it now before I get out into the real world.

Note, the result of executing the code above is as expected, simply "RUN" and "WALK".


texts:
I have written a plugin loader in Ruby, and I would like to know if it uses the best technique to handle classes, or if anyone has any recommendations on how to improve my code.

I have written a class called PluginManager, and an accompanying module named Plugin. The names of these are self explanatory, one handles the plugins (loading them), and the other is a module to be included by plugin files.

My Plugin module looks like the following, and currently just replaces the puts method, to ensure all output comes through the logger. I had some issues with making the @@logger variable definable, and I have solved it, but I'm not sure if there is a better way to solve it.

module Plugin
    @@logger = nil

    def puts(string)
        if @@logger.nil?
            super(string)
        else
            @@logger.info string
        end
    end

    # I tried the following, but it didn't work (still said "undefined method 'logger='")

    # class << self
    #   attr_accessor :logger
    # end

    def self.logger=(string)
        @@logger = string
    end
end

My PluginManager class is a bit more complex, but not by much. It simply takes an array of file names, performs some checks to ensure everything exists, then loads them into the loaded_plugins array.

class PluginManager

    def initialize(logger=nil)
        set_logger logger
        @loaded_plugins = []
    end

    def set_logger(logger)
        @logger = logger
        Plugin.logger = logger
    end

    def load(plugins, directory="./plugins/")

        # Iterate through plugins
        plugins.each do |plugin|

            # Work out plugin information
            class_name = plugin.split(".").first.downcase.capitalize
            full_path = directory + plugin
            @logger.info "Loading \"#{class_name}\" from \"#{full_path}\""

            # Ensure the plugin file exists
            if File.file? full_path

                # Load the plugin file and ensure the class exists
                require full_path
                unless eval("defined? #{class_name}")
                    @logger.error "Class \"#{class_name}\" not found!"
                    next
                end

                # Get the plugin's class and ensure it includes plugin
                plugin_class = eval class_name
                if plugin_class.ancestors.include? Plugin

                    # Ensure the initialize method takes no arguments
                    if plugin_class.allocate.method(:initialize).arity > 0
                        @logger.error "\"#{class_name}.initialize\" accepts more than 0 arguments"
                        next
                    end

                    # Load the plugin itself by pushing it into the loaded_plugins list
                    @logger.info "Plugin \"#{class_name}\" loaded!"
                    @loaded_plugins.push plugin_class.new
                    @logger.info "Plugin \"#{class_name}\" enabled!"
                else
                    @logger.error "The class \"#{class_name}\" does not include Plugin!"
                    next
                end
            else

                # Check if the file exists, or is a directory
                unless File.exist? full_path
                    @logger.error "Unable to find file \"#{full_path}\""
                else
                    @logger.error "\"#{full_path}\" is a directory!"
                end

                next
            end
        end
    end
end

I am wondering if there are any better ways to perform some of the checks, such as using exec to find if a class exists.


texts: Find maximum length of array where every entries are the same

texts:
Is the complexity of this code \$O(n^3)$? How can I improve the efficiency and reduce the complexity?

A = [3,2,4,2,4,2,4,5,3]
n= len(A)
def ALG2 (A,i,j):  #to check whether all entries between A[i] and A[j] are the same
    if i==j:
        return True
    for k in range (i,j-1):
        if A[k] != A[k+1]:
            return False
    return True

def  ALG1(A,n):   #find the max length of the arrays that are found in ALG2
    l=0
    for i in range (0,n-1):
        for j in range (i+1,n-1):
            if ALG2(A,i,j) and (j-i)>l:
                l= j-i

    return l

result = ALG1(A,n)

print (result)


texts:
My domain model consists mostly of simple DTOs, i.e. 'Data Transfer Objects' which this article distinguishes from 'Plain Old C# Objects', like this one:

public class Settings
{
    public bool FullScreen = false;
    public int WindowWidth = 800;
    public int WindowHeight = 600;
}

I realize this model is "anemic," but it works well with the JSON serializer I use for persistence. Also, I'm still in the exploratory stage of development and I read that it's okay at this point to have a bunch of "property bags."

Other classes look less like DTOs and more like POCOs (or POJOs although I'm using C#):

public class Sprite
{
    [JsonProperty]
    private readonly string assetName;

    [JsonProperty]
    private Vector2 position;

    // other properties...

    public Sprite( string assetName, Vector2 position )
    {
        this.assetName = assetName;
        this.position = position;
    }

    public void Move( Vector2 direction )
    {
        // do move
    }

    // other methods...
}

Because this type of object needs to be persisted by the JSON serializer, the properties need either to be public or have a JsonProperty attribute. I went with the attribute in this case because I want to restrict access to its properties.

Is this a good design? Does it make sense for my "entities" (I'm not sure if that's the correct term) to look so different from one another? My gut told me no, so I tried extracting the stuff not needed by the serializer into a separate class outside of the namespace:

public class SpriteModel
{
    private readonly Sprite sprite;

    public SpriteModel( Sprite sprite )
    {
        this.sprite = sprite;
    }

    public void Move( Vector2 direction )
    {
        // do move
    }

    public void GetSprite()
    {
        return sprite;
    }

    // other methods...
}

Now the Sprite class looks more like a DTO:

public class Sprite
{
    public string AssetName;
    public Vector2 Position;
    // other properties...
}

Someone told me that my domain model is actually the SpriteModel class now and not the Sprite class itself. I'm obviously confused about what to call these things exactly, and any clarification would be appreciated.

But my main question is: which of these approaches is better and why? Are they both terrible? And in that case is there another approach that I should use instead? If I go with the second approach, then I could have SpriteModel implement ISpriteModel, and the classes that use it could be more loosely coupled, which is a nice side benefit I think. But I don't want to go that route just for a side benefit that might not actually pay off (and could just add more complexity).


texts: Geolocation check and error management for Google Maps

texts:
I've written this code that I've been using for a while now to check for browser geolocation services for Google Maps applications. I have to say that I am not very happy with it as I've had to hack it quite a bit to work in IE9.

Could I please get some critical assessment of the following and possible suggestions for an elegant solution?  I need to stress that I do not want to use Modernizr or Gears. However, if there are good arguments, I'm willing to listen.

Notes: All the vars and functions in this script do pretty much as the function or var describes. All variables are declared as jQuery objects. start() launches Google Maps once the latitudes/longitudes are set.

function checkGeolocate()
{
    return 'geolocation' in navigator;
}

if (checkGeolocate())
{
    // Note that the if condition does not start until the end of the
    // entire geolocation procedure.

    if(navigator.geolocation.getCurrentPosition(function(position)
    {
        userLat.val(position.coords.latitude);
        userLng.val(position.coords.longitude);
        userDist.val(25);

        start();

        mapControls.fadeIn(200);
        mapOverlay.fadeOut(100);
    },
    function(error)
    {
        console.log(error);

        displayPostcodeSelect();
    },
    {
        timeout : 5000,
        maximumAge : 90000,
        enableHighAccuracy : true
    }))
    {
        // Do nothing as script has started
        // This if clause is to force IE9 to error out
        // instead of hanging when geolocation throws a PERMISSION_DENIED error.
    }
    else {
        displayPostcodeSelect();
    }
}
else
{
    console.log('no geo support');

    displayPostcodeSelect();
}


texts:
I am trying to solve this problem:

  Given an array of integers, return indices of the two numbers such that they add up to a specific target.

and this is my implementation:

public int[] twoSum(int[] numbers, int target) {
    Map<Integer, Integer> numbersMap = new HashMap<Integer, Integer>();
    int[] requiredNumbers = null;
    int index = 0;
    for (int number : numbers) {
        if (numbersMap.containsKey(target - number)) {
            requiredNumbers = new int[2];
            requiredNumbers[0] = numbersMap.get(target - number);
            requiredNumbers[1] = index;
            return requiredNumbers;
        } else {
            numbersMap.put(number, index);
            index++;
        }
    }
    return requiredNumbers;
}

How can I improve its execution time?


texts:
I've been working on numerals conversion lately. Now the JavaScript course I'm following asked me to do something similar for Roman numerals.
To keep things fresh and given the amount of test-cases provided I decided to write this one Test-Driven Development style. That is, for as much as I understand it.
First I check whether it's dividable by a full numeral (M, C, etc.). After that I have to reverse the string because the numerals were added in reverse order. The next step is to translate all combinations into their correct form using regex and a translation map. The functions were written in that order and fixing the problem the last part caused.
So far it looks very messy. Is this how one is supposed to solve problems TDD style? There is definitely a lot of code duplication going on, could this be fixed with another map?
Challenge

Convert the given number into a Roman numeral.
All Roman numerals answers should be provided in upper-case.

Test cases
convert(5) // "V".
convert(9) // "IX".
convert(12) // "XII".
convert(16) // "XVI".
convert(29) // "XXIX".
convert(44) // "XLIV".
convert(45) // "XLV"
convert(68) // "LXVIII"
convert(83) // "LXXXIII"
convert(97) // "XCVII"
convert(99) // "XCIX"
convert(500) // "D"
convert(501) // "DI"
convert(649) // "DCXLIX"
convert(798) // "DCCXCVIII"
convert(891) // "DCCCXCI"
convert(1000) // "M"
convert(1004) // "MIV"
convert(1006) // "MVI"
convert(1023) // "MXXIII"
convert(2014) // "MMXIV"
convert(3999) // "MMMCMXCIX"

Code
function convert(num) {
  roman = "";
  for (var i = 0; i < num; i++) {
    //MDCLXVI
    if (!(num % 1000)) { roman += "M"; num -= 1000; }
    else if (!(num % 500)) { roman += "D"; num -= 500; }
    else if (!(num % 100)) { roman += "C"; num -= 100; }
    else if (!(num % 50)) { roman += "L"; num -= 50; }
    else if (!(num % 10)) { roman += "X"; num -= 10; }
    else if (!(num % 5)) { roman += "V"; num -= 5; }
    else if (!(num % 1)){ roman += "I"; num -= 1; }
  }
  roman = roman.split('').reverse().join('');
  var translationMap = {
    DCCCC : 'CM',
    CCCC : 'CD',
    LXXXX : 'XC',
    XXXX : 'XL',
    VIIII : 'IX',
    IIII : 'IV',
  };
  for (var i in translationMap) {
    roman = roman.replace(new RegExp(i,'g'), translationMap[i]);
  }
  return roman;
}

convert(3999);

Run it at repl.it


texts: Downloading images from Reddit using Python 3

texts:
I have been working on this small project in order to fetch top-notch images from Reddit. Overall I am pretty confident about the code below but I am not entirely sure about whether my error handling conforms to best practices or not. (Obviously account-related data has been 'censored'.) Thoughts?

#!/usr/bin/env python3

import os
import praw # reddit API Wrapper
from urllib.error import URLError, HTTPError
import urllib.request as web
import shutil # shell utilities
import colorama
from colorama import Fore, Style

def main(subreddit_name = 'all', current_dir = os.getcwd()):
    reddit = praw.Reddit(
        client_id = 'censored',
        client_secret = 'censored',
        username = 'censored',
        password = 'censored',
        user_agent = 'subreddit crawler')

    dir_path = os.path.join(current_dir,subreddit_name)
    if not os.path.exists(dir_path):
        os.mkdir(dir_path)

    colorama.init(autoreset = True)
    subreddit = reddit.subreddit(subreddit_name).top(limit=1000)

    print("Download files...")

    for submissions in subreddit:
        if not submissions.stickied and submissions.score > 50:
            fullfilename = os.path.join(dir_path, "{}.jpg".format(submissions))
            request = web.Request(submissions.url, headers = {'User-Agent':'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0'})
            with web.urlopen(request) as response, open(fullfilename, 'wb') as out_file:
                try:
                    shutil.copyfileobj(response, out_file)
                except HTTPError as e:
                    print("{}{}{}".format(Fore.RED, e.code, Style.RESET_ALL))
                except URLError as e:
                    print("{}{}{}".format(Fore.RED, e.reason, Style.RESET_ALL))

            # delete corrupted files smaller than 55 KB
            filesize = os.path.getsize(fullfilename)
            if filesize < 55000:
                os.remove(fullfilename)
            else:
                # this is for debugging purposes only
                temp = "{}[{:07d}KB]{}".format(Fore.GREEN, filesize, Style.RESET_ALL)
                print("{} ID: {} URL: {}".format(temp, submissions, submissions.url))

    dir_count = len(os.listdir(dir_path))
    print("Download succeeded. {} files saved in '{}'.".format(dir_count, dir_path))

if __name__ == '__main__':
    main('PrequelMemes')


texts: Reach to the last index starting at index 0

texts:
The task:

  Given an integer list where each number represents the number of hops
  you can make, determine whether you can reach to the last index
  starting at index 0.

  For example, [2, 0, 1, 0] returns true while [1, 1, 0, 1] returns
  false.

My solutions:

// functional:
const reachLastIndexOf = (arr, start) => {
  if (arr[start] === undefined) return false;
  const next = start + arr[start];
  if (start === next || next >= arr.length) return false;
  if (next === arr.length -1) return true;
  return reachLastIndexOf(arr, next);
}
console.log(reachLastIndexOf([2, 0, 1, 0], 0)

// imperative:
const reachLastIndexOf2 = arr => {
  let start = 0;
  while(start < arr.length) { // I'm tempted to write `while(true)` here
    if (arr[start] === undefined) return false;
    const next = start + arr[start];
    if (start === next || next >= arr.length) return false;
    if (next === arr.length - 1) return true;
    start = next;
  }
}
console.log(reachLastIndexOf2([1, 1, 0, 1]));


texts:
I like to create tools for memoization since it can sometimes be useful. I recently created a generic tool for memoizing the results of pure functions.

Here is an example of how it works:

// Dummy function
auto func(int a, bool b)
    -> std::string
{
    // Some heavy computations
}

int main()
{
    auto memof_f = memoized(func);
    auto a = memo_f(5, true);
    auto b = memo_f(8, false);
    // ...
}

In this example, memo_f is a wrapper that calls func and memoizes its results. When called, it checks whether the result for the given arguments is in cache and computes it only if it is not.

Here is the implementation of memoized:

template<typename Ret, typename... Args>
class MemoizedFunction
{
    public:
        MemoizedFunction(const std::function<Ret(Args...)>& func):
            _func(func)
        {}

        auto operator()(Args... args)
            -> Ret
        {
            auto tuple_args = std::make_tuple(args...);
            if (not _memory.count(tuple_args))
            {
                auto res = _func(args...);
                _memory[tuple_args] = res;
                return res;
            }
            return _memory[tuple_args];
        }

    private:
        // Stored function
        std::function<Ret(Args...)> _func;
        // Map containing the pairs args/return
        std::unordered_map<std::tuple<Args...>, Ret> _memory;
};

template<typename Ret, typename... Args>
auto memoized(Ret (*func)(Args...))
    -> MemoizedFunction<Ret, Args...>
{
    return { std::function<Ret(Args...)>(func) };
}

Also, it's not of utmost importance, but I need these little functions in order to hash a tuple:

template<typename First, typename... Rest>
auto hash_all(First first, Rest... rest)
    -> std::size_t
{
    auto seed = std::hash<First>()(first);
    seed ^= hash_all(rest...);
    return seed;
}

template<typename First, typename Second>
auto hash_all(First first, Second second)
    -> std::size_t
{
    return std::hash<First>()(first) ^ std::hash<Second>()(second);
}

namespace std
{
    // Hash function for tuples
    template<typename... Args>
    struct hash<std::tuple<Args...>>
    {
        auto operator()(const std::tuple<Args...>& args) const
            -> std::size_t
        {
            return apply(hash_all<Args...>, args);
        }
    };
}

Note: the function apply is a function that uses the elements of a tuple as parameters for a given function, as proposed in N3802.

My question is simple: since this a low-level tool, which could be used in several contexts, is there any way to improve its performance at least a little bit? And while we are at it, do not hesitate to give tips for that construct to be more versatile too :)

Note: this class is only intended to work for pure (or "well-behaved" as of N3744) functions.


texts:
Today I created my second app - a simple body mass index calculator. The BMI is calculated by the following formula:

$$\dfrac{\text{weight}}{\text{(height)}^2}$$

The general meaning of the resulting BMI values:

\$<18.5\$ = underweight
\$18.5-25\$ = normal weight
\$25-30\$ = overweight
\$>30\$ = obese

My goal was to improve my skills and make something useful at the same time. I'm sharing my code in hope to get some constructive feedback. Is there anything I could improve?

My model file:

import Foundation

struct CalculatorBrain {
let weightInKG: Double
let heightInCM: Double

init(weightInKG: String, heightInCM: String) {
    self.weightInKG = Double(weightInKG) ?? 0.0
    self.heightInCM = Double(heightInCM) ?? 0.0
}

func calcBmi() -> Double {
    return weightInKG / ((heightInCM / 100) * (heightInCM / 100))
}
}

The ViewController:

class ViewController: UIViewController {

@IBOutlet weak var weightTextField: UITextField!

@IBOutlet weak var heightTextField: UITextField!

@IBOutlet weak var resultTextField: UILabel!

@IBAction func calculateBtn(_ sender: Any) {
    guard let weightInKG = weightTextField.text,
        let heightInCM = heightTextField.text else {
            return
    }
    let cm = CalculatorBrain(weightInKG: weightInKG, heightInCM: heightInCM)
    let result = cm.calcBmi()
    resultTextField.text = "BMI: \(result)"
}

}


texts:
The User Model

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class UserModel extends CI_Model
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('PermissionModel');
        $this->load->database('default');
    }

    public function getUserById($userId)
    {
        $this->db->select('login, name');
        $this->db->where('id', $userId);
        $queryUser = $this->db->get('user');
        return $queryUser->row(0);
    }

    #Function that returns the user object from the actual session.
    public function getUserFromSession()
    {
        $userId = $this->session->userdata('userId');
        $user = getUserById($userId);
        return $user;
    }

    public function listUsers()
    {
        if ($this->PermissionModel->checkPermission(__METHOD__)) {
            $this->db->select('login, nome');
            $queryUser = $this->db->get('usuarios');
            return $queryUser->result();
        }
    }
}

The PermissioModel

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class PermissionModel extends CI_Model
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('UserModel');
        $this->load->database('default');
    }

    #Essa função verifica se o usuário da sessão tem uma permissão para o método/ação passado como argumento.
    public function checkPermission($actionName)
    {
        $user = $this->UserModel->getUserFromSession();
        $this->db->select('user_id, action_id');
        $this->db->from('permission');
        $this->db->join('action','action.id=permission.action_id AND acao.nome='.'"'.$actionName.'"');
        $this->db->where('user_id',$user->id)
        $queryPermission = $this->db->get();
        #Se retornou somento um resultado, significa que o usuário tem acesso.
        if ($queryPermission->num_rows() == 1) {
            return true;
        }
        return false;
    }

}

So is there any better way to do this? Is my code reasonable? How can I make it testable?
I probably will use these models for all system here. So it will grow a lot and I'm omitting some of the details to simplify the example.


texts: Vectorize/speed-up exponentially weighted covariance calculation in R

texts:
I have the following 2-column data.frame:

Data <- data.frame(matrix(rnorm(100),ncol = 2))

I would like to calculate the variance-covariance matrix as the exponentially weighted average of the past squared/cross observations (on an expanding window):

Where delta is set to be 60/61. Thus, at t=4, the sum runs from 1 to 4, and the averages are computed over the first 4 observations. I have managed to implement a function calculating the upper triangular part of the covariance matrix, but it is quite slow. Does anyone have ideas to improve the speed?

rollEWCov <- function(Data){
  res <- c()
  for(i in 1:nrow(Data)){ # Expanding window of data used to calc covariances
    means <-  colMeans(Data[1:i,])
    Cov <- matrix(0,nrow = ncol(Data),ncol=ncol(Data))
    for(k in 1:ncol(Data)){ # first data-column
      l <- k
      while(l <= ncol(Data)){ # second data-column
        Sum <- 0
        for(j in 1:i){ # calc sum of exponentially weighted average of past returns
          Sum <- Sum + (1-60/61)*(60/61)^(j-1)*(Data[i-(j-1),k] - means[k])*(Data[i-(j-1),l] - means[l])
        }
        Cov[k,l] <- Sum
        l <- l + 1
      }
    }
    res[[i]] <- Cov
  }
  return(res)
}


texts:
I have a one function to calculate all the possible widths plus the margins for the gutters.

In this same function, the grid extensions such as the pull, pushand offset functions are also calculated.

@function calculate-one-column() {
  $a: 100%;
  @if ($gutter-width-px > 0px) {
    $a: ($a - ($gutter-width-procent * ($column-count - 1)));
  }
  @return $a / $column-count;
}

@function calculate-each-gutter() {
  @if ($gutter-width-px > 0px) {
    @return $gutter-width-procent;
  }
  @return 0;
}

@function calculate-function($function, $size, $first-child: false, $responsive: false) {
  $each-column: calculate-one-column() * $size;
  $each-gutter: calculate-each-gutter() * ($size - 1);
  @if ($function == 'size') {
    @return $each-column + $each-gutter;

  } @else if ($function == 'offset' and $first-child == false) and ($responsive == false) {
    @return $each-column + $each-gutter + ($gutter-width-procent * 1.5);

  } @else if ($function == 'push' or $function == 'pull') and ($responsive == false) or ($function == 'offset' and $first-child == true) {
    @return $each-column + $each-gutter + $gutter-width-procent;

  } @else if($function == 'offset' or 'push' or 'pull') and ($responsive == true)  {
    @return auto !important;
  }
}

The calculate-function @function is getting called by this piece of code:

@mixin make-grid-sizes() {
  @for $index from 1 through $column-count {
    &.#{$column-size}#{$index} {
      @include calculate-property('width', $index);
    }
  }
}

All of these functions are getting hold together with these variables:

$column-count: 12;
$row-max-width: 1024px;

$gutter-width-px: 15px !default;
$gutter-width-procent: percentage($gutter-width-px / $row-max-width);

The code works perfectly, but in my opinion it looks very messy.


texts:
I'm solving this in perl:

https://github.com/kennyledet/Algorithm-Implementations/tree/master/100_Doors_Problem

  Puzzle:
  There are 100 doors in a long hallway. They are all closed. The first time you walk by each door, you open it. The second time around, you close every second door (since they are all opened). On the third pass you stop at every third door and open it if it’s closed, close it if it’s open. On the fourth pass, you take action on every fourth door. You repeat this pattern for 100 passes.
  At the end of 100 passes, what doors are opened and what doors are closed?

This is my solution:

#!/usr/bin/env perl

use strict;
use warnings;
use utf8;
use feature qw(say);

my @doors = (0) x 100;

sub check_hallway {
    say "door ". ++$_ , $doors[$_] ? ' is open' : ' is closed' foreach 0 .. $#doors;
}

sub walk_hallway {
    for my $step ( 1 .. $#doors + 1 ) {
        for ( my $i = $step; $i < $#doors + 1; $i += $step ) {
            $doors[ $i ] ^= 1;
        }
    }
}

walk_hallway();
check_hallway();

Is there any better way to write this or any advice to keep in mind?


texts:
I use Nginx as a server, and I currently use this for configuration of each my sites. Basically, I have multiple files like this located in /etc/nginx/conf.d/.

#example.conf
server {
  listen             80;
  server_name        www.my-site.com  my-site.com;
  root               /var/www/html/my-site.com;

  location / {
         rewrite ^/category/(.*)$ /category.php?id=$1 last;
         rewrite ^/profile/(.*)$ /profile.php?id=$1 last;
         try_files $uri $uri/ /index.php?$query_string;
  }

  index  index.html index.htm index.php;

  error_page  404              /404.html;
        location = /var/www/html/nginx/error/404.html {
        root       /var/www/html/nginx/error/;
  }

  error_page   500 502 503 504  /50x.html;
       location = /var/www/html/nginx/error/50x.html {
       root        /var/www/html/nginx/error/error/;
  }

  location ~ \.php$ {
       fastcgi_pass   127.0.0.1:9000;
       fastcgi_index  index.php;
       fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
       include        fastcgi_params;
  }
}

So, I have 6 sites with their own file like this, and since I am about to do a complete re-install of my server, I would like to know how I can improve this configuration, both security and optimization wise.


texts:
I am pretty knew to the VBA world but I am really eager to improve my skills. I have a case where I would like to match cancellation with new business to see what we get back from our dropped business as new orders.

The matching is as follows: a variable called Fastighet (meaning "real estate" in Swedish) will be specified and takes a value from the dropped business and searches in the new orders business. If they match with same real estate then will check the date of new business if it is +/- 90 days then it will bring me back something called "Service-ID". The macros below work and get me the result but it takes 3 hours every time to finish matching as it matches 2200 rows in dropped business with 25000 rows of new orders!

My question is: Is there a way to make it faster?

Sub MatchingNedVSUpp()

Dim LRow, LRow2, i, n, serviceID As Long
Dim Fastighet As String

LRow = Sheet5.Range("A" & Rows.Count).End(xlUp).Row
LRow2 = Sheet6.Range("A" & Rows.Count).End(xlUp).Row

For i = 3 To LRow
    Fastighet = Sheet5.Range("CA" & i).Value
    For n = 3 To LRow2
       serviceID = Sheet6.Range("B" & n).Value

       If Sheet6.Range("BH" & n).Value = Fastighet And Sheet6.Range("AH" & n) <= Sheet5.Range("BM" & i) And Sheet6.Range("AH" & n) >= Sheet5.Range("BL" & i) And Sheet5.Application.WorksheetFunction.CountIf(Range("BU:BU"), serviceID) = 0 Then
           Sheet6.Range("B" & n).Copy
           Sheet5.Range("BU" & i).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
                     :=False, Transpose:=False
           Application.CutCopyMode = False
       End If
   Next n
Next i

End Sub


texts:
I'm just wondering if you see any ways I could simplify the following code without making it too difficult for a newbie to understand what I'm trying to do:

    if (trim($this->uri->segment(5)) == 1) {

    if ( $this->my_model->functionA($this->uri->segment(8),$this->uri->segment(4)) )
    {
        $data['light'] =  $this->my_model->data();
    }
    else
    {
        show_error($this->my_model->errormessage());
    }
    }
    elseif (trim($this->uri->segment(5)) == 0) {

      if ( $this->my_model->functionB($this->uri->segment(8),$this->uri->segment(4)) )
      {
          $data['light'] = $this->my_model->data();
      }
      else
      {
          show_error($this->my_model->errormessage());
      }
    }
    elseif (trim($this->uri->segment(5)) == 2) {

      if ( $this->my_model->functionC($this->uri->segment(8),$this->uri->segment(4)) )
      {

          $data['light'] = $this->my_model->data();
      }
      else
      {
          show_error($this->my_model->errormessage());
      }
    }

I guess I could use a switch statement but i would still need to check the results of each function call.  Would it still be beneficial to use switch?  if so, can you explain why?

Any suggestions would be appreciated.
thanks.


texts:
I'm taking the CS50 course, and we're asked to create a program which takes an input (the total height of the pyramid) and outputs a pyramid of that height.
i.e Here’s how the program might work if the user inputs 8 when prompted:
$ ./mario
Height: 8
       #  #
      ##  ##
     ###  ###
    ####  ####
   #####  #####
  ######  ######
 #######  #######
########  ########

Here is my code:
#include <cs50.h>
#include <stdio.h>

void print_hashes(int width, int empty_space);

int main(void)
{
    // Get height input between ranges 1 to 8 inclusive
    int height;
    do
    {
        height = get_int("Height: ");
    }
    while (height < 1 || height > 8);
    // Loops through each row
    for (int row = 1; row <= height; row++)
    {
        // Prints the left part of the pyramid, we need to print empty spaces before printing the hashes, so
        // the width is equal to the height, amount of hashes printed is equal to the row, so amount of empty spaces is the width - row
        print_hashes(height, height - row);
        printf("  ");
        // Prints the right part of the pyramid, we don't need to print empty spaces before printing hashes, so
        // the width is equal to the amount of hashes, i.e the row and the amount of empty space is just 0
        print_hashes(row, 0);
        printf("\n");
    }
}

void print_hashes(int width, int empty_space)
{
    // Loops through the column in the row
    for (int column = 0; column < width; column++)
    {
        // Checks if there needs to be an empty space within that column, if so print a space and if not print a hash
        if (column < empty_space)
        {
            printf(" ");
        }
        else
        {
            printf("#");
        }
    }
}

I would like some feedback on my code and how I could improve it; things like readability, efficiency, etc.
Is my code easily understandable? Am I overdoing the comments? The reason I put a lot of comments is because in my experience, when looking at code days/weeks after writing it, I tend to forget what it does. So I wrote explanations so that I can easily understand the code in the future.
How do I improve the style, and are there any code conventions I'm not following? Can I optimize this to make it a faster process? Or maybe there's a better way to do the same thing? Basically, how do I improve my code?


texts:
Here's the start of some code for a clock that can display time in 24 and 12 hours.

What could be added to it? How could I can apply notions such as OOP, model and Enums here?

public Clock {
    private int time = 0;

    public int get24hrTime(){
        return time;
    }

    public int set24hrTime( int newTime ){
        this.time = newTime;
    }

    public int get12hrTime(){
        if( time - 12 < 0 ){
            return time;
        } else {
            return time - 12;
        }
    }

    public String get12hrPostfix(){
        if( hours - 12 < 0 ){
            return "AM";
        } else {
            return "PM";
        }
    }
}


texts:
I am new to the OOP world I have been reading as much as I can about it and have never been more confused. I understand that its great for organizing code and making it more maintainable, etc. I have written some OOP code but I am unsure if its proper, it works fine though.

I am confused about public private functions along with extends and constructors. I haven't used them yet in my code and do not see where I would use them in a real life example. The more I read and try to understand it the more confused I get. I have included my code and was wondering if someone could point out mistakes, improvements, proper usage, organization. I feel it would help me better understand if someone with a lot of experience was to look at my code and give me pointers.

class userFunctions {

  const SALT_LENGTH = 9;

  //Retrieves encrypted password from database returns in variable $salt
  public function retrievePassword($conn,$username) {
    try{
      $stmt = $conn->prepare('SELECT `password` FROM `users` WHERE `userName`= :userName');
      $stmt->bindValue(':userName', $username);
      $stmt->execute();
      $salt = $stmt->fetchColumn();

        } catch (PDOException $e){
            echo 'Connection failed: ' . $e->getMessage();
        }
            return $salt;
    }

  //Generate an encrypted password method
  public function generateHash($password, $salt = null) {
    if ($salt === null) {
      $salt = substr(md5(uniqid(rand(), true)), 0, self::SALT_LENGTH);
    } else {
      $salt = substr($salt, 0, SALT_LENGTH);
    }
    return $salt . sha1($salt . $password);
 }

//Check database for duplicate username
  public function userCheck($conn,$userName) {
    try{
      $stmt = $conn->prepare('SELECT COUNT(*) FROM `users` WHERE `userName` LIKE CONCAT("%",:userName)');
      $stmt->bindValue(':userName', $userName);
      $stmt->execute();
      $count = $stmt->fetchColumn();
      return $count;
    } catch (PDOException $e){
      echo 'Connection failed: ' . $e->getMessage();
    }
  }

  //Add user to database
  public function Register($conn,$userName,$encryptedPass) {
    try{
      $stmt = $conn->prepare('INSERT INTO users (userName, password) VALUES (:userName, :password)');
      $stmt->execute(array(':userName' => strip_tags($userName), ':password' => $encryptedPass));
    }  catch (PDOException $e){
      echo 'Connection failed: ' . $e->getMessage();
    }
  }
}


texts:
I am trying to find the best way to structure this. I want to avoid if-else statements and reduce the number of code lines.

def get_parent(relationships,GU)
  parent = []
  if relationships.class == Array
    relationships.each do |y|
      if y[:relationship_roles][:relationship_role][:to_role][:name] == type
        parent << y[:party][:party_id][:id]
      end
    end
  else
    if relationships[:relationship_roles][:relationship_role][:to_role][:name] == type
      parent << relationships[:party][:party_id][:id]
    end
  end
  return parent
end

Input:

:relationship=>{:name=>nil, :party=>{:party_id=>{:id=>"12344",
:id_type=>"abc"}, :name=>"XYZ", :@active=>"true", :@type=>"Organization"},
:relationship_roles=>{:relationship_role=>{:to_role=>{:name=>"GU"}}}}

The input could be only one relationship or multiple ones, which is why I have the if/else loop.


texts: Get a limit number to test all the prime numbers it contains in C

texts:
My task was:

Write a program that accepts an integer as input and then displays all the prime
numbers smaller than or equal to that number.

And my code is:

#include <stdio.h>
void FindPrime(int number);

int main()
{
    int userInput, counter;
    printf("Please enter a limit number to test all the prime numbers it contains:\n");

    scanf("%d", &userInput);

    printf("The prime numbers %d contains are:\n", userInput);

    for (counter =  2; counter < userInput; counter++)
    {
        FindPrime(counter);
    }

    return 0;
}

void FindPrime(int number)
{
    int numberTest, nextNumber = 1;

    for (numberTest = 2; numberTest < number; numberTest++)
    {
        if (number%numberTest == 0 && numberTest < number)
            continue;
        else
            nextNumber++;
    }

    if (nextNumber == (number - 1))
        printf("%d ", number);
}

Can this code be improved?


texts: Task-List: Adding, updating and deleting tasks with CSS animations

texts:
I would really like to improve, so any feedback is so appreciated!

Tasks.js

class Tasks extends Component {
  constructor(props) {
    super(props)
    this.state = {
      tasks: [],
      nextId: null
    }
  }

  componentDidMount() {
    this.getTasks()
  }

  getTasks() {
    const tasks = List(this.state.tasks).push({ id: 1, name: 'Task 1'}, { id: 2, name: 'Task 2'}, { id: 3, name: 'Task 3'})
    this.setState({ tasks, nextId: 4 })
  }

  postTask() {
    const tasks = List(this.state.tasks).push({ id: this.state.nextId, name: `Task ${this.state.nextId}` })
    const nextId = this.state.nextId + 1
    this.setState({ tasks, nextId })
  }

  deleteTask(index) {
    const tasks = List(this.state.tasks).delete(index)
    this.setState({ tasks })
  }

  render() {
    return (

          {this.state.tasks.map((task, index) => (
            <Task
              key={task.id}
              deleteTask={() => this.deleteTask(index)}
              putTask={() => this.putTask(index)}
              name={task.name}
            />
          ))}

        <button onClick={() => this.postTask()}>

        </button>

    )
  }
}

Task.js

class Task extends Component {
  constructor(props) {
    super(props)
    this.state = {
      name: null,
      show: false,
      edit: false
    }
  }

  componentDidMount() {
    setTimeout(() => this.setState({ name: this.props.name, show: true }), 25)
  }

  onClickDelete() {
    this.setState({ show: false }, () => setTimeout(this.props.deleteTask, 250))
  }

  onClickEdit() {
    this.setState({ edit: true })
  }

  putTask() {
    this.setState({ edit: false })
  }

  onChangeInput(event) {
    this.setState({ name: event.target.value })
  }

  onKeyDownInput(event) {
    if(event.keyCode === 38) { // UP
      event.preventDefault()
    }
    if(event.keyCode === 13) { // ENTER
      this.putTask()
    }
  }

  render() {
    if(this.state.edit) {
      return (
        <input
          type='text'
          value={this.state.name}
          onChange={this.onChangeInput.bind(this)}
          onBlur={this.putTask.bind(this)}
          onKeyDown={this.onKeyDownInput.bind(this)}
          ref={input => input && input.focus()}
        />
      )
    }
    return (

        {this.state.name}

           this.onClickEdit()}>
           this.onClickDelete()}>

    )
  }
}


texts: The Next Palindrome: Is my code efficient?

texts:
I was trying to solve the Next Palindrome problem listed in SPOJ in Ruby language. Please find the problem statement here. Though i came up with the below solution, i could not get the execution time below 1.4s even after tweaking this code numerous times. Where can this code be optimized in terms of memory and execution time or is there a better approach than the solution i came up with?

def next_palindrome
  number = gets.chomp
  len = number.length
  if len == 1
    return "11\n" if number == "9"
    return number.next!<<"\n"
  end
  if len.even?
    f = len/2
    return number[0..f-1]<<number[0..f-1].reverse<<"\n" if number[0..f-1]>number[f..-1]
    number = number[0..f-1].next!
    return number<<number[0..f-1].reverse<<"\n"
  else
    f = (len-1)/2-1
    return number[0..f+1]<<number[0..f].reverse<<"\n" if number[0..f]>number[f+2..-1]
    number = number[0..f+1].next!
    return number<<number[0..f].reverse<<"\n"
  end
end

def input
  gets.chomp.to_i.times {print next_palindrome}
end

input