Use base class as template’s type in C++

I have a base class and two classes on top of it, and another template class like below.

class Base {}
class A : Base {}
class B : Base {}

template <typename T>
class C {}

I need to have a variable in instance of either C or C. I am wondering if there is any way I can have the variable in type of C. I tried to assign C or C to C, but it got an error “no conversion from C to C”. Any suggestions will be appreciated!

c++ – OpenGL Mesh Class

I’ve written a simple mesh class. The purpose of it is to build a mesh, draw it to the screen, and provide some means by which the mesh can be transformed/scaled, etc. This was done with GLAD, GLFW, GLM, and OpenGL.

/*
The mesh class takes vertex data, binds VAOs, VBOs, drawing orders, etc, and draws it.
Other classes can inherit from this class.
*/
class Mesh {
private:

    //-------------------------------------------------------------------------------------------
    // GLenum: drawing mode (ie GL_STATIC_DRAW) and primitive type (ie GL_TRIANGLES)
    GLenum DRAW_MODE, PRIMITIVE_TYPE;

    //-------------------------------------------------------------------------------------------
    // Vertex buffer object, vertex array object, element buffer object
    unsigned int VBO, VAO, EBO;

protected:
    //-------------------------------------------------------------------------------------------
    // Vectors holding vertex and index data
    std::vector<Vertex> vertices;
    std::vector<unsigned int> indices;

    //-------------------------------------------------------------------------------------------
    void init() {
        // Generate vertex arrays
        glGenVertexArrays(1, &VAO);
        // Generate VBO
        glGenBuffers(1, &VBO);
        // Generate EBO
        glGenBuffers(1, &EBO);

        // Bind the VAO
        glBindVertexArray(VAO);

        // Bind the buffer
        glBindBuffer(GL_ARRAY_BUFFER, VBO);
        // Detail the VBO buffer data - attach the vertices
        glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(Vertex), &vertices(0), DRAW_MODE);

        // Bind the indices
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
        // Detail the EBO data
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int),
            &indices(0), DRAW_MODE);

        glEnableVertexAttribArray(0);
        // Tell OpenGL how the vertex data is structured
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)0);
        glBindVertexArray(0);
    }

    //-------------------------------------------------------------------------------------------
    void set_vertices(std::vector<Vertex> _vertices) {
        vertices = _vertices;
    }

    //-------------------------------------------------------------------------------------------
    void set_indices(std::vector<unsigned int> _indices) {
        indices = _indices;
    }

    //-------------------------------------------------------------------------------------------
    void set_primitive_type(GLenum _PRIMITIVE_TYPE) {
        PRIMITIVE_TYPE = _PRIMITIVE_TYPE;
    }

    //-------------------------------------------------------------------------------------------
    void set_draw_mode(GLenum _DRAW_MODE) {
        DRAW_MODE = _DRAW_MODE;
    }

public:
    //-------------------------------------------------------------------------------------------
    Mesh(std::vector<Vertex> _vertices, std::vector<unsigned int> _indices,
        GLenum _DRAW_MODE = GL_STATIC_DRAW, GLenum _PRIMITIVE_TYPE = GL_TRIANGLES) {
        this->vertices = _vertices;
        this->indices = _indices;
        this->DRAW_MODE = _DRAW_MODE;
        this->PRIMITIVE_TYPE = _PRIMITIVE_TYPE;
        //std::cout << vertices(0).position.x << std::endl;
        init();
    }

    //-------------------------------------------------------------------------------------------
    // Constructor for an empty mesh. Note: it MUST RECIEVE VERTEX DATA
    Mesh(GLenum _DRAW_MODE = GL_STATIC_DRAW, GLenum _PRIMITIVE_TYPE = GL_TRIANGLES) {
        this->DRAW_MODE = _DRAW_MODE;
        this->PRIMITIVE_TYPE = _PRIMITIVE_TYPE;
    }

    //-------------------------------------------------------------------------------------------
    virtual ~Mesh() {
        glDeleteVertexArrays(1, &VAO);
        glDeleteBuffers(1, &VBO);
        glDeleteBuffers(1, &EBO);
    }

    //-------------------------------------------------------------------------------------------
    virtual void update() {}

    //-------------------------------------------------------------------------------------------
    void draw() {
        // Bind the EBO
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
        // Bind the vertex array object
        glBindVertexArray(VAO);

        // Ready to draw
        glDrawElements(PRIMITIVE_TYPE, indices.size(), GL_UNSIGNED_INT, 0);
        // Unbind the vertex array (although this isn't entirely necessary)
        glBindVertexArray(0);
    }

    //-------------------------------------------------------------------------------------------
    /* Now I will introduce some simple mesh transformation functions */
    void move(glm::vec3 _position) {
        // Transform each vertex in the given vector to achieve the desired effect
        for (std::size_t i = 0; i < vertices.size(); i++) {
            vertices(i).position += _position;
        }
    }

    //-------------------------------------------------------------------------------------------
    void scale(float factor) {
        // Initalise as identity matrix
        glm::mat3 scaling_matrix = glm::mat3();
        // Multiply by the scaling factor
        scaling_matrix = factor * scaling_matrix;
        // Apply the transformation
        for (std::size_t i = 0; i < vertices.size(); i++) {
            vertices(i).position = scaling_matrix * vertices(i).position;
        }
    }
};

