texts: Configuring MVC 5 project with service layer and DI and UOW

texts:
In the past I have always called the repositories directly from the controller, but that is a bad practice and now I am implementing a "Business Layer" to my project.

Would I have two UnitOfWorks?  One for the Service and then one for the repositories?

BaseController:

public class BaseController : Controller
{
    protected IUnitOfWorkService UnitOfWorkService;
    private readonly IEmployeeService _employeeService;

    protected BaseController(IUnitOfWorkService unitOfWorkService)
    {
        UnitOfWorkService = unitOfWorkService;
        _employeeService = unitOfWorkService.EmployeeService;
    }
}

HomeController:

public class HomeController : BaseController
{
    private readonly IEmployeeService _employeeService;

    public HomeController(IUnitOfWorkService unitOfWorkService) : base(unitOfWorkService)
    {
        _employeeService = unitOfWorkService.EmployeeService;
    }

    public ActionResult Index()
    {
        var emp = _employeeService.GetEmployee(employeeId);
        ...
    }

    ...
}

EmployeeService:

public class EmployeeService : IEmployeeService
{
    private IEmployeeRepository _employeeRepo;

    public EmployeeService(IUnitOfWork unitOfWork)
    {
        _employeeRepo = unitOfWork.EmployeeRepository;
    }

    public Employee GetEmployee(int employeeId)
    {
        return _employeeRepo.GetEmployee(employeeId);
    }

    ...
}

EmployeeRepository

public class EfEmployeeRepository : EfRepository, IEmployeeRepository
{
    public EfEmployeeRepository(SqlContext context) : base(context) { }

    public Employee GetEmployee(int employeeId)
    {
        var employee = Context.Employees
                    .SingleOrDefault(e => e.EmployeeId == employeeId);

        return employee != null ? employee.ToDomain() : null;
    }
}

Unit of Work

IUnitOfWorkService:

public interface IUnitOfWorkService : IDisposable
{
    IEmployeeService EmployeeService { get; }
}

UnitOfWorkService:

public class UnitOfWorkService : IUnitOfWorkService
{
    private readonly IUnitOfWork _unitOfWork;

    private EmployeeService _employeeService;

    public UnitOfWorkService()
    {
        _unitOfWork = new EfUnitOfWork();
    }

    public IEmployeeService EmployeeService
    {
        get { return _employeeService ?? (_employeeService = new EmployeeService(_unitOfWork)); }
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
            _unitOfWork.Dispose();
    }
}

IUnitOfWork:

public interface IUnitOfWork : IDisposable
{
    IEmployeeRepository EmployeeRepository { get; }
}

UnitOfWork:

public class EfUnitOfWork : IUnitOfWork
{
    private readonly SqlContext _context;

    private EfEmployeeRepository _employeeRepository;

    public IEmployeeRepository EmployeeRepository
    {
        get { return _employeeRepository ?? (_employeeRepository = new EfEmployeeRepository(_context)); }
    }

    public EfUnitOfWork()
    {
        _context = new SqlContext();
    }

    public void Save()
    {
        _context.SaveChanges();
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
            _context.Dispose();
    }
}

Register Dependencies

builder.RegisterType<EfUnitOfWork>().As<IUnitOfWork>().InstancePerRequest();
builder.RegisterType<UnitOfWorkService>().As<IUnitOfWorkService>().InstancePerRequest();


texts: All possible groups of combinations of array

texts:
Let's assume I have a one-dimensional array of integers of size n. My problem is to generate all the combination of all possible groups of size 1 to n, such as each combination has exactly one occurrence of each element. The order does not count:

[[1,2]] == [[2,1]]
[[1],[2]] == [[2],[1]]
[[1,2],[3,4]] == [[2,1],[4,3]] == [[4,3],[2,1]]...

For example, for the input array [1,2], I would get:

[[1,2]]
[[1],[2]]

With [1,2,3], I would have:

[[1,2,3]]
[[1,2],[3]]
[[1,3],[2]]
[[2,3],[1]]
[[1],[2],[3]]

And with [1,2,3,4]:

[[1,2,3,4]]
[[1,2,3],[4]]
[[1,2,4],[3]]
[[1,3,4],[2]]
[[2,3,4],[1]]
[[1,2],[3,4]] <= Equivalent to [[3,4],[1,2]]
[[1,3],[2,4]] <= Equivalent to [[2,4],[1,3]]
[[1,4],[2,3]] <= Equivalent to [[2,3],[1,4]]
[[1,2],[3],[4]]
[[1,3],[2],[4]]
[[1,4],[2],[3]]
[[2,3],[1],[4]]
[[2,4],[1],[3]]
[[3,4],[1],[2]]
[[1],[2],[3],[4]]

My code below is working but is actually very slow when the list has more than 6 elements:

public Set<Set<Set<Integer>>> recurseGroups(List<Integer> initialArray, List<Set<Integer>> currentGroups, int i) {
    if (i == initialArray.size()) {
        // Deep copy current group to save its content
        Set<Set<Integer>> copy = currentGroups.stream()
                .map(HashSet::new)
                .collect(Collectors.toSet());

        return Collections.singleton(copy);
    }

    Set<Set<Set<Integer>>> result = new HashSet<>();

    for (int j = i; j < initialArray.size(); ++j) {
        // Add a singleton group with the i-th integer
        // And generate groups with the remaining elements
        Set<Integer> newGroup = new HashSet<>(Collections.singletonList(initialArray.get(i)));
        currentGroups.add(newGroup);
        result.addAll(recurseGroups(initialArray, currentGroups, i + 1));
        currentGroups.remove(newGroup);

        // Add the i-th integer to each previous existing groups
        // And generate groups with the remaining elements
        for (int k = 0; k < currentGroups.size(); ++k) {
            currentGroups.get(k).add(initialArray.get(i));
            result.addAll(recurseGroups(initialArray, currentGroups, i + 1));
            currentGroups.get(k).remove(initialArray.get(i));
        }
    }

    return result;
}

// Calling line
Set<Set<Set<Integer>>> groups = recurseGroups(Arrays.asList(1,2,3), new ArrayList<>(), 0)

By adding a log in the stop condition, I noticed the code actually adds many times the same group combinations. I suspect it would be possible to improve the stop condition or the loop, but I don't see how.


texts: Single method for different parameterized mysql command

texts:
I currently have these two methods. One method returns all records, while the other one returns only a specific record.

function GetLeaveRequestDetailsAll($leaveCurrentStatus){

    global $connPDO;

    $sql = "select *, emp.Employee_Name, emp.Designation, emp.Emp_Dept_Category, lt.Leave_Name
            from tbl_emp_leave_details eld
            Inner join tbl_leave_types lt
            ON lt.leave_id = eld.leave_type
            Inner Join employee emp
            on emp.PK = eld.emp_id
            Inner JOIN dept_category dc
            ON emp.Emp_Dept_Category = dc.PK
            where eld.leave_current_status_id = :leave_current_status_id";

    $binds = array(
        ":leave_current_status_id"   =>  $leaveCurrentStatus
    );

    $statementEntryCount = $connPDO->prepare($sql);

    $statementEntryCount->execute($binds);
    $queryData = $statementEntryCount->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode($queryData);
}

function GetLeaveRequestDetailsById($leaveCurrentStatus, $leaveDetailId){

    global $connPDO;

    $sql = "select *, emp.Employee_Name, emp.Designation, emp.Emp_Dept_Category, lt.Leave_Name
            from tbl_emp_leave_details eld
            Inner join tbl_leave_types lt
            ON lt.leave_id = eld.leave_type
            Inner Join employee emp
            on emp.PK = eld.emp_id
            Inner JOIN dept_category dc
            ON emp.Emp_Dept_Category = dc.PK
            where eld.leave_current_status_id = :leave_current_status_id
            And eld.leave_detail_id = :leave_detail_id";

    $binds = array(
        ":leave_current_status_id"   =>  $leaveCurrentStatus,
        ":leave_detail_id"   =>  $leaveDetailId
    );

    $statementEntryCount = $connPDO->prepare($sql);

    $statementEntryCount->execute($binds);
    $queryData = $statementEntryCount->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode($queryData);
}

As you can see, both are doing the same work with a small difference, which is leave_detail_id. How can I convert these two functions into a single parameterized method to handle both queries?


texts:
I need to get folder names with the path for which I need to search the directory in a server with about 6000 folders. I have the following snippet of code to run through the folder and get the folder names with path. It works fine in a local directory but when I run the same code on a server directory it fails after about printing 86 folder names. The code works absolutely fine but stops working when run on a server directory with about 6000 folders. Excel freezes up and seems like it hangs.

Private Sub PrintFolders()
Dim objFSO As Object
Dim objFolder As Object
Dim objSubFolder As Object
Dim i As Integer
Application.StatusBar = ""
'Create an instance of the FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Get the folder object
Set objFolder = objFSO.GetFolder("C:\Temp")
i = 1
'loops through each folder in the directory and prints their names and path
On Error GoTo handleCancel
Application.EnableCancelKey = xlErrorHandler
MsgBox "This may take a long time: press ESC to cancel"
For Each objSubFolder In objFolder.subfolders
Application.StatusBar = objSubFolder.Path & " " & objSubFolder.Name
    'print folder name
    Cells(i + 1, 1) = objSubFolder.Name
    'print folder path
    Cells(i + 1, 2) = objSubFolder.Path
    i = i + 1
Next objSubFolder
handleCancel:
If Err = 18 Then
 MsgBox "You cancelled"
End If
End Sub


texts: Project Euler problem 44: sums and differences of pentagonal numbers

texts:
This is my code for solving the pentagonal number problem on Project Euler:

  Pentagonal numbers are generated by the formula, \$P_n=n\dfrac{3n−1}{2}\$.

  The
  first ten pentagonal numbers are:

1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...

  It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However,
  their difference, 70 − 22 = 48, is not pentagonal.

  Find the pair of
  pentagonal numbers, \$P_j\$ and \$P_k\$, for which their sum and difference are
  pentagonal and \$D = |P_k − P_j|\$ is minimized; what is the value of \$D\$?

As a beginner, I use the most basic concepts so often that sacrifices efficiency. If I could get some general tips on improving this code that would be awesome.

Key things I'd like to improve on:

How to deal with double for loops when using elements from 2 lists:

for x in a:
    for y in b:

And if there are any functions built into Python that I could use to instead of the bit of code written.

lst = []
dic = []
test = []
Final = []

for x in range(1, 3010):
    thing = int((x * (3*x - 1))/2)
    test.append(thing)
test = set(test)

for x in range(1, 3001):
    num = int((x * (3*x - 1))/2)
    lst.append(num)
lst = set(lst)

list2 = lst

for x in lst:
    for y in list2:
        num = x + y
        num2 = abs(x - y)
        dic.append({num: num2})

dic = [dict(t) for t in set([tuple(d.items()) for d in dic])]

for x in dic:
    for y in x:
        if y in test:
            Final.append(x)

for x in Final:
    for y in x:
        if x[y] in test:
            print(x)


texts: Ubuntu-Nginx lightweight server environment setup

texts:
Please review the following Bash script that uses to establish a "lightweight" Ubuntu-Nginx server environment mainly aimed to run small WordPress sites (about 5 plugins, about 25 webpages, about 25 images) on a cloud hosting platform.

The BASHRC heredocument sets aliases for personal scripts I already have and might use me later on.

apt-get update -y && apt-get upgrade -y && add-apt-repository ppa:certbot/certbot -y
ufw enable && ufw allow 22/tcp 80/tcp 443/tcp 9000/tcp && ufw allow 53/upd
apt-get install zip unzip tree unattended-upgrades sshguard postfix nginx python-certbot-nginx mysql-server php-fpm php-mysql php-mbstring php-mcrypt -y