I have also made a simple application of the mesh class: drawing a plane.

// A simple plane, the test shape that we'll use for drawing
class Plane : public Mesh {
private:
    //-------------------------------------------------------------------------------------------
    // Amount of vertices in the x direction
    std::size_t SIZE_X = 100;
    // Amount of vertices in the y direction
    std::size_t SIZE_Y = 100;
    // Width between vertices (x direction)
    std::size_t VERTEX_WIDTH = 1;
    // 'Height' between vertices (y direction)
    std::size_t VERTEX_HEIGHT = 1;

    //-------------------------------------------------------------------------------------------
    std::vector<Vertex> vertices;
    std::vector<unsigned int> indices;

    //-------------------------------------------------------------------------------------------
    // Set up the plane
    void create_mesh_plane() {
        const int w = SIZE_X + 1;
        for (std::size_t i = 0; i < SIZE_X + 1; i++) {
            for (std::size_t j = 0; j < SIZE_Y + 1; j++) {
                Vertex v;
                v.position.x = i * VERTEX_WIDTH;
                v.position.y = j * VERTEX_HEIGHT;
                v.position.z = 0;
                vertices.push_back(v);

                unsigned int n = j * (SIZE_X + 1) + i;

                if (j < SIZE_Y && i < SIZE_X) {
                    // First face
                    indices.push_back(n);
                    indices.push_back(n + 1);
                    indices.push_back(n + w);
                    // Second face
                    indices.push_back(n + 1);
                    indices.push_back(n + 1 + w);
                    indices.push_back(n + 1 + w - 1);
                }
            }
        }

        //-------------------------------------------------------------------------------------------
        set_vertices(vertices);
        set_indices(indices);
        set_primitive_type(GL_TRIANGLES);
        set_draw_mode(GL_STATIC_DRAW);
        init();
    }

public:

    //-------------------------------------------------------------------------------------------
    Plane() {
        create_mesh_plane();
    }

    //-------------------------------------------------------------------------------------------
    ~Plane() {

    }
};

This code works, and you can instantiate a plane object and draw it in your render function and it will work quickly and nicely.

I’m looking at a review on this code because it’s going to become a centrepiece of future things I work on with OpenGL and am concerned about the efficiency, particularly:

  • Multiple instantiations of mesh-like objects lead to multiple VBOs, causing unnecessary buffer switches.

  • The vectors seem like an incredibly inefficient way of storing the data. Particularly because as can be seen in my move() and scale() functions, I’m iterating over them, which is extremely slow in realtime and very detrimental to performance. Also, if I want to dynamically update mesh vertex data (I added a virtual update function for this purpose) it would be extremely slow.

  • I could probably split up the init() function such that it doesn’t have to be recalled every time the vertex data changes (ie, the drawing order is still the same, I could just feed in the new vertex data if I wanted to update the vertex data of the mesh during its existence).

I’d be grateful for any feedback.

javascript – Selector to ignore all elements inside a given class

I am trying to select all elements that are not inside the following divs <div class="manager"></div> or <div class="release"></div>.

So I have made my selector below however it is incorrectly selecting elements inside those above div’s. Do you know how I can update my selector to ignore all elements inside <div class="manager"></div> and <div class="release"></div>?

$('*:not(.release, .manager) *').filter(function () { 
   return $(this).css('position') == 'fixed';
}).addClass('reset-pos');

Here is how my html is organised:

<body>
    <div>
        ...
    </div>

    <!-- This element and all below should be ignored/not selected -->
    <div class="manager">
        ...
    </div>

    <!-- This element and all below should be ignored/not selected -->
    <div class="release">
        ...
    </div>
</body>

c# – How to design a class holding information about a relationship between two interchangable objects

I’d like to design a class that holds comparison results about to objects.

Given I have a class Thing and that Thing has a bunch of properties. Now I have an engine that compares Thing instances (held in a collection) to one another. Comparisons are actually Types deriving from a Comparison base class and can be fairly complex (e.g. ColorComparison). The actual result is not of importance, only that the comparison results in a match. So if comparing two Thing instances succeeds the comparison will be stored in a Match class, along with information about the applied comparison. So a Match class might have the properties

I later need to store the Match class instances in a HashSet for fast lookup. What identifies a Match is the combination of ThingA and ThingB. In a perfect world the Match class could provide the same Hash for ThingA = x and ThingB = y vs. ThingA = y and ThingB = x. It might be later needed that not only one Comparison is stored within a Match but several different.

Some additional implementation notes:

  • Once a Match class has been instanciated, both ThingA and ThingB are immutable
  • The Things inside a Match cannot be manipulated (e.g. I cannot store the relationship information inside them)

My question is, how to I design the Match class in a way that when the HashSet is searched for the x and y combination of Things it also finds the y and x combination.

views – How to Add Active class on click of link

I have created a view of taxonomy term. In View’s field area added Taxonomy name and ID(Exclude from display). In field-> Name’s configuration details Overriding output of this field in rewrite area eg. {{ name }}, And selected output this field as custom link. So my question is How can I add active class on it. Because in UI after click on Name its navigating to other page(that is given in output link path) and page is getting refreshed.

views

python 3.x – Wrap functions which run in two threads in one class

My application consist of two threads.
One – is running http server with aiohttp

Second thread is asking another web resource about current currency.

So there are two threads with asyncronous requests.
But I was struggling to run my http-server in another thread, I found solution here

I need two threads here because server must be asyncronous and request to another server must also be asyncronous , that is why two threads.

My code is below:

import asyncio
import json
import threading

from aiohttp import web, ClientSession
from random import randint


common_dict = {
    'USD': 60,
    'EUR': 70,
    'RUB': 1,
}


async def fetch(session, url):
    async with session.get(url) as response:
        return await response.text()



# GETTING CURRENCY
# Thread number one
async def fetch_currency():
    """ Here we get currency once in 30 seconds from 
      https://www.cbr-xml-daily.ru/daily_json.js)

    """
    while True:
        async with ClientSession() as session:
            await asyncio.sleep(30)
            data = await fetch(session,
                               'https://www.cbr-xml-daily.ru/daily_json.js')

            response_from_server = json.loads(data, strict=False)
            try:
                usd_value = response_from_server('Valute')('USD')('Value')
            except Exception:
                print(Exception)
            else:
                if usd_value != common_dict.get('USD'):
                    await spit_data_into_console(currency=usd_value)
                    common_dict('USD') = usd_value


#SERVER IN THREAD
# THREAD NUMBER TWO
def aiohttp_server():
    """
    REST API for http-server

    """
    def get_usd_currency(request):
        common_dict('USD') = randint(1, 10)
        return web.Response(text=str(common_dict('USD')))

    def get_euro_currency(request):
        return web.Response(text=str(common_dict('EUR')))

    def get_rub_currency(request):
        return web.Response(text=str(common_dict('RUB')))

    # ...
    # many APIs

    app = web.Application()
    app.add_routes(
        (web.get('/usd/get', get_usd_currency),
         # ...
         # many APIs
         web.get('/eur/get', get_euro_currency),
         web.get('/rub/get', get_rub_currency),
         )
    )
    runner = web.AppRunner(app)
    return runner


def run_server(runner):
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)

    loop.run_until_complete(runner.setup())

    site = web.TCPSite(runner, 'localhost', 8080)
    loop.run_until_complete(site.start())

    loop.run_forever()