sed -i "s/# gzip_/gzip_/g" /etc/nginx/nginx.conf
sed -i "s/max_size = .M/max_size = 200M/g" /etc/php/*/fpm/php.ini
sed -i "s/;cgi.fix_pathinfo=1/cgi.fix_pathinfo=0/g" /etc/php/*/fpm/php.ini
/etc/init.d/php*-fpm restart && systemctl restart nginx.service

cat <<-"BASHRC" >> /etc/bash.bashrc
    alias rss="/etc/init.d/php*-fpm restart && systemctl restart nginx.service"
    alias brc="nano /etc/bash.bashrc"
    alias www="cd /var/www/html"
    alias pma="tmux new-session -d 'bash ~/scripts/pma.sh"
    alias imb="bash ~/scripts/imb.sh"
BASHRC
source /etc/bash.bashrc


texts:
I wrote something to "compress" svg files. The svg files I am using often have comments and empty <g> tags, and I want to remove them. My main goal is not the speed of the compression, but the size of the compressed svg file.

Here is an example svg file: https://image.flaticon.com/icons/svg/222/222436.svg

And here is the code I am using:

public function compress($svg)
{
    $svg = preg_replace('/<!--.*-->/', '', $svg);
    $svg = preg_replace('/<g>[\n\r\s]*<\/g>/', '', $svg);
    $svg = preg_replace('/\n/', ' ', $svg);
    $svg = preg_replace('/\t/', ' ', $svg);
    $svg = preg_replace('/\s\s+/', ' ', $svg);
    $svg = str_replace('> <', '><', $svg);
    $svg = str_replace(';"', '"', $svg);

    return $svg;
}

Do you see any dangers here, perhaps this could ruin some svg files?
Is there something I could do to compress the file even more?
Is there any way to speed this up?


texts: Integer to binary using an old-school way

texts:
I know I could achieve this using System.out.println(Integer.toBinaryString(num)); in Java. However, I wanted to do it this way.

private static void toBinary(int x) {

    Scanner in = new Scanner(System.in);
    int num = in.nextInt();
    String s = "";

    while (num >= 2) {

      s = s + valueOf(num % 2);

      num = (int) num / 2;
    }

    String newS = new StringBuilder(s).reverse().toString();

    System.out.print(num + newS);
  }


texts: Memory management for fetching a list of drive letters on Windows

texts:
I'm using the WinAPI GetLogicalDriveStrings() function that requires a LPWSTR and am wondering if there is a safer way to do this to ensure there is no memory leak.

Currently I construct an initial pointer to a buffer buf using:

auto buf = GetLogicalDriveStrings(0, nullptr);

Then I create the LPWSTR to be used in lieu of the null pointer in my actual call using:

auto driveStrings = static_cast<LPWSTR>(malloc((buf + 1) * sizeof(WCHAR)));