# Possible(?) Thread number three
async def spit_data_into_console(currency=None,
                                 total_amount=None):

    """one time in a minute spit data into stdout if currency has changed"""

    await asyncio.sleep(60)
    if currency is not None:
        print('Value of {} has changed'.format(currency))


def main():
    # оthread for http-server
    t = threading.Thread(target=run_server, args=(aiohttp_server(),))
    t.start()

    # thread for json-response from another server
    loop = asyncio.get_event_loop()
    loop.run_until_complete(fetch_currency())


if __name__ == '__main__':
    main()

This is working example.

But it is not looking good. For example I have common_dict as a global variable to exchange data between threads (I must use mutex here probably).

And my server as a

def aiohttp_server():
    """
    REST API for http-server

    """
    def get_usd_currency(request):
        common_dict('USD') = randint(1, 10)
        return web.Response(text=str(common_dict('USD')))

    def get_euro_currency(request):
        return web.Response(text=str(common_dict('EUR')))

    def get_rub_currency(request):
        return web.Response(text=str(common_dict('RUB')))

    # ...
    # many APIs

    app = web.Application()
    app.add_routes(
        (web.get('/usd/get', get_usd_currency),
         # ...
         # many APIs
         web.get('/eur/get', get_euro_currency),
         web.get('/rub/get', get_rub_currency),
         )
    )
    runner = web.AppRunner(app)
    return runner


def run_server(runner):
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)

    loop.run_until_complete(runner.setup())

    site = web.TCPSite(runner, 'localhost', 8080)
    loop.run_until_complete(site.start())

    loop.run_forever()

does not look perfect because I am using here a function (aiohttp_server()) and then define my APIs in this function. What if I need many APIs?

Since this code serves to a task of handling currency I would prefer to wrap it into a class, but I do not know if it is appropriete here or not.

And if it is then how can I create (probably!) a class and then run two different tasks in two threads…?

Thank you very much in advance!

.net – C# class to dump the memory of a process in several formats

I made this because I couldn’t find any good C# classes/libraries that allow you to dump the contents of a process’ memory into a file or a byte array. I haven’t tested this on 32 bit systems but it works in both x86 and x64 on my 64 bit system. I’ve been mostly testing this on the notepad process which executes pretty quickly, but I’ve also tried this on the steam process with 120 mb memory which worked but took around 30 seconds. How can I improve this and what bugs have I overlooked? Any feedback is appreciated, thanks.

MemoryDump.cs

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;

namespace MemoryDumper
{
    public struct Chunk
    {
        public Dumper.MEMORY_BASIC_INFORMATION MemoryInformation;
        public byte() Bytes;
    }

    public class MemoryDump
    {
        public MemoryDump(Chunk() chunks)
        {
            Chunks = chunks;

            long bytesSum = 0;
            foreach (var chunk in chunks)
                bytesSum += chunk.Bytes.Length;

            Bytes = new byte(bytesSum);

            int byteOffset = 0;
            foreach (var chunk in chunks)
            {
                for (int i = 0; i < chunk.Bytes.Length; i++)
                {
                    Bytes(byteOffset + i) = chunk.Bytes(i);
                }
                byteOffset += chunk.Bytes.Length;
            }
        }

        public readonly Chunk() Chunks;
        public readonly byte() Bytes;

        public string BytesString
        {
            get
            {
                byte() cleansedBytes = Bytes;
                for (int i = 0; i < Bytes.Length; i++)
                    cleansedBytes(i) = (byte)ToChar(cleansedBytes(i));

                return Encoding.UTF8.GetString(cleansedBytes);
            }
        }

        public static char ToChar(byte bt)
        {
            bool isPrintable = bt >= 32 && bt <= 126;
            return isPrintable ? (char)bt : '.';
        }

        (Flags)
        public enum DumpSaveOptions
        {
            // ex: 43 6F 77 4E 61 74 69 6F 6E
            BytesArray = 1,
            // ex: CowNation
            BytesString = 2,
            // ex: 43 6F 77 4E 61 74 69 6F 6E | CowNation
            Both = BytesArray | BytesString
        };

        public void Save(string filePath, DumpSaveOptions options = DumpSaveOptions.Both, int bytesPerLine = 56)
        {
            if (!File.Exists(filePath))
                throw new Exception("File '" + filePath + "' doesn't exist");

            bool bytesArray = (options & DumpSaveOptions.BytesArray) != 0;
            bool bytesString = (options & DumpSaveOptions.BytesString) != 0;

            StreamWriter streamWriter = new StreamWriter(filePath);
            for (int i = 0; i < Bytes.Length / bytesPerLine; i++)
            {
                // the bytes for this line
                byte() lineBytes = new byte(bytesPerLine);
                Array.Copy(Bytes, i * bytesPerLine, lineBytes, 0, bytesPerLine);

                string line = "";
                string dataString = "";
                foreach (byte bt in lineBytes)
                {
                    if (bytesArray)
                    {
                        string b = bt.ToString("X");
                        line += (b.Length == 1 ? "0" + b : b) + " ";
                    }

                    if (bytesString)
                        dataString += ToChar(bt);
                }
                line += (bytesArray && bytesString ? "| " : "") + dataString;

                streamWriter.WriteLine(line);
            }

            streamWriter.Close();
        }
    }

    public class Dumper
    {
        #region IMPORTS
        (DllImport("kernel32.dll"))
        static extern IntPtr OpenProcess(ProcessAccessFlags dwDesiredAccess, bool bInheritHandle, int dwProcessId);

        (DllImport("kernel32.dll", SetLastError = true))
        static extern bool ReadProcessMemory(
           IntPtr hProcess,
           IntPtr lpBaseAddress,
           byte() lpBuffer,
           int nSize,
           out IntPtr lpNumberOfBytesRead);

        (DllImport("kernel32.dll"))
        static extern void GetSystemInfo(out SYSTEM_INFO lpSystemInfo);

        (DllImport("kernel32.dll", SetLastError = true))
        static extern int VirtualQueryEx(IntPtr hProcess, IntPtr lpAddress, out MEMORY_BASIC_INFORMATION lpBuffer, uint dwLength);
        #endregion

        #region ENUMS
        public enum AllocationProtectEnum : uint
        {
            PAGE_EXECUTE = 0x00000010,
            PAGE_EXECUTE_READ = 0x00000020,
            PAGE_EXECUTE_READWRITE = 0x00000040,
            PAGE_EXECUTE_WRITECOPY = 0x00000080,
            PAGE_NOACCESS = 0x00000001,
            PAGE_READONLY = 0x00000002,
            PAGE_READWRITE = 0x00000004,
            PAGE_WRITECOPY = 0x00000008,
            PAGE_GUARD = 0x00000100,
            PAGE_NOCACHE = 0x00000200,
            PAGE_WRITECOMBINE = 0x00000400
        }

        public enum StateEnum : uint
        {
            MEM_COMMIT = 0x1000,
            MEM_FREE = 0x10000,
            MEM_RESERVE = 0x2000
        }

        public enum TypeEnum : uint
        {
            MEM_IMAGE = 0x1000000,
            MEM_MAPPED = 0x40000,
            MEM_PRIVATE = 0x20000
        }

        (Flags)
        enum ProcessAccessFlags : uint
        {
            All = 0x001F0FFF,
            Terminate = 0x00000001,
            CreateThread = 0x00000002,
            VirtualMemoryOperation = 0x00000008,
            VirtualMemoryRead = 0x00000010,
            VirtualMemoryWrite = 0x00000020,
            DuplicateHandle = 0x00000040,
            CreateProcess = 0x000000080,
            SetQuota = 0x00000100,
            SetInformation = 0x00000200,
            QueryInformation = 0x00000400,
            QueryLimitedInformation = 0x00001000,
            Synchronize = 0x00100000
        }
        #endregion

        #region STRUCTS
        public struct MEMORY_BASIC_INFORMATION
        {
            public IntPtr BaseAddress;
            public IntPtr AllocationBase;
            public AllocationProtectEnum AllocationProtect;
            public IntPtr RegionSize;
            public StateEnum State;
            public AllocationProtectEnum Protect;
            public TypeEnum Type;
        }

        (StructLayout(LayoutKind.Sequential))
        public struct SYSTEM_INFO
        {
            public ushort processorArchitecture;
            ushort reserved;
            public uint pageSize;
            public IntPtr minimumApplicationAddress;
            public IntPtr maximumApplicationAddress;
            public IntPtr activeProcessorMask;
            public uint numberOfProcessors;
            public uint processorType;
            public uint allocationGranularity;
            public ushort processorLevel;
            public ushort processorRevision;
        }
        #endregion