Next I create a pointer to driveStrings to free it later. After checking if driveStrings is a null pointer or if the buffer (buf) is NULL (in case memory couldn't be allocated), I call GetLogicalDriveStrings() using driveStrings.

After I get the result I manually free() the LPWSTR using the pointer I made after allocating it.

How can I use a smart pointer for LPWSTR instead so I don't have to use malloc() and free(), but so that it will still work with the GetLogicalDriveStrings() function?

Mininum working example:

auto buf = GetLogicalDriveStrings(0, nullptr);

auto driveStrings = static_cast<LPWSTR>(malloc((buf + 1) * sizeof(WCHAR)));
auto pDriveStrings = driveStrings;

if (driveStrings == nullptr || buf == NULL)
{
    std::stringstream msg;
    msg << "Can't allocate memory for drive list: ";
    msg << GetLastError();
    throw std::runtime_error(msg.str());
}

// get drive strings
if (GetLogicalDriveStrings(buf, driveStrings) == NULL)
{
    std::stringstream msg;
    msg << "GetLogicalDriveStrings error: ";
    msg << GetLastError();
    throw std::runtime_error(msg.str());
}

// iterate over results
while (*driveStrings)
{
    // GetDriveType() requires a LPCWSTR
    if (GetDriveType(driveStrings) == DRIVE_FIXED || GetDriveType(driveStrings) == DRIVE_REMOVABLE)
    {
        std::wcout << driveStrings << std::endl;
    }
    driveStrings += lstrlen(driveStrings) + 1;
}

free(pDriveStrings);

If I use a std::wstring, I can't figure out how to iterate over each string in the driveStrings buffer. If I use a std::vector<WCHAR>, I can't figure out how to cast each element to an LPCWSTR for GetDriveType().

This works fine as is, but is there a better/safer way to do this? I'm open to any and all improvements.

Cross-posted on StackOverflow, but it has close votes because it is a better fit here.


texts: Does my first npm package follow best practices?

texts:
I have created my first npm package: https://github.com/sunnysideup/stretched-bg-image.
The purpose of the package is to add a class to a div (or any other block element in the HTML) depending on the width / height ratio of the div (panorama / landscape / portrait / skyscraper)
Below is the code. It works fine, but does it follow best practice?
Also, what is the best way to include the vanilla css
Here is the core code:
'use strict';

(
  function (root, factory) {
    if (typeof define === 'function' && define.amd) {
      define(factory)
    } else if (typeof exports === 'object') {
      module.exports = factory()
    } else {
      root.StretchedBgImages = factory()
    }
  }(
    typeof window !== 'undefined' ? window : this,
    function () {
      if (typeof window === 'undefined') {
        return null
      }

      /**
       *
       * @type {Function}
       * @constructor
       */
      const StretchedBgImages = function () {}
      StretchedBgImages.apply = function (opt) {
        // defaults ...
        const defaultClassRanges = [
          {
            max: '8',
            min: '2',
            className: 'panorama'
          },
          {
            max: '2',
            min: '1',
            className: 'landscape'
          },
          {
            max: '1',
            min: '0.5',
            className: 'portrait'
          },
          {
            max: '0.5',
            min: '0.125',
            className: 'skyscraper'
          }
        ]

        const defaultQueryString = '.stretched-bg-images'
        const defaultErrorClass = 'stretched-bg-images-error'

        // set options
        opt = opt || {}
        const classRanges = opt.classRanges || defaultClassRanges
        const queryString = opt.queryString || defaultQueryString
        const errorClass = opt.errorClass || defaultErrorClass

        // observer method
        const ro = new window.ResizeObserver(
          entries => {
            for (const entry of entries) {
              if (entry.target.handleResize) {
                entry.target.handleResize(entry)
              }
            }
          }
        )

        // find elements...
        const entries = document.querySelectorAll(queryString)

        // loop elements
        for (let i = 0; i < entries.length; ++i) {
          const entry = entries[i]
          ro.observe(entry)
          // set resize Method
          entry.handleResize = entry => {
            const height = entry.target.clientHeight
            const width = entry.target.clientWidth
            const ratio = width / height
            let hit = false
            for (let j = 0; j < classRanges.length; ++j) {
              const range = classRanges[j]
              if (ratio >= range.min && ratio <= range.max) {
                entry.target.classList.add(range.className)
                hit = true
              } else {
                entry.target.classList.remove(range.className)
              }
            }
            if (hit === false) {
              entry.target.classList.add(errorClass)
            } else {
              entry.target.classList.remove(errorClass)
            }
          }
        }
      }
      return StretchedBgImages
    }
  )
)
```


texts:
I have the following query which retrieve all those who have ordered a book_id n°10 and but never ordered the book with id n°1.
http://sqlfiddle.com/#!9/1bb9e8/44
|user_id | book_id |
| 1 | 1 |
| 1 | 2 |
| 1 | 3 |
| 2 | 1 |
| 2 | 10|
| 2 | 9 |
| 3 | 5 |
| 3 | 10|
| 4 | 6 |
| 4 | 7 |
| 4 | 10|
| 8 | 8 |

select u.user_id,o.book_id
from users u
inner join c
  on u.user_id = o.user_id
    and  o.book_id = 10
 where u.user_id not in (
 select 02.user_id
   from orders o2
  where o2.book_id = 1 );

The keyword "except" is not available on MariaDB 10.1
What are the others way can this be written in SQL aside using a CTE that would be efficient ?


texts: Program to provide CRUD operations for a Boxers(Fighter) table in a database

texts:
I have been through a few SQLite tutorials and wrote this code on my own to reinforce the principles. The tutorials I went through varied widely in a few areas so this is what I came up with as a combination of everything.

Other than the two classes I have listed below, all I have is one activity that adds, remove, inserts, update and display data from the database.

I have a few specific questions:

When should I close the helper class or does garbage collection deal with it automatically?
Should I create a Boxer POJO (Plain Old Java Object) to pass boxer data to and from the DAO?
Is the DAO implementation efficient?
Does the code deviate from Java and Android best practices in any way?

Helper Class

public class BoxScoresHelper extends SQLiteOpenHelper {

    private static final String DB_NAME = "boxing_scores.db";
    private static final int VERSION = 1;
    private static BoxScoresHelper instance = null;

    public static BoxScoresHelper getInstance(Context context){

        if(instance == null){

            instance = new BoxScoresHelper(context);

        }

        return instance;
    }

    private BoxScoresHelper(Context context) {
        super(context, DB_NAME, null, VERSION);

    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL(createBoxerSQLString());

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        db.execSQL("Drop Table If Exists " + BoxerDAO.TABLE_NAME);
        onCreate(db);

    }

    private String createBoxerSQLString(){

        String boxerCreateString = "create table " + BoxerDAO.TABLE_NAME +
                "(" + BoxerDAO._ID + " Integer Primary Key AutoIncrement, " +
                BoxerDAO.BOXER_NAME +  " Text Not Null, " +
                BoxerDAO.WEIGHT_CLASS + " Text Not Null, " +
                BoxerDAO.WINS + " Integer Not Null, " +
                BoxerDAO.LOSSES + " Integer Not Null);";

        return boxerCreateString;
    }

}

DAO Class

public class BoxerDAO {

    public static final String TABLE_NAME = "Boxer";
    public static final String _ID  = "_id";
    public static final String BOXER_NAME = "boxer_name";
    public static final String WEIGHT_CLASS = "weight_class";
    public static final String WINS = "wins";
    public static final String LOSSES ="losses";

    private final BoxScoresHelper myScoresHelper;
    private SQLiteDatabase myBoxerDB;

    public BoxerDAO(Context context){

        myScoresHelper = BoxScoresHelper.getInstance(context);

    }

    public Cursor query(String[] projection,String selection,String[] selectionArgs, String orderBy){

        Cursor cursor;
        myBoxerDB = myScoresHelper.getReadableDatabase();

        cursor = myBoxerDB.query(TABLE_NAME, projection, selection, selectionArgs, null, null, orderBy);

        //myBoxerDB.close();

        return cursor;

    }

    public Cursor queryAll(){

        Cursor cursor;
        myBoxerDB = myScoresHelper.getReadableDatabase();

        cursor = myBoxerDB.rawQuery("Select * From " + TABLE_NAME, null);

        //myBoxerDB.close();
        return cursor;

    }

    public int delete(int id){

        int rowsDel;
        myBoxerDB = myScoresHelper.getWritableDatabase();

        rowsDel = myBoxerDB.delete(TABLE_NAME, _ID + " = " + id , null);

        //myBoxerDB.close();
        return rowsDel;

    }

    public long insert(ContentValues values){

        long insertId = -1;

        myBoxerDB = myScoresHelper.getWritableDatabase();

        insertId = myBoxerDB.insert(TABLE_NAME, null, values);

        //myBoxerDB.close();

        return insertId;

    }

    public int update(ContentValues values,String selection, String[] selectionArgs){

        int updatedRows;
        myBoxerDB = myScoresHelper.getWritableDatabase();

        updatedRows = myBoxerDB.update(TABLE_NAME, values, _ID + " = " + selection, selectionArgs);
        //myBoxerDB.close();

        return updatedRows;

    }

}


texts: Parsing key-value pairs to fill a struct

texts:
I must read and extract some values from string. These values are coded like this:

k="11,3,1" v="140.3"

I have defined the codes and created struct with all field as well as a temp one where I store k and v. In fillFields proc I transfer values from temp struct to the right one (with the valid types). It works but I have many fields and fillFields would need to have many if-conditions. Maybe someone could give me any hint how to write it smarter.

The simplified code now:

   #define ASK                       "11,3,1"
   #define BID                       "11,2,1"
   #define CLOSE                     "3,1,1"

    typedef struct tic {

      float ask;
      float bid;
      float close;
    }tic, *ticP;
    typedef struct pElem {
      char       * k;
      char       * v;
    }pElem, *pElemP;

    void fillFields(ticP t, pElemP p)
    {
      if (strcmp( ASK, p->k)==0)
      {
        printf ("ASK %s\n", p->v);
        t->ask = atof(p->v);
      }
      if (strcmp( BID, p->k)==0)
      {
        printf ("BID %s\n", p->v);
        t->bid = atof(p->v);
      }
      if (strcmp( CLOSE, p->k)==0)
      {
        printf("CLOSE >>>%s<<<\n", p->v)    ;
        t->close =  atof (p->v);
      }
    }


texts: A method to log and display text in a console screen simultaneously.

texts:
I had always had the necessity to display long text outputs on the console screen. The size of the text displayed usually exceeds the amount of text that can be accessed by scrolling up through he console output. Also, there had been times when I wanted to look at the output history, to spot out abnormalities or bugs. Doing this was difficult until I decided to write a  logger. Logging all the output text to a file, and simultaneously displaying it solves the above problems.

Source code:

#ifndef FILELOGGER_H_
#define FILELOGGER_H_

#include <fstream>
#include <iostream>
#include <string>

class FileLogger;

template <class Type>
FileLogger& operator << ( FileLogger& logCout, const Type& data);

class FileLogger {
    std::string fileName;
    bool __linkWithFile;
    bool __linkWithCout;
    bool __appendToFile;
public:

    FileLogger(const std::string& pfileName, bool pAppendToFile = true): fileName(pfileName),
                                              __linkWithFile(true),
                                              __linkWithCout(true)
                                              {
        if (pfileName == "<null>") {
             __linkWithFile = false;
        }

        __appendToFile = pAppendToFile;
    }
    FileLogger(const FileLogger& flog) {
        fileName       = flog.fileName;
        __linkWithFile = flog.__linkWithFile;
        __linkWithCout = flog.__linkWithCout;
        __appendToFile = flog.__appendToFile;
    }

    void linkWithCout() {
        __linkWithCout = true;
    }

    void unlinkWithCout() {
        __linkWithCout = false;
    }

    void linkWithFile() {
        __linkWithFile = true;
    }

    void unlinkWithFile() {
        __linkWithFile = false;
    }

    template <class Type> friend FileLogger& operator << ( FileLogger& logCout, const Type& data);

    void flush_console() {
        std::cout.flush();
    }

    ~FileLogger(){}

};

template <class Type>
FileLogger& operator << ( FileLogger& logCout, const Type& data) {
    if(logCout.__linkWithCout)
        std::cout << data;
    if(logCout.__linkWithFile) {
        std::ofstream fout;
        fout.open(logCout.fileName.c_str(),
                                            ((logCout.__appendToFile) ?(std::ios::out | std::ios::app) :
                                                    std::ios::out) );
        logCout.__appendToFile = true;
        fout << data;
    }
    return (logCout);
}

#endif

Example usage:

FileLogger logCout ("log.text", false);

// writes to both the screen and to the file `log.text`.
logCout << "Hello " << "World";
// appends the next line to the file by default.
logCout << "!";

 Explanation:

The functions, void linkWithCout() and void unlinkWithCout() can be used to force the class to write the output text to the screen and refrain from writing the output text to the screen respectively.
The functions, void linkWithFile() and void unlinkWithFile() can be used to force the class to write the output text to the file and refrain from writing the output text to the file respectively.

Is there a better way to achieve this functionality? Or is there any possible modifications that could help this become more useful (probably like linking this to multiple log files)?


texts: Producing residues of combinatorics on strings

texts:
Basically, this code does multiplication of chosen operations.

public static String[] gen8String(String[] pattern1, String[] pattern2){
    String[] combinedSubset = new String[90]; //emty array for the subset of 90 strings
    String  combinedString = ""; //string holder for each combined string
    int index = 0; //used for combinedSubset array
    int present = 0; //used to check if all 6 characters are present

    for(int i = 0; i < 15; i++){

        for(int j = 0; j < 15; j++){
            combinedString = pattern1[i] + pattern2[j]; //combine both 4 letter strings into 8 char length string
            char[] parsedString = combinedString.toCharArray(); //parse into array

            //check if all 6 characters are present
            for(int k = 1; k <= 6; k++)
            {
                if(new String(parsedString).contains(k+"")) {
                    present++;
                }
                else
                    break;
                //if all 6 are present, then add it to combined subset
                if(present == 6)
                    combinedSubset[index++] = combinedString;
            }
            present = 0;
        }
    }
    return combinedSubset;
}

Let's look at an example:

Let's says I have 2 strings ABCDEF and ACDEBF. Now before I call gen8string, I will first perform a \${6 \choose 4}\$ deletion operation on each string. For instance, I will take ABCDEF delete any two characters in that string and I am left with substring of length 4. How many different such strings can I have (given all the letters are unique)? \$15 = {6 \choose 4}\$. Now, I will do the same for both strings. Now I am left with 2 string arrays, each of size 15.

In gen8String, I am passing in the 2 above mentioned arrays and I am combining the substrings under the following constraints:

I can only combine 2 strings to make one 8-length string (4+4).
I can only combine them if there are no overlapping missing characters.

What do I mean by the 2nd point? Well, let's say I one of the inputs in pattern is ABCD and in pattern2 one of the inputs is ACDE. These 2 substrings cannot be combined because there are overlapping missing characters, i.e. the F. However, if I have ABCD in pattern1 and CDEF, these can be combined because all 6 characters are present in the 8-length string at least once. So, no overlapping missing characters. This can be seen by tracing through the code.

As a concluding note, this function essentially does a

$${{6}\choose{4}} * {{4}\choose{2}} = 90$$

How can I optimize/generalize this code? Ways to improve it?


texts: Insert and update SQL entries for posts to be accessed by up to 3 other users

texts:
At first, I have this HTML I use here:

body {
  text-align: center;
}
<form method='post' action=''>
  <input type='text' placeholder='post' name='post'>

    <input type='text' placeholder='ref1' name='ref1'>
    <input type='text' placeholder='ref1id' name='ref1id'>

    <input type='text' placeholder='ref2' name='ref2'>
    <input type='text' placeholder='ref2id' name='ref2id'>

    <input type='text' placeholder='ref3' name='ref3'>
    <input type='text' placeholder='ref3id' name='ref3id'>

  <input type='submit' name='submit'>
</form>

I receive the data using PHP and send it like this:

<?php
if (isset($_POST['submit'])) {
  $post = $_POST['post'];

  $ref1 = $_POST['ref1'];
  $ref1id = $_POST['ref1id'];

  $ref2 = $_POST['ref2'];
  $ref2id = $_POST['ref2id'];

  $ref3 = $_POST['ref3'];
  $ref3id = $_POST['ref3id'];

  $stmt = $conn->prepare($Query)
  $stmt->execute([
    'post' => $post,
    'ref1' => $ref1,
    'ref1id' => $ref1id,
    'ref2' => $ref2,
    'ref2id' => $ref2id,
    'ref3' => $ref3,
    'ref3id' => $ref3id
  ])

}
?>

Then I apply this SQL Query to INSERT the data:

INSERT INTO `posts` (`post`, `ref1`, `ref1id`, `ref2`, `ref2id`, `ref3`, `ref3id`) VALUES (:post, :ref1, :ref1id, :ref2, :ref2id, :ref3, :ref3id)

And this one to UPDATE the data:

UPDATE `posts` SET `post` = :post, `ref1` = :ref1, `ref1id` = :ref1id, `ref2` = :ref2, `ref2id` = :ref2id, `ref3` = :ref3, `ref3id` = :ref3id

in/of this MYSQL Table: http://sqlfiddle.com/#!9/7d22d8/1/0

The idea is that the user can make a private post for 3 people only, He writes their name in ref[x] and their passcode which is ref[x]id


texts: Shutdown-Script for Don't Starve Together Dedicated Server

texts:
I have written my first LUA-Script/Function to shut down the Dedicated Server for Don't Starve Together.
I wanted to shut down the server in 2 minutes and inform everyone on the server that the server is shutting down.
The function os.execute is nil in the dedicated server console, so I can't use os.execute("sleep " .. seconds).

Can I improve something on this script? Is it best practice?

function sleep(seconds)
    local t = os.time()
    local diff = 0
    while diff < seconds do
        diff = os.difftime(os.time(), t)
    end
end

local steps = {120,60,30,10,5,4,3,2,1}
local n = table.getn(steps)
for i=1,n-1,1 do
  TheNet:SystemMessage("The server shuts down in " .. steps[i] .. " seconds")
  sleep(steps[i] - steps[i+1])
end
TheNet:SystemMessage("The server shuts down in " .. steps[n] .. " seconds")
sleep(steps[n])
TheNet:SystemMessage("The server is shutting down now")
c_shutdown(true)

Link to the server command list for Don't Starve.

TheNet:SystemMessage prints the message into the chat
c_shutdown(true) shutdown the server and persist the world


texts:
Below is a C++ implementation of the Command Pattern. I wrote three receivers that carry out the intended action (making a sound) differently. I also wrote command and invoking classes. I saw no need to write a client class, so main() is the client.

#include <iostream>
#include <string>

// receivers

class Cow {
public:
    void moo() {
        std::cout << "Cow says moo!" << std::endl;
    }
};

class Dog {
    std::string name;
public:
    Dog(const std::string& name) : name(name) {}

    void makeSound() {
        std::cout << name + " barks!" << std::endl;
    }
};

class Car {
    bool engineOn;
public:
    Car() : engineOn(false) {};

    void turnCarOn() {
        engineOn = true;
    }

    void revEngine() {
        if (engineOn) {
            std::cout << "Vroom, vroom, vroom!" << std::endl;
        }
        else {
            std::cout << "Silence!" << std::endl;
        }
    }
};

// commands

class Command {
public:
    virtual void execute() = 0;
};

class CowCommand : public Command {
    Cow cow;
public:
    CowCommand(Cow cow) : cow(cow) {}

    void execute() {
        cow.moo();
    }
};

class DogCommand : public Command {
    Dog dog;
public:
    DogCommand(Dog dog) : dog(dog) {}

    void execute() {
        dog.makeSound();
    }
};

class CarCommand : public Command {
    Car car;
public:
    CarCommand(Car car) : car(car) {}

    void execute() {
        car.turnCarOn();
        car.revEngine();
    }
};

// invoker

class PlatoSays {
    Command* ptr_command;
public:
    PlatoSays() : ptr_command(nullptr) {}

    void setCommand(Command* ptr_cmd) {
        ptr_command = ptr_cmd;
    }

    void invokeCommand() {
        if (ptr_command) {
            std::cout << "Plato says: ";
            ptr_command->execute();
        }
        else {
            std::cout << "Plato has nothing to say!" << std::endl;
        }
    }
};

// client

int main() {
    PlatoSays plato;

    plato.setCommand(new CowCommand(Cow()));
    plato.invokeCommand();

    plato.setCommand(new DogCommand(Dog("Lucky")));
    plato.invokeCommand();

    plato.setCommand(new CarCommand(Car()));
    plato.invokeCommand();

    getchar();
}


texts: Send an email if a URL is down twice only

texts:
We want to check if a URL is down or not. But sometimes, the environment is down for maintenance for 3-4 hours and we don't want to keep sending emails during that time.

I have written a shell script for performing a URL check and running it every 30 mins using a cronjob.

The actual requirements are:

Check if the URL is up.  If it is down, send an email.
Cronjob will execute the script again. If Step 1 sent an email, then send an email again asking if the environment is under maintenance.
Cronjob will execute the script again.  If it is still down, don't do anything.
Keep checking the URL, and if it is responding, don't do anything.  But if it goes down again, follow step 1-3.

The script works.  Could you please review and suggest if there is a nicer way of writing the script?  I'm learning shell script but don't know all the available options.

#!/bin/bash
#Checking urls from urls.txt
MAddr="jsing002@internalsvcs.pte.com"
TIME=`date +%d-%m-%Y_%H.%M.%S`
SCRIPT_LOC=/user/inf/ete4/eteabp4/eid_scripts/jsing002
for url in `awk '{print $1}' $SCRIPT_LOC/urls.txt`
do
    /usr/bin/wget -t 0 --spider --no-check-certificate $url > wget.output  2>&1
    HTTPCode=`(/usr/bin/wget -t 0 --spider --no-check-certificate $url) 2>&1 | grep HTTP| tail -1|cut -c 41-43`
        ENV=`(grep $url $SCRIPT_LOC/urls.txt | awk '{print $2}')`
        echo $HTTPCode
        E1=`/bin/grep -ise  'refused' -ise 'failed'  wget.output`
        if [ "$E1" != "" ] || [ $HTTPCode -ge 500 ]
            then
                    status="DOWN"
                    echo "Step 1"
                    echo "${ENV}""_DOWN"

                    if [ -f "${ENV}""_DOWN" ];
                        then
                            echo "step 2"
                            echo "Please check if $ENV in Maintanance window.The check for $url has failed twice.Next The next failure email will be sent if preceding test was SUCCESSFUL" | /bin/mail -s "Is $ENV in Maintanance Window ?" $MAddr
                            mv "${ENV}""_DOWN" "${ENV}""_DOWN""_2"
                            echo "Step 3"
                        elif [ -f "${ENV}""_DOWN""_2" ];
                            then
                                echo "this is elif statement"

                        else
                            echo "E1 is empty. Site is down"
                            echo "Site is down. $url is not accessible" | /bin/mail -s "$ENV is $status" $MAddr
                            touch  "${ENV}""_DOWN"
                        fi

            else
                        if [ $HTTPCode -eq 200 ]
                            then
                                status="UP"
                                echo $status
                                rm "${ENV}""_DOWN""_2"
                        fi
        fi
done

Content of urls.txt:
http://mer01bmrim:30270/rim/web         E2E-RIMLITE4
http://mer01csmap:18001/console         ABP_WL-E2E1
http://mer02sitap:18051/console         ABP_WL-E2E2
http://mer03sitap:18101/console         ABP_WL_E2E3


texts: Filter out non-alphabetic characters from a list of words

texts:
For coding practice / interview exercises, I'd like to know if there's an optimizaton I can make to the following, where I "clean" a given word to remove punctuation or other characters that are not within "a" to "z".

There are some great answers here to remove punctuation from a string, so my question today is not the best way how to do this, but instead whether there is an optimization I can make to my 3 lines of code below in the word_count_engine function? Can I do this in 1 or 2 lines or make the code more efficient so it doesn't loop over the list twice (i.e. with 2 list comprehensions)?

def clean(word):
    returnword = ""
    for letter in word.lower():
        if letter >= 'a' and letter <='z':
            # not out of bounds
            returnword += letter
    return returnword

def word_count_engine(document):

    words = document.split() # if there are     extra    spaces, split() still filters empty words out FYI
    words = [clean(word) for word in words] # a word like "$33!" will result in an empty string though
    words = [word for word in words if word] # so filter out empty strings and get the final list of clean words

document = "Practice makes perfect. you'll only get Perfect by practice. just practice! $544 test"


texts:
I have this recursive function that searches an object tree structure:

dataSearcher = (dataElement, identifierToFind) ->
    if dataElement.identifier == identifierToFind
        return dataElement
    else
        for childDataElement in dataElement.children
            found = dataSearcher childDataElement, identifierToFind
            if found then return found

Which I then call thus:

foundDataElement = dataSearcher @options.nodeData, identifier

It works just fine so I am happy about that, but I am pretty new to CoffeeScript and would like feedback on the way I structured it.  The loop I used seems a bit old school, so could I have used a comprehension here instead?  Any other feedback would be great as I am still getting my head into the CoffeeScript idiom.

Please let me know if I should edit with more context code.


texts: Implementing a cross-browser event utility as an exercise

texts:
I am currently learning JavaScript and created this cross-browser event utility as a learning exercise. It was not meant to be used in production code, and I just tried to cover only the cases that I'm aware of, so there might be a lot of edge cases that are not covered.

I'd be happy if you could check it and let me know how it looks and give me suggestions on how to improve it:

var helpers = {
    getOldEventName: function(eventName) {
        if (eventName.lastIndexOf('on', 0) !== 0) {
            return 'on' + eventName;
        }

        return eventName;
    },
    getModernEventName: function(eventName) {
        if (eventName.lastIndexOf('on', 0) !== -1) {
            return eventName.substring(2);
        }

        return eventName;
    },
    isCollection: function(variable) {
        return variable instanceof Array || variable instanceof HTMLCollection || variable instanceof NodeList;
    }
}

var myEvent = {
    addListener: function(element, eventName, callback) {
        var elements = element;
        if (!helpers.isCollection(element))
            elements = [element];
        for (var i = 0; i < elements.length; i++) {
            if (elements[i].addEventListener) {
                elements[i].addEventListener(helpers.getModernEventName(eventName), callback, false);
            } else if (element.attachEvent) {
                elements[i].attachEvent(helpers.getOldEventName(eventName), callback);
            } else {
                elements[i][helpers.getOldEventName(eventName)] = callback;
            }
        }
    },
    removeListener: function(element, eventName, callback) {
        var elements = element;
        if (!helpers.isCollection(element))
            elements = [element];
        for (var i = 0; i < elements.length; i++) {
            if (elements[i].removeEventListener) {
                elements[i].removeEventListener(helpers.getModernEventName(eventName), callback, false);
            } else if (elements[i].detachEvent) {
                elements[i].detachEvent(helpers.getOldEventName(eventName), callback);
            } else {
                elements[i][helpers.getOldEventName(eventName)] = null;
            }
        }
    },
    getEvent: function(event) {
        return event || window.event;
    },
    getTarget: function(event) {
        return (typeof event.target !== 'undefined') ? event.target : event.srcElement;
    },
    stopPropagation: function(event) {
        if (event.stopPropagation) {
            event.stopPropagation();
        } else if (typeof event.cancelBubble !== 'undefined') {
            event.cancelBubble = true;
        }
    },
    preventDefault: function(event) {
        if (event.preventDefault) {
            event.preventDefault();
        } else if (typeof event.returnValue !== 'undefined') {
            event.returnValue = false;
        }
    }
}

Usage examples:

function myCallback(e) {
    e = myEvent.getEvent(e);
    alert(myEvent.getTarget(e).href);
    myEvent.stopPropagation(e);
    myEvent.preventDefault(e);
}
myEvent.addListener(document.links, 'click', myCallback);

function dynamicDivHandler(e) {
    e = myEvent.getEvent(e);
    var keyCode = e.keyCode;
    var node = document.getElementById('dynamicDiv');

    switch (keyCode) {
        case 37:
            node.style.left = (parseInt(node.style.left) - 5) + 'px';
            break;
        case 38:
            node.style.top = (parseInt(node.style.top) - 5) + 'px';
            break;
        case 39:
            node.style.left = (parseInt(node.style.left) + 5) + 'px';
            break;
        case 40:
            node.style.top = (parseInt(node.style.top) + 5) + 'px';
            break;
    }
}
myEvent.addListener(document, 'keydown', dynamicDivHandler);

P.S.: This exercise is from the book "Object-Oriented JavaScript" by Stoyan Stefanov.


texts:
I am using class "active" to keep track on which child to fade in and fade out in my gallery. Are there any other, better options for doing this?

<!DOCTYPE html>

<meta charset="utf-8" />
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

1

2

3

4


texts: Ruby metaprogramming - declaring "properties" on a class

texts:
I'm new to Ruby and trying to do a bit of metaprogramming. I want to declare some "properties" on a class, describing some field names and their access privileges:

class Resource
  # my_property(name, privilege => level)
  my_property :id, :read => :admin # :write => :none
  my_property :name, :read => :all, :write => :owner
  my_property :pin, :read => :owner, :write => :owner

  # ...
end

Where privileges are various symbols and levels are [:all, :owner, :admin], and higher level implies all lower levels.

Later, I want to retreive the information in this way:

res.readable_properties(:admin) # => [:id, :name, :pin]
res.writeable_properties(:admin) # => [:name, :pin]
res.writeable_properties(:all) # => []

Where method names are based on privilege names plus "able_properties" suffix.

Obviously, those declarations are on class level, so everything should be done only once when class is declared, and not on every instance creation.

I've tried to implement, but while it works fine, I suspect that my code is ugly and kludgy. Could someone please give me a hints on how to improve it? Here's what I came with:

require 'set'

class ResourceBase
  class << self
    def my_property(name, access)
      access_levels = %w[all owner admin].map {|s| s.to_sym}
      puts "#{name}: #{access}"

      @permissions ||= {}
      permit = {}
      access_levels.each do |level|
        access.each do |permission, min_level|
          @permissions[permission] ||= {}
          @permissions[permission][level] ||= []
          permit[permission] = true if level == min_level
          @permissions[permission][level].push(name) if permit[permission]
        end
      end

      @perm_methods ||= Set.new()
      @permissions.keys.each do |permission|
        next if @perm_methods.include? permission
        @perm_methods.add permission
        define_method "#{permission}able_properties".to_sym, do |level|
          self.class.permissions[permission][level]
        end
      end
    end

    def permissions
      @permissions
    end
  end
end

class Resource < ResourceBase
  # Levels range: all < owner < admin
  # Higher levels imply lower ones (i.e. admin always have owner access)
  my_property :id, :read => :admin #, :write => :none
  my_property :name, :read => :all, :write => :owner
  my_property :pin, :read => :owner, :write => :owner
end

resource = Resource.new
puts "Readable: " + resource.readable_properties(:admin).to_s
puts "Writeable: " + resource.writeable_properties(:admin).to_s

I seek for any suggestions which could be phrased as "Rather than [how OP did it] it's better to [how it should be done]."


texts: Remove row when everything in the row is same

texts:
I have a code that will delete the row if the entire row is exactly the same. So if in row 1 I have 100,200,300,400,500,600 in column A,B,C,D,E,F respectively, and in row 3 I have the same thing, it will remove row 3.

Sub remove()
    Dim a As Long
    For a = Cells(Rows.Count, 1).End(xlUp).row To 1 Step -1
        If WorksheetFunction.CountIf(Range("A1:A" & a), Cells(a, 1)) > 1 Then
            If WorksheetFunction.CountIf(Range("B1:B" & a), Cells(a, 2)) > 1 Then
                If WorksheetFunction.CountIf(Range("C1:C" & a), Cells(a, 3)) > 1 Then
                    If WorksheetFunction.CountIf(Range("D1:D" & a), Cells(a, 4)) > 1 Then
                        If WorksheetFunction.CountIf(Range("E1:E" & a), Cells(a, 5)) > 1 Then
                            If WorksheetFunction.CountIf(Range("F1:F" & a), Cells(a, 6)) > 1 Then Rows(a).Delete
                        End If
                    End If
                End If
            End If
        End If
    Next
End Sub

However this code looks a little long and I was wondering if I could use a for loop but I have no idea on how to start. I am new to VBA coding which is why my methods could be a little hard coded. Any help is appreciated, Thank you!

(Edit) Here is a sample workbook that I have created.
In this workbook I have a few names on the first column and the next few columns are the points they obtain on different days. However, there are entries that have the exact same entry row, meaning, the points and the name is exactly the same and this is what I want to remove. in the sample workbook, the name james have the 2 exact same entries and therefore, it will remove 1 of it. However Lan and Denise does not have the same entries hence it remains after running the code.


texts: Python monkeypatch an API and search through iterable object tree

texts:
General information

I am using an acceptance testing framework (robot framework) and it has an API which allows you to 'visit' suites and tests before execution.

Specific goal

The framework does not save the original suites name (a.k.a. tests.my_test). If you wanted to run that test twice with different names it will throw out the tests component and become new_name.my_test. I wanted to be able to preserve that information so that while viewing it can have descriptive names, but while searching the suite trees I could still find the original test names and rerun.

Questions to people unfamiliar with the framework

I wanted to piggyback off of their work to stay as compatible with the framework as possible. The selection of rerunned tests is here. It includes a function gather_failed_tests which uses class GatherFailedTests. Since, that native feature of rerunfailed and my feature of rerunrenamedtests can't coexist I chose to simply monkeypatch the GatherFailedTests class to inherit from my class, which fixes the names before it would gather the tests.

Is that a dangerous idea anyway? Should I copy all the source for the function gather_failed_tests and rename them in their entirety? It's a maintainability vs stability problem. I either can monkey patch a minimal component and hope I get any fixes added to the function or surrounding framework or I can have to manually update the whole chain.

I feel like there is a more efficient way to go through the iterable suites. suite_obj.suites returns an iterable of suites. However the initial top level suite itself also needs to be searched. Is there a way to collapse config_suites and config_all_suites simply?

It is ultimately a tree of suites and I need to handle the first element in each branch that has the originallongname in metadata.

Questions for anyone who knows robot

I'm unhappy with wiping out the parent when I am configuring a non-root suite test.parent.parent = None. I'm uncertain if why that method doesn't just configure the parent's criticality instead of failing, but regardless of how it functions is there a better way to alter the longname property without destroying info?

from robot.api import SuiteVisitor
from robot.conf import gatherfailed

class rename(SuiteVisitor):
    """Store the original longname so that rerunning can happen even with virtually reorganized tests."""

    def __init__(self, new_name):
        self.new_name = new_name

    def start_suite(self, suite):
        originallongname = suite.longname
        suite.metadata.setdefault('originallongname', originallongname)
        suite.configure(name=self.new_name)

class resetname(SuiteVisitor):
    def config_test(self, suite):
        originallongname = suite.metadata['originallongname']
        try:
            suite.configure(name=originallongname)
        # Critically setting from non-root error
        except TypeError:
            for test in suite.tests:
                test.parent.name = originallongname
                test.parent.parent = None

    def config_all_suites(self, suite):
        for suite in suite.suites:
            try:
                self.config_test(suite)
            except KeyError:
                self.config_suites(suite)

    def config_suites(self, suite):
        try:
            self.config_test(suite)
        except KeyError:
            self.config_all_suites(suite)

    def start_suite(self, suite):
        self.config_suites(suite)

class RenameThenGatherFailedTests(resetname):

    def __init__(self):
        self.tests = []

    def visit_test(self, test):
        if not test.passed:
            self.tests.append(test.longname)

    def visit_keyword(self, kw):
        pass

gatherfailed.GatherFailedTests = RenameThenGatherFailedTests

class rerunrenamedtests(SuiteVisitor):
    def __init__(self, output):
        self.output = output

    def start_suite(self, suite):
        tests = gatherfailed.gather_failed_tests(self.output)
        suite.filter(included_tests=tests)

If it would help to see how this would be used you could see here.


texts:
I want to create a state machine for menu in my SDL game. So this is my code without the SDL. I just want to ask if this is a good way to create it. I am trying to implement a screen and then mouse events, but I have a problem there so this is a reason why I ask if this is okay. Here is a code:
#include <stdio.h>
#include <windows.h>
enum states
{
Menu,
Game,
Game_over,
Exit
};

int main()
{
int game_is_running = 1;
enum states state = Menu;
while(game_is_running == 1)
{
  switch(state)
{
 case Menu:
state = Game;
printf("menu screen with play and exit button.\n"); //need to add if
                                            //exit or play is pressed
                 // if exit then exit program if play than you know...
 break;
case Game:
 state = Game_over;
printf("after play button is pressed game screen will show up.\n"); //after this i will come back to menu.
break;
case Game_over:
state = Exit;
printf("screen after game.\n");
break;
case Exit:
printf("turn game off.\n"); //this will be in the if function with a game.
game_is_running = 0;
break;
}
Sleep(1000); // sleep for a second just for test
}
 return 0;
}


texts: Find substring count without string functions

texts:
Find the substring count from a string without string functions in Java. Given String str = "abcdefghcde"; and String find = "cde";, count occurrences of "cde" in String str.

Taking into account overlaps.

Example: String str = "cdcdcdc"; and String find = "cdc";, occurrence count is 3

Please give any feedback about improving it or any issues (performance or otherwise) that you see.

String input = "cdcdcdcdcdcddc";
    String find = "cdc";
    StringBuffer found = new StringBuffer();
    int count = 0;
    int j=0;
    for ( int i = 0; i <input.length();){
            j = 0;
            while(j<find.length() && i<input.length() && input.charAt(i) == find.charAt(j)) {
                found.append(input.charAt(i));
                j++;
                i++;
            }
            i=i-j;
            if(found.toString().equals(find)) {
                count++;
            }
            i++;
            found.setLength(0);
        }
    System.out.println("count is " + count);
    }

I have another question here which doesn't take into account overlaps and it's complexity is \$O(n)\$. But for this question, I'm unable to achieve \$O(n)\$ time running time.

Update: For all the people down voting, this is not a duplicate but a variant of the other question. If posting variants of a question is against the rules of stackexchange, please let me know and I'll delete my other post. Otherwise, I'd like to keep the other post because my solutions are slightly different in approach and much different in complexity and I'd like a feedback on both of them. Posting them as part of one post would be messy, both for me, and for the people trying to give feedback.


texts: Regular Expression matching customer number strings


texts: Mobile app backend using Gin and Gorm ORM

texts:
I'm developing backend for my mobile app by using gin-gonic and gorm ORM (mysql). But I'm not sure api and db handle huge amount requests if clients increased. for example I'm using my db struct as parameter, is this a problem for concurrency ?

Here is my implementation:

main.go:

var i Impl

func main() {

    // #GIN# //
    r := gin.New()
    r.Use(gin.Logger())
    r.Use(gin.Recovery())
    // #GIN# //

    // #DB# //
    i.InitDB()
    // #DB# //

    // #TWITTER# //
    t := Twitter{}
    t.InitTwitter()
    // #TWITTER# //

    r.GET("/someEndpoint", func(c *gin.Context) {
    i.InsertUser(&user)
    go t.Ping(&i)
    c.JSON(200, gin.H{"status": true})
    })

    r.Run(":5000")
}

twitter.go:

// InitAPI TO-DO
func (t *Twitter) InitAPI(token string, tokenSecret string) {
    t.API = anaconda.NewTwitterApi(token, tokenSecret)
    t.UserID = strings.Split(token, "-")[0]
}

// Ping TO-DO
func (t *Twitter) Ping(i *Impl) {
    t.GetHomeTimeLine(i)
    t.GetUsersFriends(i)
}

// GetHomeTimeLine TO-DO
func (t *Twitter) GetHomeTimeLine(i *Impl) {
    v := url.Values{}
    v.Set("count", "200")
    v.Set("exclude_replies", "true")
    results, err := t.API.GetHomeTimeline(v)

    if err != nil {
        log.Println(err.Error())
        return
    }

    tweets := convertTweets(results, t.UserID)
    go i.CreateOrUpdateTimeline(tweets)
}

// GetUsersFriends TO-DO
func (t *Twitter) GetUsersFriends(i *Impl) {
    v := url.Values{}
    v.Set("count", "200")
    v.Set("skip_status", "true")
    friendsChannel := t.API.GetFriendsListAll(v)

    for {
        _friends, more := <-friendsChannel
        if _friends.Error != nil {
            log.Println(_friends.Error.Error())
            break
        }

        friends := convertFriends(_friends.Friends, t.UserID)
        go i.CreateOrUpdateFriends(friends)
        if !more {
            break
        }
    }
}

db.go:

// Impl TO-DO
type Impl struct {
    DB gorm.DB
}

// InitDB TO-DO
func (i *Impl) InitDB() {
    var err error
    i.DB, err = gorm.Open("mysql", "connection string")
    if err != nil {
        log.Fatalf("Got error when connect database, the error is '%v'", err)
    }
    i.DB.LogMode(false)
    i.DB.DB().SetMaxIdleConns(10)
    i.DB.DB().SetMaxOpenConns(100)
}

// InsertUser TO-DO
func (i *Impl) InsertUser(user *User) bool {
    if err := i.DB.Create(&user).Error; err != nil {
        log.Fatalf("InsertError: %s", err.Error())
        return false
    }
    return true
}


texts: PHP function to check whether a user is logged in

texts:
So, I have a function which checks if a user is logged in, but it's a long chain of if/else statements.

public static function isLoggedIn(){
    Session::openSession();

    if(isset($_SESSION['userId'])){
        return true;
    }

    if(isset($_COOKIE['authToken'])){
        list($selector, $token) = explode(':', $_COOKIE['authToken']);
        $result = Database::query('SELECT * FROM logins WHERE login_selector = ?', array($selector))[0];

        if($result){
            if(!hash_equals($result['login_token'], hash('sha256', base64_decode($token)))){
                return self::notLogged();
            }else{
                self::relogUser($result['login_userId']);
                return true;
            }
        }else{
            return self::notLogged();
        }
    }else{
        return self::notLogged();
    }
}

I'm looking for advice on how to refactor it to make it more clean and easy to read.

EDIT: I tried using a series of returns but it didn't work because one failed and blocked the rest (obviously).


texts: Array that defines product information and generates the html for the product

texts:
Is there a more productive way to do this? Is my code up to standards or up to best practices?

   <?php

    /*
      FILE:       index.php
      AUTHOR:     Darcey Mckelvey
      PURPOSE:    View Products
    */

    // Define product information
    $products[0] = array(
      'name' => 'Sneakers',
      'price' => 24.99,
      'category' => 'Shoes',
      'description' => 'Black sneakers. Good for walking or athletic activity'
    );

    $products[1] = array(
      'name' => 'Armani Red Silk Shirt',
      'price' => 379.99,
      'category' => 'Shirts',
      'description' => 'Fancy Italian red silk shirt. Very spiffy, sure to attract the ladies'
    );

    echo "
Welcome to DropShop!

Our Products
";

    // Loop to display all products
    foreach($products as $product) {
      echo "
" . $product['name'] . "
" .
      "Price: $" . $product['price'] . "
" .
      "Category: " . $product['category'] . "
" .
      $product['description'] . "
";
    }

    ?>


texts:
I was working on a class assignment today and I wrote this code which works perfectly fine. It looks tho kind of has too much 'if statements' in it, and I was thinking that it could be written much better than this. (I'm still a beginner in C).

Do you suggest any new techniques that I could use/learn to avoid so many if statements and how could you improve this code without making it much longer or complex?

The code is a part of much bigger code to add a new node in an AVL tree.

if (avlt->root == NULL) {
    new = &(avlt->root);
    parent = NULL;
}
if (avlt->root != NULL) {
    parent = avlt->root;
    while (1)
    {
        if (parent->value > value)
        {
            if (parent->left) parent = parent->left;
            else
            {
                new = &(parent->left);
                break;
            }
        }
        else if (parent->value < value)
        {
            if (parent->right) parent = parent->right;
            else
            {
                new = &(parent->right);
                break;
            }
        }
        else return;
    }
}

These are the structs, maybe they can be useful for you to understand the code:

struct AVLNode {
  struct AVLNode* left;
  struct AVLNode* right;
  struct AVLNode* parent;
  int value;
  int height;
};

struct AVLTree {
  struct AVLNode* root;
  int numberOfNodes;
};

typedef struct AVLNode AVLNode;
typedef struct AVLTree AVLTree;


texts: Custom sorting a list of objects efficiently

texts:
I'm trying to make sorting of objects in my program as fast as possible. I know that sorting with a cmp function is deprecated in python 3.x and that using keys is faster, but I'm not sure how to get the same functionality without using a cmp function.

Here's the definition of the class:

class Topic:
    def __init__(self, x, y, val):
        self.id = val
        self.x = x
        self.y = y

I have a dictionary full of Topic to float key, value pairs and a list of Topics to be sorted. Each topic in the list of Topics to be sorted has an entry in this dictionary. I need to sort the list of topics by the value in the dictionary. If two topics have a difference in value <= .001, the topic with higher ID should come first.

Here's the current code I'm using:

topicToDistance = {}
# ...
# topicToDistance populated
# ...
topics = topicToDistance.keys()
def firstGreaterCmp(a, b):
  if abs(topicToDistance[a]-topicToDistance[b]) <= .001:
    if a.id < b.id:
      return 1
  if topicToDistance[a] > topicToDistance[b]:
      return 1
  return -1
# sorting by key may be faster than using a cmp function
topics.sort(cmp = firstGreaterCmp)

Any help making this a bit more efficient would be greatly appreciated.


texts: Map square coordinates in matrix to flat array indices without hurting performance

texts:
I'm more like playing and the problem I'm going to demonstrate is a learning task, so to speak, not something I really need to solve.

Imagine having a matrix of data. You chose square in it and would like to access each point on square perimeter by 1D index, like this:

This image represents instance of some Matrix class, such as:

Matrix m = ...;
std::cout<<m.data[0][1]; // "foo", first row, second column

Now I would like to create wrapping class Subsquare which, if represents the yellow square on the image works like this:

// Params: x, y, size, parent matrix
Subsquare sqr(1, 1, 6, m); // create from matrix

std::cout<<sqr[4]; //"4", as per image

I did try to make the class, but I got lost when trying to invent the algorithm to perform the mapping. I'd also like the algorithm to be optimal.

This is my attempt:

/**
 * @brief The Subsquare class allows you to iterate over square section of matrix
 */
class Subsquare {
public:
    /**
     * @brief Subsquare
     * @param x coordinate, 0-indexed
     * @param y coordinate, 0-indexed
     * @param length size of the square, it will span length items with it's side
     * @param parent matrix that contains the data
     */
    Subsquare(const int x, const int y, const int length, const Matrix& parent)
        : x(x)
        , y(y)
        , length(length)
        // the trick is that we only can count square corners once
        , items(length*4-4)
        , m(parent)
    {}
    /**
     * @brief The Side enum is helper enum for determining from which side are we picking index
     *
     */
    enum Side:byte {
        TOP,
        RIGHT,
        BOTTOM,
        LEFT
    };
    /**
     * @brief operator [] provides access to nth item in square, starting
     *                    at top left corner and going clockwise
     * @param index the index, 0-indexed
     * @return
     */
    int operator[] (int index) const {
        const byte side = index/(length-1);
        const int position = index%(length-1);
        //std::cerr<<"Pos: "<<index<<" side: "<<(int)side<<" subpos: "<<position<<'\n';
        switch (side) {
        case TOP:
            return m.data[y][x+position];
            break;
        case RIGHT:
            return m.data[y+position][x+length-1];
            break;
        case BOTTOM:
            return m.data[y+length-1][x+length-1-position];
            break;
        case LEFT:
            return m.data[y+length-1-position][x];
            break;
        }
    }
    /**
     * @brief Allows iterating over the square using for(int val: square) {}
     */
    class iterator {
    public:
        iterator(const int pos, const Subsquare& sq) :
            pos(pos), parent(sq)
        {}
        int pos;
        const Subsquare& parent;
        int operator*() {
            return parent[pos];
        }
        bool operator!=(const iterator& other) {
            return other.pos!=pos;
        }
        void operator++() {
            ++pos;
        }
    };
    /// Iterator helper methods
    iterator begin() const {
        return iterator(0, *this);
    }
    iterator end() const {
        return iterator(items, *this);
    }

    const Matrix& m;
    const int x;
    const int y;
    const int length;
    const int items;
};

Now this works correctly, it seems:

1 2 3
4 5 6
7 8 9
1, 2, 3, 6, 9, 8, 7, 4,

However I'm quite concerned about performance. Is there a way to make the algorithm faster while keeping it comfortable to use? The task I'm working on involves searching squares in very big matrix and the algorithm must be fast.


texts: Request dispatcher for PHP JSON web service

texts:
Below you can find the constructor method and related fields of the main class of my REST API (note that the class contains more code than displayed) written in PHP 7.1. It does various things with the HTTP-request. It starts with getting the arguments and then it gets the method in which the request is made (like POST or GET). The request gets trimmed of tags and that gets saved back into the instance/member variable $this->request.

Now, to my best knowledge, $this->request in PHP always points to the HTTP-request when a HTTP-request has just been made. The code can only get here when a HTTP-request has been made and $this->method has been filled ($this->method = $_SERVER['REQUEST_METHOD'];).

In other words, $this->method should always exist, but I keep getting the 'Field declared dynamically' warning:

Is it okay to just ignore the warning or is there a best practice to deal with it?

Other tips to improve my code are welcome too. I've 'learned' PHP  back in version 4 (I used it for uni once). I struggle with the OO concepts since introduced in a language where so much is allowed.

class BaseAPI {

    protected $method = '';
    protected $endpoint = '';
    protected $verb = '';
    protected $args = Array();

    public function __construct($request)
    {
        header("Access-Control-Allow-Orgin: *");
        header("Access-Control-Allow-Methods: *");
        header("Content-Type: application/json");

        $this->args = explode('/', rtrim($request, '/'));
        $this->endpoint = array_shift($this->args);
        if (array_key_exists(0, $this->args) && !is_numeric($this->args[0])) {
            $this->verb = array_shift($this->args);
        }

        $this->method = $_SERVER['REQUEST_METHOD'];
        if ($this->method == 'POST' && array_key_exists('HTTP_X_HTTP_METHOD', $_SERVER)) {
            if ($_SERVER['HTTP_X_HTTP_METHOD'] == 'DELETE') {
                $this->method = 'DELETE';
            } else if ($_SERVER['HTTP_X_HTTP_METHOD'] == 'PUT') {
                $this->method = 'PUT';
            } else {
                throw new IncorrectHeaderException("Unexpected Header");
            }
        }

        switch ($this->method) {
            case 'DELETE':
            case 'PUT':
                // don't do anything yet
            case 'POST':
                $this->request = $this->_cleanInput($_POST);
                break;
            case 'GET':
                $this->request = $this->_cleanInput($_GET);
                break;
            default:
                throw new IncorrectMethodException('Invalid Method');
                break;
        }
    }

    private function _cleanInput($data)
    {
        $cleaned_input = Array();
        if (is_array($data)) {
            foreach ($data as $k => $v) {
                $cleaned_input[$k] = $this->_cleanInput($v);
            }
        } else {
            $cleaned_input = trim(strip_tags($data));
        }
        return $cleaned_input;
    }
}


texts: Possible letter combinations of a dial pad in linear time using a recursive approach

texts:
Time complexity: I walk the initial unzipped array of keys representing the number O(N) backwards. I then do an inner walk of the proceeding array of letters *O(L^2), mapping it to every value in the target O(T)). finally, I  flattening the values and repeat to get O(N^3)

I know this can not be solved in linear time, but can the runtime be improved (maybe recursively) and is my time analysis correct?

let letters_keys = {
  2: ['a', 'b', 'c'],
  3: ['d', 'e', 'f'],
  4: ['g', 'h', 'i'],
  5: ['j', 'k', 'l'],
  6: ['m', 'n', 'o'],
  7: ['p', 'q', 'r', 's'],
  8: ['t', 'u', 'v'],
  9: ['w', 'x', 'y', 'z']
}

function all_possable(num) {
  return num.toString().split('').map(x => new Set(letters_keys[x]))
}

function remp(possable) {
  possable = all_possable(possable)
  possable = possable.map(x => [...x])

  let v = possable.reduceRight((x, a) => {

    if (x.length === 0) {
      x = a
    } else {

     let k = x.map(c => a.map(b => b + c))
      x = k.reduce((acc, a) => acc.concat(a), [])
    }
    return x
  }, [])
  return v.sort()

}

console.log(remp(5678).sort())


texts:
I currently I have this code
if (this.showAllOnlineFriends === false) {
  this.showAllOnlineFriends = true;
} else {
  this.showAllOnlineFriends = false;
}

When you press a button, it will toggle a boolean on or off. Is there a more readable way to write this?


texts:
I have two data frames/ lists of data, humanSplit and ratSplit, and they are of the form

> ratSplit$Kidney_F_GSM1328570
  ratGene        ratReplicate alignment RNAtype
1    Crot Kidney_F_GSM1328570         7     REV
2    Crot Kidney_F_GSM1328570        12     REV
3    Crot Kidney_F_GSM1328570         4     REV

and

> humanSplit$Fetal_Brain_408_AGTCAA_L009_R1_report.txt
   humanGene                            humanReplicate alignment RNAtype
53     ZFP28 Fetal_Brain_408_AGTCAA_L009_R1_report.txt         5     reg
55     RC3H1 Fetal_Brain_408_AGTCAA_L009_R1_report.txt         9     reg
56     IFI27 Fetal_Brain_408_AGTCAA_L009_R1_report.txt         4     reg

And another file used below is geneList of the form:

ABAT,Abat
ABCA1,Abca1
ABCA12,Abca12
ABCA2,Abca2
ABCA3,Abca17
ABCA4,Abca4
ABCA5,Abca5

now I want to do Fisher's exact test between all the elements pair combination between ratSplit and humanSplit after some data manipulation. And ultimately want to write the result of fisher's test in a .csv file. Right now I am doing double for loops. But I am wondering how I can use sapply or other related things to make it more efficient.

I am currently doing the following thing:

Here I am first making a data.frame result where I store/append all the information got from fisher's test in a pair in each step. Then finally when the whole loop is done, I write the final result in a .csv file. my understanding is to use sapply I need to transform the inside of the loop into a function and then call sapply. But I am not sure what's the best way to optimize it.

result <- data.frame(humanReplicate = "human_replicate", ratReplicate = "rat_replicate", pvalue = "p-value", alternative = "alternative_hypothesis",
                     Conf.int1 = "conf.int1", Conf.int2 ="conf.int2", oddratio = "Odd_Ratio")
for(i in 1:length(ratSplit)) {
  for(j in 1:length(humanSplit)) {
    ratReplicateName <- names(ratSplit[i])
    humanReplicateName <- names(humanSplit[j])

    #merging above two based on the one-to-one gene mapping as in geneList defined above.
    mergedHumanData <-merge(geneList,humanSplit[[j]], by.x = "human", by.y = "humanGene")
    mergedRatData <- merge(geneList, ratSplit[[i]], by.x = "rat", by.y = "ratGene")

    mergedHumanData <- mergedHumanData[,c(1,2,4,5)] #rearrange column
    mergedRatData <- mergedRatData[,c(2,1,4,5)]  #rearrange column
    mergedHumanRatData <- rbind(mergedHumanData,mergedRatData) #now the columns are "human", "rat", "alignment", "RNAtype"

    agg <- aggregate(RNAtype ~ human+rat, data= mergedHumanRatData, FUN=getGeneType) #agg to make HmYn form
    HmRnTable <- table(agg$RNAtype) #table of HmRn ie RNAtype in human and rat.

    #now assign these numbers to variables HmYn. Consider cases when some form of HmRy is not present in the table. That's why
    #is.integer0 function is used
    HyRy <- ifelse(is.integer0(HmRnTable[names(HmRnTable) == "HyRy"]), 0, HmRnTable[names(HmRnTable) == "HyRy"][[1]])
    HnRn <- ifelse(is.integer0(HmRnTable[names(HmRnTable) == "HnRn"]), 0, HmRnTable[names(HmRnTable) == "HnRn"][[1]])
    HyRn <- ifelse(is.integer0(HmRnTable[names(HmRnTable) == "HyRn"]), 0, HmRnTable[names(HmRnTable) == "HyRn"][[1]])
    HnRy <- ifelse(is.integer0(HmRnTable[names(HmRnTable) == "HnRy"]), 0, HmRnTable[names(HmRnTable) == "HnRy"][[1]])

    contingencyTable <- matrix(c(HnRn,HnRy,HyRn,HyRy), nrow = 2)

    fisherTest <- fisher.test(contingencyTable)
    newLine <- data.frame(t(c(humanReplicate = humanReplicateName, ratReplicate = ratReplicateName, pvalue = fisherTest$p,
                              alternative = fisherTest$alternative, Conf.int1 = fisherTest$conf.int[1], Conf.int2 =fisherTest$conf.int[2],
                              oddratio = fisherTest$estimate[[1]])))

    result <-rbind(result,newLine)
  }
}

write.table(result, file = "newData5.csv", row.names = FALSE, append = FALSE, col.names = TRUE, sep = ",")


texts:
I needed smth that could send (scp/rsync) many files in parallel but that would not overload machine, firewalls on the way by starting e.g. 600 simultaneous uploads, so upload should be done in batches.

Most of the utilities like aria2c are download managers and I needed something to send many files in parallel from a machine behind NAT to a machine on the internet (so no dl from internet possible).

Pls keep in mind that it's the draft that I quote below, I do not need details on general good practices such as setting paths and counters using variables and not literal values.

Any better approach? Problems? I've noticed that I have to sleep 1 between starting scp cmds in background or else target server refuses some connections.

#!/bin/bash

FLIST=file_paths_list.txt

COUNTER=0
PIDS=()

cat ${FLIST} | while read F; do
                COUNTER=$((COUNTER + 1))
                echo COUNTER $COUNTER
                sleep 1
                scp ${F} root@host:/data/tmp &
                PID=$!
                echo Adding PID $PID
                PIDS+=($PID)
                if [ $COUNTER -lt 20 ]; then
                        continue
                fi
                # wait for uploads batch to complete
                for PID in ${PIDS[@]}; do
                        echo waiting for PID $PID
                        wait $PID
                done
                # reset PIDS array
                PIDS=()
                COUNTER=0
done


texts: Name comparison using fuzzy string matching

texts:
I'm somewhat new to python and wrote this piece of code to do a string comparison of accounts that are being requested for import into our data base against accounts that are already present. The issue is that the accounts currently in our DB is over 65K and I'm comparing over 5K accounts for import causing this code to take over 5 hours to run. I suspect this has to do with the loop I'm using but I'm not certain how to improve it.

TLDR; I need help optimizing this code so it has a shorter run time.

from fuzzywuzzy import fuzz
from fuzzywuzzy import process

accounts_DB = pd.read_csv("file.csv") #65,000 rows and 15 columns
accounts_SF = pd.read_csv("Requested Import.csv") #5,000 rows and 30 columns

def NameComparison(DB_account, choices):
    """Function uses fuzzywuzzy module to perform Levenshtein distance string comparison"""
    return(process.extractBests(DB_account, choices, score_cutoff= 95))

options = accounts_sf["Account Name"]
a_list = []
for i in range(len(accounts_db)):
    a_list.append(NameComparison(accounts_db.at[i,"Company Name"], options))
b_list = pd.DataFrame(a_list)
b_list.to_csv("Matched Accounts.csv")


texts: Count unique characters in a String and group the counts

texts:
The code counts the amount of unique characters that fit in the character set ACGT (stemming from nucleobases).

We take a string as input that must contain only either 'A', 'C', 'G', or 'T'.

For instance, "AACCC" should return the Map that looks like this:
Map('A' -> 2, 'C' -> 3, 'G' -> 0, 'T' -> 0).
More detail can be found in a gist with specs.

class DNA(code: String) {
  val nucleotides = Map('A' -> 0, 'T' -> 0, 'C' -> 0, 'G' -> 0)

  code foreach valid_nucleotide

  def nucleotideCounts(): Map[Char, Int] = {
    nucleotides ++ code.filter(nucleotides.contains(_)).groupBy(identity).mapValues(_.length)
  }

  def count(nucleotide: Char): Int = {
    valid_nucleotide(nucleotide)
    nucleotideCounts()(nucleotide)
  }

  private def valid_nucleotide(char: Char) = {
    if (!nucleotides.contains(char)) {
      throw new IllegalArgumentException("DNA is wrong");
    }
  }

}


texts: Calculation of the distance to the next space station

texts:
I've made a solution for this problem:

  Task:

  Write a program for calculation of the distance to the next space station.

  Algorithm:

  First base is located at the distance equal to
  SMK from the beginning of the path (Sirius in our case). The next
  station is located at the distance of F(SMK) from the first. Third
  station — at the distance of F(F(SMK)) and so on. Here \$F\$ — is the Top
  Secret Mars Function (TSMF).  Its value is the sum of the cubes of
  digits its argument in decimal notation (for example \$F(12) = 1^3 + 2^3
> = 9\$). So if the distance from the (\$I − 1\$)-th to \$I\$-th stations is \$X\$, then the distance between \$I\$-th and (\$I + 1\$)-th stations is \$F(X)\$. Your
  cruiser is located between (\$N − 1\$)-th and \$N\$-th space stations at the
  distance of \$L\$ from (\$N − 1\$)-th station. Taking \$N\$, \$K\$ (Secret Mars Key)
  and \$L\$ as input your program should output the distance \$M\$ between your
  cruiser and \$N\$-th station. Oh, by the way! The value of SMK is always
  divisible by 3.

  Input:

  Number \$T\$ (\$2 ≤ T ≤ 33333\$) is placed in the first line of input — it is the number of tests for your program. It followed by the next \$T\$ lines.

  Each of these \$T\$ lines contains 3 integer numbers:

  \$N\$ (\$2 ≤ N ≤ 33333\$), \$K\$ (\$3 ≤ K ≤ 33333\$) and \$L\$ (\$L ≥ 1\$)

  Output:

  \$T\$ lines. \$I\$-th line contains the calculated value of \$M\$ for \$I\$-th test case.

  It has to run in less than one second and take up less than 16 megabytes of memory.

  Sample:

  http://img33.imageshack.us/img33/502/81219587.jpg

Here is the compiled code:

static void Main()
{
    int T = Convert.ToInt32(Console.ReadLine());
    for (int k = 0; k < T; k++)
    {
        string[] split = (Console.ReadLine()).Split(new Char[] { ' ' });
        int N = Convert.ToInt32(split[0]);
        double K = 0;
        string Kst = split[1];
        double POST = 0;

        for (int i = 0; i < N - 1; i++)
        {
            for (int j = 0; j <= Kst.Length - 1; j++)
            {
                int Kindex = int.Parse(Convert.ToString(Kst[j]));
                K = K + Kindex*Kindex*Kindex;
            }
           POST = K;
            Kst = Convert.ToString(K);
            K = 0;
        }
        Console.WriteLine(POST - Convert.ToDouble(split[2]));
    }
}

But this code doesn't go through the time limit of 1.0 second.  How can I improve the speed of this solution?


texts: Regularity in the "Rusty Towel of Mutual understanding"

texts:
I have the following Java class:

import java.util.Random;

public class RandomNameGenerator {

    private Random rand;

    private static String[] prefixes = { "Ultimate", "Bloody", "Crooked",
            "Hallowed", "Magnificent", "Heavy", "Jagged", "Grand", "Shiny",
            "Rusty" };

    private static String[] items = { "Chainsaw", "Towel", "Ping-Pong Ball",
            "Longsword", "Scissors", "Dagger", "Blade", "Bow", "Axe", "Dagger",
            "Spoon", "Fork", "Coat", "Chain Mail", "Plate Mail", "Cloak",
            "Cape", "Mirror", "Cauldron", "Pouch", "Boots", "Shoes", "Greaves",
            "Pants", "Robes", "Locket", "Ring", "Amulet", "Potion", "Fish",
            "Teapot", "Hood", "Crown", "Cap", "Helmet" };

    private static String[] addons = { "Glorious", "Bloody", "Prolonged",
            "Bitter", "Wicked", "Furious" };

    private static String[] postfixes1 = { "Destruction", "Feminism",
            "Twilight", "Massacre", "Dread", "Terror", "Mutual Understanding",
            "Spite", "Immobility", "Mediocrity", "Anger" };

    private static String[] postfixes2 = { "the Occult", "the Captain",
            "the Warrior", "the Hunter", "the Haunted", "the Dead",
            "the Fallen", "the Hitchhiker", "the Wicked King", "the Grue" };

    public RandomNameGenerator() {
        rand = new Random(System.currentTimeMillis());
    }

    public String getRandomName() {
        StringBuilder str = new StringBuilder();
        if (rand.nextInt(100) < 10) {
            str.append("+");
            str.append(Integer.toString(rand.nextInt(10) + 1));
            str.append(" ");
        }
        if (rand.nextInt(100) < 50) {
            str.append(prefixes[rand.nextInt(prefixes.length)]);
            str.append(" ");
        }
        str.append(items[rand.nextInt(items.length)]);
        str.append(" of ");
        if (rand.nextInt(postfixes1.length + postfixes2.length) > postfixes2.length) {
            if (rand.nextInt(100) < 70) {
                str.append(addons[rand.nextInt(addons.length)]);
                str.append(" ");
            }
            str.append(postfixes1[rand.nextInt(postfixes1.length)]);
        } else {
            str.append(postfixes2[rand.nextInt(postfixes2.length)]);
        }
        return str.toString();
    }
}

I use it in a small program to generate sample item names like

  Shiny Dagger of the Haunted
  Shoes of Immobility
  Bow of Mediocrity

In general I get the results that I want, however I can't help but notice, that certain combinations pop up very frequently, for example

  Ping-Pong Ball of the Occult

occurs very often.
Is there a design flaw that leads to this outcome? Is there a better way to format what I'm trying to achieve?


texts: Finding neighbors and returning average value from neighbors

texts:
I have a list of sales records sorted by sales date. I need to fill in the gaps (days without a sales record) in this list with 'inferred sales' records. The method in question  calculates an average price for the inferred sales records from its closest valid neighbors that have the same SalesType. If there's only one neighbor then no need to average it just returns the sales price of the neighbor. I'd like to improve readability of this method.

public class SalesRecord
{
    public DateTime Date { get; set; }
    public bool IsValid { get; set; }
    public int SalesType { get; set; }
    public double UnitPrice { get; set; }
}
public class SalesDataContainter
{
    private SortedList<DateTime, SalesRecord> salesData;
    private double GetInferredPrice(SalesRecord inferredSalesRecord)
    {
        SalesRecord closestBefore = null;
        SalesRecord closestAfter = null;
        foreach (var salesRecord in salesData.Values)
        {
            //neigbor needs to be valid
            if (salesRecord.IsValid)
            {
                continue;
            }
            //has to have the same sales type
            if (salesRecord.SalesType != inferredSalesRecord.SalesType)
            {
                continue;
            }
            //listed is sorted get the last found for before neighbor
            if (salesRecord.Date < inferredSalesRecord.Date)
            {
                closestBefore = salesRecord;
            }
            //listed is sorted get the first found for after neighbor
            if (closestAfter == null && salesRecord.Date > inferredSalesRecord.Date)
            {
                closestAfter = salesRecord;
            }
        }
        // we have neighbors on both sides
        if (closestBefore != null && closestAfter != null)
        {
            return (closestAfter.UnitPrice + closestBefore.UnitPrice) / 2;
        }
        // there's only before neighbor
        if (closestBefore != null)
        {
            return closestBefore.UnitPrice;
        }
        // there's only after neighbor
        if (closestAfter != null)
        {
            return closestAfter.UnitPrice;
        }
        return 0;
    }
}


texts:
I am still a beginner in CSS and am trying to make a tiles/cards design. I have reached this code, and I want to know if my layout this way is good or if there are any improvements I need to make.

Is writing margin and padding auto is the right practice? How about using flexbox as am doing?

html{
  font-size: 12px;
  font-family: Arial, sans-serif;
}

body{
  margin: auto;
  padding: auto;
  /* What's the best practice to align content in the middle */
}

h1{
  background-color: red;
  text-align: center;
  height: 50px;
  vertical-align: /*What to put here to make it centered? */  ;
}

.flex{
  display: flex;
}

.item{
  width: 30%;
}
.item  h3{
    color: grey;
  }

   .item span{
    font-style: italic;
  }
<!DOCTYPE html>

    <link rel="stylesheet/less" href="style.less" />

Hello Plunker!

        Project 1

        Time: 10:30AM

        Project 2

        Time: 10:30AM

        Project 3

        Time: 10:30AM

        Project 4

        Time: 10:30AM

        Project 5

        Time: 10:30AM


texts: Comparing similar types that don't share any interface

texts:
I have two types that don't share any interface but have similar properties and that I need to compare for equality.

One of them is comming from a 3rd party library and one of them is mine. I obviously cannot add any interface to the foreign type and honestly I don't want to create any wrapper for both of them in order to just use it once for some linq. I prefer to have something that lasts longer and can be reused for other projects.

I used these to types for testing but they might of course have many other properties - and as a matter of fact my two actual types have exactly the same properties as this example:

class PersonLib1
{
  public string FirstName { get; set; }

  public string LastName { get; set; }
}

class PersonLib2
{
  public string FirstName { get; set; }

  public string LastName { get; set; }
}

API

I solved this problem by implementing the IEqualityComparer<object> as a DuckEqualityComparer - its name comes from the idea of Duck Typing - this is, since both types share some common or similar properties they must be the same.

My comparer allows the user to specify the exact types and their comparison logic. The order of the types is not relevant and it tries both combinations.

I used additional blocks of {} inside the Equals method to be able to reuse the short variable names.

class DuckEqualityComparer<Tx, Ty> : IEqualityComparer<object>
{
    private readonly Func<Tx, Ty, bool> _equals;
    private readonly Func<Tx, int> _getHashCodeX;
    private readonly Func<Ty, int> _getHashCodeY;

    private DuckEqualityComparer(Func<Tx, Ty, bool> equals, Func<Tx, int> getHashCodeX, Func<Ty, int> getHashCodeY)
    {
        _equals = equals;
        _getHashCodeX = getHashCodeX;
        _getHashCodeY = getHashCodeY;
    }

    public new bool Equals(object x, object y)
    {
        if (ReferenceEquals(x, y)) return true;
        if (ReferenceEquals(x, null)) return false;
        if (ReferenceEquals(y, null)) return false;
        {
            if (x is Tx tx && y is Ty ty && Equals(tx, ty)) return true;
        }
        {
            if (x is Ty ty && y is Tx tx && Equals(tx, ty)) return true;
        }
        return false;
    }

    private bool Equals(Tx x, Ty y)
    {
        if (ReferenceEquals(x, null)) return false;
        if (ReferenceEquals(y, null)) return false;
        return _equals(x, y);
    }

    public int GetHashCode(object obj)
    {
        switch (obj)
        {
            case Tx x: return _getHashCodeX(x);
            case Ty y: return _getHashCodeY(y);
            default: return 0;
        }
    }

    public static IEqualityComparer<object> Create(Func<Tx, Ty, bool> equals, Func<Tx, int> getHashCodeX, Func<Ty, int> getHashCodeY)
    {

        return new DuckEqualityComparer<Tx, Ty>(equals, getHashCodeX, getHashCodeY);
    }
}

Why didn't I use tuples? Because they don't allow me to use other then the default comparer on the property level.

Is this an acceptable solution or is there anything that could be done better?

Example

This is how I use it:

var p1 = new PersonLib1 { FirstName = "John", LastName = "Doe" };
var p2 = new PersonLib2 { FirstName = "JOHN", LastName = "Doe" };
var p3 = new PersonLib2 { FirstName = "Joh", LastName = "Doe" };

var stringComparer = StringComparer.OrdinalIgnoreCase;
var personComparer = DuckEqualityComparer<PersonLib1, PersonLib2>.Create(
    equals: (x, y) =>
        stringComparer.Equals(x.FirstName, y.FirstName) &&
        stringComparer.Equals(x.LastName, y.LastName),
    getHashCodeX: x =>
        stringComparer.GetHashCode(x.FirstName) +
        stringComparer.GetHashCode(x.LastName),
    getHashCodeY: y =>
        stringComparer.GetHashCode(y.FirstName) +
        stringComparer.GetHashCode(y.LastName)
);

personComparer.Equals(p1, p2).Dump();
personComparer.Equals(p2, p1).Dump();

personComparer.Equals(p1, p3).Dump();
personComparer.Equals(p3, p1).Dump();


texts: Most efficient way to get columns where one is minimum

texts:
I have a table with 3 columns in the format below:

WebcastChannelId, WebcastEventId, SortSequence

1 , 2 , 1
1 , 5 , 2
1 , 3 , 3
2 , 7 , 2
2 , 8 , 1

I would like to get the values for the webcastChannelId  and WebcastEventId with the minimum sort sequence.

In the above example this would be:

WebcastChannelId, WebcastEventId, SortSequence

1 , 2 , 1
2 , 8 , 1

I have the following, which gets what I require, but I don't know if there is a more efficient way to do this?

SELECT wcwel.WebcastChannelId, wcwel.WebcastEventId
FROM [dbo].[WebcastChannelWebcastEventLink] wcwel with (nolock)
inner join [dbo].[WebcastChannelWebcastEventLink] wcwel1 with (nolock) on wcwel1.WebcastChannelId = wcwel.WebcastChannelId
group by
wcwel.WebcastChannelId,
wcwel.WebcastEventId,
wcwel.SortSequence
having
wcwel.SortSequence = MIN(wcwel1.SortSequence)


texts: Refactoring a class / map of query parameters that are passed between layers

texts:
There is an interface:

interface JournalCreator {

    @Async
    Journal create(Parameters params);
}

And many different implementations:

class CarsJournal implements JournalCreator {

    @Autowired
    private JournalRepo journalRepo;

    @Override
    public Journal create(Parameters params) {
        String name = params.getName();
        long id = params.getId();
        // do something with name / id
        // ...
        return journalRepo.getCars(name, id);
    }
}

class MotoJournal implements JournalCreator {

    @Autowired
    private JournalRepo journalRepo;

    @Override
    public Journal create(Parameters params) {
        return journalRepo.getMoto(params.getName(),
                                   params.getId(),
                                   params.getAge(),
                                   params.getColor());
    }
}

The problem is that Parameters class acts like a container for all possible parameters that could be passed to different methods in different controllers:

class Parameters {

    private String name;
    private long id;
    private int age;
    private Color color;

    // dozens of other fields
    // getters and setters
}

One of many controllers example:

@RestController
class CarsController {

    private JournalCreator carsJCreator;

    @Autowired
    public JournalController(JournalCreator carsJCreator) {
        this.carsJCreator = carsJCreator;
    }

    @RequestMapping("...")
    public Journal createCarsJournal(@RequestBody Parameters params) {
        return carsJCreator.create(params);
    }
}

The Parameters class became some kind of a god-object that holds too may different parameters. Also, this is inefficient in terms of memory, because most often only several parameters are used to be passed between different layers.

There could be the Map<String, Object> params instead of Parameters, but I also don't like this idea too much, because it requires a bunch of casts (and it's a bad practice to use an Object as a generic type).

Are there any other alternatives of how to deal with such variations of parameters?


texts:
As suggested by the name of source file (ex1.12.scm), I just started learning mit-scheme by reading SICP. In Exercise 1.12, I'm asked to "compute elements of Pascal's triangle by means of a recursive process." For fun and extra practice, I wrote a program to print the whole triangle. (It took me several minutes to print a Pascal's triangle, and several hours to beautify it :/)

(define (pascal x)
  (define (pascal-iter m n max-len)
    (cond ((and (> m 0) (> n 0))
             (pascal-iter m (- n 1) max-len)
             (beauti-print (pascal-item m n) max-len))
          ((= n 0) (pascal-iter (- m 1) (- m 1) max-len)
                   (display "\n")
                   (print-space (* (- x m) max-len)))
          ((= m 0) "Done")))
  (define (pascal-item m n)
    (cond ((= n 1) 1)
          ((= n m) 1)
          (else (+ (pascal-item (- m 1) (- n 1))
                   (pascal-item (- m 1) n)))))
  (define (beauti-print item max-len)
    (print-space (floor (- max-len
                       (/ (num-of-digit item) 2))))
    (display item)
    (print-space (ceiling (- max-len
                         (/ (num-of-digit item) 2)))))
  (define (num-of-digit n)
    (+ (floor (/ (log n) (log 10))) 1) )
  ;; (print-space 1)   -> " "
  ;; (print-space 1.5) -> "  "
  (define (print-space n)
    (cond ((> n 0) (display " ")
                (print-space (- n 1)))
          (else (display ""))))
  (pascal-iter x x (num-of-digit (pascal-item x (/ x 2)))))

(pascal 12)

Here is the output:

;Loading "ex1.12.scm"...

                                   1
                                1     1
                             1     2     1
                          1     3     3     1
                       1     4     6     4     1
                    1     5     10    10    5     1
                 1     6     15    20    15    6     1
              1     7     21    35    35    21    7     1
           1     8     28    56    70    56    28    8     1
        1     9     36    84   126   126    84    36    9     1
     1     10    45   120   210   252   210   120    45    10    1
  1     11    55   165   330   462   462   330   165    55    11    1
;... done

One of its drawbacks is obvious: recursion is very expensive. In fact, (pascal 15) would produce ;Aborting!: maximum recursion depth exceeded on my machine.

However, please don't put too much emphasis on performance-related issues when answering this question, because I think for me, for this moment, the form of good programming habits takes higher priority than the optimization of algorithm. As a result, please focus on readability, code style and so on.