        public static MemoryDump Dump(Process process)
        {
            if (process == Process.GetCurrentProcess()) // a recursive memory allocation loop happens in this case until it runs out of memory
                throw new Exception("Cannot dump the memory of this process");

            List<Chunk> chunks = new List<Chunk>();

            SYSTEM_INFO systemInfo = new SYSTEM_INFO();
            GetSystemInfo(out systemInfo);

            IntPtr minimumAddress = systemInfo.minimumApplicationAddress;
            IntPtr maximumAddress = systemInfo.maximumApplicationAddress;

            IntPtr processHandle = OpenProcess(ProcessAccessFlags.QueryInformation | ProcessAccessFlags.VirtualMemoryRead, false, process.Id);
            if (processHandle == IntPtr.Zero)
                throw new Exception("Cannot get a handle to process");

            while (minimumAddress.ToInt64() < maximumAddress.ToInt64())
            {
                MEMORY_BASIC_INFORMATION memoryInformation = new MEMORY_BASIC_INFORMATION();
                VirtualQueryEx(processHandle, minimumAddress, out memoryInformation, (uint)Marshal.SizeOf(typeof(MEMORY_BASIC_INFORMATION)));

                // check if this chunk is accessible
                if (memoryInformation.Protect == AllocationProtectEnum.PAGE_READWRITE && memoryInformation.State == StateEnum.MEM_COMMIT)
                {
                    byte() buffer = new byte(memoryInformation.RegionSize.ToInt64());
                    ReadProcessMemory(processHandle, memoryInformation.BaseAddress, buffer, memoryInformation.RegionSize.ToInt32(), out IntPtr bytesRead);

                    chunks.Add(new Chunk
                    {
                        MemoryInformation = memoryInformation,
                        Bytes = buffer
                    });
                }

                // move to the next chunk
                try
                {
                    minimumAddress = new IntPtr(minimumAddress.ToInt64() + memoryInformation.RegionSize.ToInt64());
                }
                catch (OverflowException)
                {
                    break;
                }
            }

            return new MemoryDump(chunks.ToArray());
        }
    }
}

Example Usage:

    var dump = Dumper.Dump(Process.GetProcessesByName("notepad")(0));
    dump.Save("dump.txt");
    File.WriteAllText("bytesString.txt", dump.BytesString);

refactoring – How to clean up a business logic class that does too many things without injecting a ton of classes into it?

Let’s say we have business logic to perform in an MVC framework after a user submits a form:

class BusinessLogic:
    def sendDataTo3rdPartyApi(self):
        # do stuff
    def validateResponse(self):
        # do stuff 
    def persistData(self):
        # do stuff 
    def calculateFees(self):
        # do stuff 
    def sendDataToAnotherApi(self):
        # do stuff

POST form data is received by the controller and it passes that data to the business logic layer for processing. All of these functions are necessary to process the data. We recognize that this BusinessLogic class is likely doing to many things, so we abstract the various methods into their own classes and inject them via DI:

class BusinessLogic:
    def __init__(self, dataSender, validator, dataPersister, feeCalculator, anotherDataSender):
        # assign objects to private properties within class
    def doLogic(self):
        # utilize the injected classes to perform necessary business logic

The problem I see with this approach is that abstracting the functions into classes that perform one thing still leaves us with a class that does too many things–it’s just in the form of classes instead of functions. We can try to move these classes out of this class, but we would just be sending the dependencies up into the controller. As our business logic gets more complex, the more we’re going to have to inject since we’re creating a class for each particular business requirement.

I feel like no matter what you do, you’ll always require a god class of some sort to organize the different parts together for execution. Now I’m unsure if this is necessarily a bad thing, but I’m wondering if there is a better approach to refactoring a business logic class like this.

python – what is the best way to implement if its just one method on a framework? should we declare it under a class or leave it independent?

I have a framework to handle web scraping, and written helper functions libraries.
But there is one method that dont fit in any class, but its required. Should I enclose it in a class or leave it as an independent method. Please clarify the best approach for this situation in coding style. thanks