r/StackoverReddit • • Sep 25 '24

Python Which is the best ide for python

0 Upvotes

r/StackoverReddit • • Jul 08 '24

C++ šŸ“Œ Asynchronous Programming With C++ šŸ“Œ

4 Upvotes

Hi there, I've been working on a project in C++, and I am very proud of the results, I hope you like it.

The project is called NodePP, it is a framework for C++, which changes the syntax of C++, for one that is more friendly and similar to NodeJS. In order to create scalable and efficient applications in C++.

The project adds support for:

  • šŸ“Œ: Coroutines & Generators

  • šŸ“Œ: Regex & Json Processing

  • šŸ“Œ: HTTP/s, TCP, TLS & WebSocket servers

  • šŸ“Œ: HTTP/s, TCP, TLS & WebSocket clients

  • šŸ“Œ: Events, Promises, Observers & Timers

The great thing about this project is that I do not use threads at all, but internally create an Event-Loop, which is responsible for executing the tasks in the background, and with the help of the native non-blocking api (windows | posix) , and with the help of Poll ( Poll | Epoll | WsaPoll ), create a 100% asynchronous framework.

Here is the link of the project:

If you are interested in knowing the usefulness of this framework, here is a list of projects that I have done 100% with this framework:


r/StackoverReddit • • Sep 08 '24

Question Python or web development

0 Upvotes

what do you guys recommend


r/StackoverReddit • • Jun 29 '24

Confusion regarding f strings

5 Upvotes

I wish to get this result

Hello, Ada Lovelace

The code written for this by a book is
first_name = "ada"
last_name = "lovelace"
full_name = f"{first_name} {last_name}"
print(f"Hello, {full_name.title()}")

But I was wondering, why cant it be this

first_name = "ada"
last_name = "lovelace"
full_name = f"{first_name} {last_name}"
print(f"Hello, {full_name}.title()")

the result of this is
Hello, ada lovelace.title()

I was wondering why this is so?
My reasoning is that the title method can be used on strings right? so then in my case, python would interpret {full_name} as a string, so it should work. Is it the case that methods work only on variables?


r/StackoverReddit • • Jul 27 '24

C Brainfuck x86_64 execution toolset for Linux: interpreter and compiler

6 Upvotes

Hello, redditors! With a great joy I want to share my first toolset made of interpreter and compiler for x86_64 processor architecture that is able to produce ELF64 executables for Linux.

I always had a dream of implementing an interpreter or a compiler and I finally achieved this goal by creating both for the brainfuck programming language in C. To implement the compiler I learned some basics of the x86_64 NASM assembly from scratch.

You can find the source code at GitHub repo: https://github.com/detectivekaktus/brainc, it also has some examples you can run with the toolset.


r/StackoverReddit • • Jul 30 '24

Python where and how do i change the two needed directory paths for this project I'm following.

2 Upvotes

Sorry about the very dumb question and please feel free to call me dumb because i feel it right now. I wanted to try this project out and cant figure out what lines to change to point to my folders of pictures.

I think its lines 31 and 32 but when i change it doesn't work.

haystackPaths = list(paths.list_images(args["haystack"]))

this is what ive tried.

haystackPaths = list(paths.list_images(args["/path/to/folder"]))

haystackPaths = list(paths.list_images(args[/path/to/folder]))

any help would be great thank you


r/StackoverReddit • • Jul 06 '24

Java Can't edit player's nametag with packets using Protocollib, getting an exception, need help.

1 Upvotes

Hello, I am trying to edit a player's nametag in Minecraft using packets, but I'm getting an exception when I do so. I've looked online and the only other person who seems to have my problem had 0 people respond to their post.

The code I have is this.

String NameJSON = JSONComponentSerializer.json().serialize(Component.text("Testing\nline2")
        .color(NamedTextColor.YELLOW));
PacketContainer TestPacket = GetProtocolManager().createPacket(PacketType.Play.Server.PLAYER_INFO);
ArrayList<PlayerInfoData> Data = new ArrayList<>();
Data.add(new PlayerInfoData(WrappedGameProfile.fromPlayer(GetPlayer()), GetPlayer().getPing(),
        EnumWrappers.NativeGameMode.fromBukkit(GetGameMode()),
        WrappedChatComponent.fromJson(NameJSON)));
TestPacket.getPlayerInfoAction().write(0, EnumWrappers.PlayerInfoAction.UPDATE_DISPLAY_NAME);
TestPacket.getPlayerInfoDataLists().write(0, Data);
GetProtocolManager().sendServerPacket(GetPlayer(), TestPacket);

PacketContainer TestPacket = GetProtocolManager().createPacket(PacketType.Play.Server.PLAYER_INFO);
ArrayList<PlayerInfoData> Data = new ArrayList<>();
Data.add(new PlayerInfoData(WrappedGameProfile.fromPlayer(GetPlayer()), GetPlayer().getPing(),
        EnumWrappers.NativeGameMode.fromBukkit(GetGameMode()),
        WrappedChatComponent.fromJson(NameJSON)));
TestPacket.getPlayerInfoAction().write(0, EnumWrappers.PlayerInfoAction.UPDATE_DISPLAY_NAME);
TestPacket.getPlayerInfoDataLists().write(0, Data);
GetProtocolManager().sendServerPacket(GetPlayer(), TestPacket);

The exception is (sorry for formatting)

(Field index 0 is out of bounds for length 0) Stack trace: ProtocolLib.jar//com.comphenix.protocol.reflect.FieldAccessException.fromFormat(FieldAccessException.java:49) ProtocolLib.jar//com.comphenix.protocol.reflect.StructureModifier.write(StructureModifier.java:318) BSripoff.jar//sus.keiger.bsripoff.game.entity.kit.KitInstance.<init>(KitInstance.java:108) BSripoff.jar//sus.keiger.bsripoff.game.entity.kit.sward.SwardKitInstance.<init>(SwardKitInstance.java:53) BSripoff.jar//sus.keiger.bsripoff.game.entity.kit.sward.SwardKit.CreateInstance(SwardKit.java:43) BSripoff.jar//sus.keiger.bsripoff.game.BasicGameInstance.SetPlayerToInGameState(BasicGameInstance.java:471) BSripoff.jar//sus.keiger.bsripoff.game.BasicGameInstance.AddPlayer(BasicGameInstance.java:660) BSripoff.jar//sus.keiger.bsripoff.command.GameCommand.JoinGame(GameCommand.java:249) BSripoff.jar//sus.keiger.plugincommon.command.CommandNode.ExecuteCommand(CommandNode.java:47) BSripoff.jar//sus.keiger.plugincommon.command.CommandNode.TryPassExecuteToNextNode(CommandNode.java:144) BSripoff.jar//sus.keiger.plugincommon.command.CommandNode.ExecuteCommand(CommandNode.java:43) BSripoff.jar//sus.keiger.plugincommon.command.CommandNode.TryPassExecuteToNextNode(CommandNode.java:144) BSripoff.jar//sus.keiger.plugincommon.command.CommandNode.ExecuteCommand(CommandNode.java:43) BSripoff.jar//sus.keiger.plugincommon.command.CommandNode.TryPassExecuteToNextNode(CommandNode.java:144) BSripoff.jar//sus.keiger.plugincommon.command.CommandNode.ExecuteCommand(CommandNode.java:43) BSripoff.jar//sus.keiger.plugincommon.command.ServerCommand.onCommand(ServerCommand.java:76) org.bukkit.command.PluginCommand.execute(PluginCommand.java:45) io.papermc.paper.command.brigadier.bukkit.BukkitCommandNode$BukkitBrigCommand.run(BukkitCommandNode.java:91) com.mojang.brigadier.context.ContextChain.runExecutable(ContextChain.java:73) net.minecraft.commands.execution.tasks.ExecuteCommand.execute(ExecuteCommand.java:30) net.minecraft.commands.execution.tasks.ExecuteCommand.execute(ExecuteCommand.java:13) net.minecraft.commands.execution.UnboundEntryAction.lambda$bind$0(UnboundEntryAction.java:8) net.minecraft.commands.execution.CommandQueueEntry.execute(CommandQueueEntry.java:5) net.minecraft.commands.execution.ExecutionContext.runCommandQueue(ExecutionContext.java:103) net.minecraft.commands.Commands.executeCommandInContext(Commands.java:456) net.minecraft.commands.Commands.performCommand(Commands.java:363) net.minecraft.commands.Commands.performCommand(Commands.java:350) net.minecraft.commands.Commands.performCommand(Commands.java:345) net.minecraft.server.network.ServerGamePacketListenerImpl.performUnsignedChatCommand(ServerGamePacketListenerImpl.java:2282) net.minecraft.server.network.ServerGamePacketListenerImpl.lambda$handleChatCommand$18(ServerGamePacketListenerImpl.java:2256) net.minecraft.server.TickTask.run(TickTask.java:18) net.minecraft.util.thread.BlockableEventLoop.doRunTask(BlockableEventLoop.java:151) net.minecraft.util.thread.ReentrantBlockableEventLoop.doRunTask(ReentrantBlockableEventLoop.java:24) net.minecraft.server.MinecraftServer.doRunTask(MinecraftServer.java:1546) net.minecraft.server.MinecraftServer.doRunTask(MinecraftServer.java:195) net.minecraft.util.thread.BlockableEventLoop.pollTask(BlockableEventLoop.java:125) net.minecraft.server.MinecraftServer.pollTaskInternal(MinecraftServer.java:1523) net.minecraft.server.MinecraftServer.pollTask(MinecraftServer.java:1446) net.minecraft.util.thread.BlockableEventLoop.managedBlock(BlockableEventLoop.java:135) net.minecraft.server.MinecraftServer.waitUntilNextTick(MinecraftServer.java:1412) net.minecraft.server.MinecraftServer.runServer(MinecraftServer.java:1273) net.minecraft.server.MinecraftServer.lambda$spin$0(MinecraftServer.java:326) java.base/java.lang.Thread.run(Thread.java:1583)

I've tried switching up the player action to player action list, that creates a can't assign to private final field exception. Removing the player action write line also creates the same can't assign to private final field exception. I'm unsure where the problem is. I tried updating to the latest dev build but it made no difference. The exception points to the line

TestPacket.getPlayerInfoAction().write(0, EnumWrappers.PlayerInfoAction.UPDATE_DISPLAY_NAME);

Any help is appreciated.


r/StackoverReddit • • Jun 23 '24

Python Python - Help to create Dynamic custom PDF Reports based on input results.

Thumbnail self.learnprogramming
1 Upvotes

r/StackoverReddit • • Sep 21 '24

Question how can I concentrate when I am coding

0 Upvotes

any tips


r/StackoverReddit • • Jul 25 '24

C writing keyboard and mouse locker with Golang or C

1 Upvotes

Hey, I want to write a simple application that runs in Windows, listens for a special shortcut key (for example, ctrl+shift+L) to lock the keyboard and mouse (so no one can click with the mouse or type with the keyboard), and waits to receive a special shortcut key to unlock the keyboard and mouse (like ctrl+shift+U). I wrote this app, but the problem is that it is completely blocked and cannot be unlocked. Could you please help me?

With C:

#include <windows.h>
#include <stdio.h>

#define LOCK_HOTKEY_ID 1
#define UNLOCK_HOTKEY_ID 2

BOOL locked = FALSE;
HHOOK hKeyboardHook = NULL;
HHOOK hMouseHook = NULL;
HWND mainWindow = NULL;

// Function declarations
void DisableTaskManager();
void EnableTaskManager();
void UnlockSystem();

void UnlockSystem() {
    if (locked) {
        printf("Unlocking keyboard and mouse\n");
        locked = FALSE;
        EnableTaskManager();
        if (hKeyboardHook) {
            UnhookWindowsHookEx(hKeyboardHook);
            hKeyboardHook = NULL;
        }
        if (hMouseHook) {
            UnhookWindowsHookEx(hMouseHook);
            hMouseHook = NULL;
        }
    }
}

//LRESULT CALLBACK LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam)
//{
//    if (nCode == HC_ACTION && wParam == WM_KEYDOWN)
//    {
//        KBDLLHOOKSTRUCT *pKeyBoard = (KBDLLHOOKSTRUCT *)lParam;
//        BOOL ctrlPressed = (GetAsyncKeyState(VK_CONTROL) & 0x8000) != 0;
//        BOOL shiftPressed = (GetAsyncKeyState(VK_SHIFT) & 0x8000) != 0;
//
//        if (ctrlPressed && shiftPressed && pKeyBoard->vkCode == 'U')
//        {
//            UnlockSystem();
//            return 1; // Prevent further processing
//        }
//        if (locked)
//        {
//            return 1; // Discard all other keys
//        }
//    }
//    return CallNextHookEx(hKeyboardHook, nCode, wParam, lParam);
//}

LRESULT CALLBACK LowLevelMouseProc(int nCode, WPARAM wParam, LPARAM lParam)
{
    if (locked)
    {
        return 1; // Discard all mouse events
    }
    return CallNextHookEx(hMouseHook, nCode, wParam, lParam);
}
LRESULT CALLBACK LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam) {
    if (nCode == HC_ACTION && (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN)) {
        KBDLLHOOKSTRUCT *pKeyBoard = (KBDLLHOOKSTRUCT *)lParam;
        BOOL ctrlPressed = (GetAsyncKeyState(VK_CONTROL) & 0x8000) != 0;
        BOOL shiftPressed = (GetAsyncKeyState(VK_SHIFT) & 0x8000) != 0;

        // Directly check for the unlock shortcut here
        if (ctrlPressed && shiftPressed && pKeyBoard->vkCode == 'U') {
            UnlockSystem();
            return 1; // Prevent further processing of this key press
        }

        if (locked) {
            return 1; // Block all other keys when locked
        }
    }
    return CallNextHookEx(NULL, nCode, wParam, lParam);
}

// Function to disable Task Manager
void DisableTaskManager() {
    HKEY hKey;
    RegOpenKeyEx(HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System", 0, KEY_ALL_ACCESS, &hKey);
    DWORD value = 1;
    RegSetValueEx(hKey, "DisableTaskMgr", 0, REG_DWORD, (const BYTE*)&value, sizeof(value));
    RegCloseKey(hKey);
}

// Function to enable Task Manager
void EnableTaskManager() {
    HKEY hKey;
    RegOpenKeyEx(HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System", 0, KEY_ALL_ACCESS, &hKey);
    DWORD value = 0;
    RegSetValueEx(hKey, "DisableTaskMgr", 0, REG_DWORD, (const BYTE*)&value, sizeof(value));
    RegCloseKey(hKey);
}

LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch (uMsg)
    {
        case WM_HOTKEY:
            if (wParam == LOCK_HOTKEY_ID && !locked)
            {
                printf("Locking keyboard and mouse\n");
                DisableTaskManager();
                locked = TRUE;
                hKeyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, LowLevelKeyboardProc, NULL, 0);
                hMouseHook = SetWindowsHookEx(WH_MOUSE_LL, LowLevelMouseProc, NULL, 0);
                if (!hKeyboardHook || !hMouseHook)
                {
                    printf("Failed to set hooks: %d\n", GetLastError());
                }
            }
            else if (wParam == UNLOCK_HOTKEY_ID)
            {
                UnlockSystem();
            }
            break;
        case WM_DESTROY:
            PostQuitMessage(0);
            return 0;
    }
    return DefWindowProc(hwnd, uMsg, wParam, lParam);
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    // Create a window to receive messages
    WNDCLASS wc = {0};
    wc.lpfnWndProc = WindowProc;
    wc.hInstance = hInstance;
    wc.lpszClassName = "KeyboardMouseLockerClass";
    RegisterClass(&wc);

    HWND hwnd = CreateWindowEx(
        0,
        "KeyboardMouseLockerClass",
        "Keyboard and Mouse Locker",
        WS_OVERLAPPEDWINDOW,
        CW_USEDEFAULT, CW_USEDEFAULT, 400, 300,
        NULL,
        NULL,
        hInstance,
        NULL
    );

    if (hwnd == NULL)
    {
        printf("Failed to create window\n");
        return 1;
    }

    mainWindow = hwnd;

    // Register hotkeys
    if (!RegisterHotKey(hwnd, LOCK_HOTKEY_ID, MOD_CONTROL | MOD_SHIFT, 'K'))
    {
        printf("Failed to register lock hotkey. Error: %d\n", GetLastError());
        printf("Failed to register lock hotkey\n");
        return 1;
    }
    if (!RegisterHotKey(hwnd, UNLOCK_HOTKEY_ID, MOD_CONTROL | MOD_SHIFT, 'P'))
    {
        printf("Failed to register unlock hotkey. Error: %d\n", GetLastError());
        printf("Failed to register unlock hotkey\n");
        return 1;
    }

    printf("Keyboard and Mouse Locker\n");
    printf("Press Ctrl+Shift+L to lock\n");
    printf("Press Ctrl+Shift+U to unlock\n");

    // Message loop
    MSG msg = {0};
    while (GetMessage(&msg, NULL, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    // Unregister hotkeys
    UnregisterHotKey(hwnd, LOCK_HOTKEY_ID);
    UnregisterHotKey(hwnd, UNLOCK_HOTKEY_ID);

    if (hKeyboardHook)
    {
        UnhookWindowsHookEx(hKeyboardHook);
    }
    if (hMouseHook)
    {
        UnhookWindowsHookEx(hMouseHook);
    }

    return 0;
}

With Golang:

package main

import (
    "fmt"
    "syscall"
    "time"

    "github.com/TheTitanrain/w32"
)

var (
    user32     = syscall.MustLoadDLL("user32.dll")
    blockinput = user32.MustFindProc("BlockInput")
)

type BOOL int32

func BoolToBOOL(value bool) BOOL {
    if value {
        return 1
    }

    return 0
}

func blockInput(fBlockIt bool) bool {
    ret, _, err := blockinput.Call(uintptr(BoolToBOOL(fBlockIt)))
    if err != nil {
        fmt.Println("BlockInput error:", err)
    }
    return ret != 0
}

func main() {
    fmt.Println("Enabling...")
    blockInput(true)
    fmt.Println("Enabled. Try typing or using the mouse. Press Ctrl+Shift+L to unlock.")

    for {
        ctrlPressed := w32.GetAsyncKeyState(w32.VK_CONTROL) & 0x8000 != 0
        shiftPressed := w32.GetAsyncKeyState(w32.VK_SHIFT) & 0x8000 != 0
        lPressed := w32.GetAsyncKeyState('L') & 0x8000 != 0

        if ctrlPressed && shiftPressed && lPressed {
            fmt.Println("Ctrl+Shift+L pressed. Exiting...")
            blockInput(false)
            break
        }

        time.Sleep(120 * time.Second)
        
    }
}

r/StackoverReddit • • Jun 23 '24

Question Looking to collaborate on a trading terminal

2 Upvotes

Hi, i freshly started to work on a trading terminal which can enable trading across multiple exchanges from the same interface, working on a fastapi backend at the moment and would like to have collaboration/coding partners


r/StackoverReddit • • Jul 25 '24

Question Fetching from a DB

2 Upvotes

I’m looking for a method or tutorial to allow fetching of data either from a database or google sheets.

The premise is that the data is text only, for example sports results, simple housing information.

The front end is just a basic search bar that can query and pull info out of the DB and display it.


r/StackoverReddit • • Jun 16 '24

Question Need some help with debugging

2 Upvotes
import cupy as cp

distance_kernel_code = '''
extern "C" __global__
void calculate_distances(const int* matrix1, const int* path, int* distances, int* city1_vals, int* city2_vals, int* indices, int* ID, int n) {
    int idx = blockIdx.x * blockDim.x + threadIdx.x;
    if (idx < n - 1) {
        int city1 = path[idx];
        int city2 = path[idx + 1];
        ID[idx] = idx;
        city1_vals[idx] = city1;
        city2_vals[idx] = city2;
        int matrix_index = city1 * n + city2;
        indices[idx] = matrix_index;
        distances[idx] = matrix1[matrix_index];
    }
}
'''

distance_module = cp.RawModule(code=distance_kernel_code)
calculate_distances_kernel = distance_module.get_function('calculate_distances')

def randomMatrix(size, maxDistance):
    matrix = cp.triu(cp.random.randint(1, maxDistance + 1, size=(size, size)), k=1)
    matrix = matrix + matrix.T
    return matrix

def calculate_distance(route, distance_matrix, n):
    route = cp.asarray(route, dtype=cp.int32)
    distances = cp.empty(route.size - 1, dtype=cp.int32)
    city1_vals = cp.empty(route.size - 1, dtype=cp.int32)
    city2_vals = cp.empty(route.size - 1, dtype=cp.int32)
    indices = cp.empty(route.size - 1, dtype=cp.int32)
    ID = cp.empty(route.size - 1, dtype=cp.int32)

    block_size = 256 
    grid_size = (route.size - 1 + block_size - 1) // block_size

    stream = cp.cuda.Stream()
    with stream:
        calculate_distances_kernel((grid_size,), (block_size,), (distance_matrix, route, distances, city1_vals, city2_vals, indices,ID, n))
        stream.synchronize()

    print("Route:", route)
    print("City1 Values:", city1_vals.get())
    print("City2 Values:", city2_vals.get())
    print("Indices:", indices.get())
    print("Intermediate Distances:", distances.get())
    print("ID",ID)
    total_distance = cp.sum(distances).get()
    return total_distance

n = 4
Separation = 100
matrix = randomMatrix(n, Separation)
flattened_matrix = matrix.flatten()
print("Matrix:\n", matrix)
print("Flattened Matrix:\n", flattened_matrix)

initial_temp = 10000
cooling_rate = 0.95
iterations = 9000

current_route = cp.asarray([0, 1, 2, 3], dtype=cp.int32)
total_distance = calculate_distance(current_route, flattened_matrix, n)
print("Total Distance:", total_distance)
print("Current Route:", current_route)

Output

Matrix:
 [[ 0  4 57 84]
 [ 4  0 89 30]
 [57 89  0 80]
 [84 30 80  0]]
Flattened Matrix:
 [ 0  4 57 84  4  0 89 30 57 89  0 80 84 30 80  0]
Route: [0 1 2 3]
City1 Values: [0 1 2]
City2 Values: [1 2 3]
Indices: [ 1  6 11]
Intermediate Distances: [ 0 84  0]
ID [0 1 2]
Total Distance: 84
Current Route: [0 1 2 3]

Intermediate Distances are wrong and I can't figure out why


r/StackoverReddit • • Jul 06 '24

C++ How do you compile/build FFmpeg source code from git repo using vscode

2 Upvotes

Hello everyone. I downloaded the source code of FFmpeg, and I know that you have to build it but there are no step-by-step guides on how to do it using vscode. Could someone point me in the right direction thanks!


r/StackoverReddit • • Jun 17 '24

C++ Kattis safe secret problem: Handling very large sets of possible input combinations

2 Upvotes

Here is my current solution: https://www.online-cpp.com/brSt5zxDqT

Here is the kattis problem: https://www.online-cpp.com/brSt5zxDqT

I've sped up my solution and I think it seems to be fast enough, but it is sometimes giving the wrong answer. If you could help me out in solving this coding problem I would really appreciate it. Maybe you notice me making some silly mistake or you notice some bad coding practice, or maybe you find my bug! But any help would be appreciated.

Thanks!


r/StackoverReddit • • Aug 03 '24

Python Value error (pls help)

2 Upvotes

I am coding for a document with multiple graphs on it, so lots of coding for x and y axis's, I don't know why but I am getting an error, 'x and y must have same first dimension, but have shapes (539,) and (544,)', now I know this is something to do with the number of x's matching the number of y's but I don't know how to resolve this issue, any help would be greatly appreciated.


r/StackoverReddit • • Jul 05 '24

Python Adding a polkit policy to a python GTK app, what am I missing ?

2 Upvotes

Hi everyone, I'm currently making my first python+GTK4 and I need to use some pkexec command for having root permission for stuffs like dnf install, dnf list, ecc.

I'm posting because I'm trying from a few days to make the user insert the admin password just one time instead to have to do that for every command. So I maked a test python app trying to achieve it. My goal is to have a smooth and simple user experience like Gparted or Input Remapper.

I created my Polkit policy file and I place it the right place /usr/share/polkit-1/actions/ and the policy is the following with the name "com.prova.setup.app.policy" :

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE policyconfig PUBLIC
        "-//freedesktop//DTD PolicyKit Policy Configuration 1.0//EN"
        "http://www.freedesktop.org/standards/PolicyKit/1/policyconfig.dtd"
        >
<policyconfig>
    <action id="com.prova.setup.app">
        <description>Run Input Remapper as root</description>
        <message>SE MI LEGGI VUOL DIRE CHE FUNZIONA !</message>

        <defaults>
            <allow_any>no</allow_any>
            <allow_inactive>auth_admin_keep</allow_inactive>
            <allow_active>auth_admin_keep</allow_active>
        </defaults>
        <annotate key="org.freedesktop.policykit.exec.path">/usr/bin/python</annotate>
        <annotate key="org.freedesktop.policykit.exec.argv1">/usr/bin/prova-setup</annotate>
        <annotate key="org.freedesktop.policykit.exec.allow_gui">true</annotate>

</policyconfig>

This is the spec file I made to build it as an RPM to install on the Fedora system (the true program will only be for Fedora) is the following :

Name:           prova-setup
Version:        0.1
Release:        1%{?dist}
Summary:        A simple Python project

License:        MIT
URL:            https://example.com/simple_project
Source0:        %{name}-%{version}.tar.gz

BuildArch:      noarch

BuildRequires:  python3-devel
BuildRequires:  python3-setuptools
BuildRequires:   gtk4-devel
BuildRequires:   libadwaita-devel

Requires:       python3
Requires:       gtk4
Requires:       libadwaita

%description
This is a simple Python project to demonstrate RPM packaging.

%prep
%setup

%build
%py3_build

%install
%py3_install

install -Dm644 desktop/prova-setup.desktop %{buildroot}%{_datadir}/applications/prova-setup.desktop
install -Dm644 desktop/prova-setup.svg %{buildroot}%{_datadir}/icons/hicolor/scalable/apps/prova-setup.svg
install -Dm644 desktop/prova-setup.policy %{buildroot}%{_datadir}/polkit-1/actions/prova-setup.policy

mkdir -p %{buildroot}%{_datadir}/prova-setup
cp -r  data/* %{buildroot}%{_datadir}/prova-setup/



%files
%doc README.md
%{_bindir}/prova-setup
%{python3_sitelib}/prova_setup*

%{_datadir}/applications/prova-setup.desktop
%{_datadir}/icons/hicolor/scalable/apps/prova-setup.svg
%{_datadir}/polkit-1/actions/prova-setup.policy
%{_datadir}/prova-setup/*


%post
update-desktop-database &> /dev/null || :

%changelog
* Thu Jul 01 2024 Developer <[email protected]> - 0.1-1
- Initial package

The dummy python app I wrote to learn how polkit and pkexec work is the following :

# IMPORTAZIONE DEI MODULI
import sys, gi, subprocess, time, os

# RICHIESTA DELLE VERSIONI DI GTK ED ADWAITA
gi.require_version('Gtk', '4.0')
gi.require_version('Adw', '1')

# IMPORTO I MODULI GTK E ADWAITA
from gi.repository import Gtk, Adw, Gdk

print("sto funzionando")

# DEFINISCO LA SOTTO-CLASSE CHE RAPPRESENTA LA FINESTRA PRINCIPALE
class contenuto_finestra_principale(Gtk.ApplicationWindow):

    # IMPORTO GLI ATTRIBUTI E METODI DELLA CLASSE MADRE GTK.APPLICATIONWINDOW
    # UTILIZZANDO LA FUNZIONE INIT E LA SUPERCLASSE
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        
        # DEFINISCO LE DIMENSIONI DELLA FINESTRA ALL'AVVIO
        self.set_default_size(800,600)

        # DEFINISCO IL TITOLO DELLA FINESTRA
        self.set_title("Primo programma in GTK")

        # CREO IL BOX PRINCIPALE ALL'INTERNO DELLA FINESTRA
        # EGUAGLIANDO UN ATTRIBUTO DELLA CLASSE ALLA FUNZIONE CHE
        # GENERA IL WIDGET NELLA LIBRERIA GTK
        self.box_principale = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)

        # ASSEGNO IL BOX PRINCIPALE ALLA FINESTRA
        self.set_child(self.box_principale)

        # CREO IL PRIMO BOX INTERNO AL BOX PRINCIPALE
        self.box_1 = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)

        # ASSEGNO IL BOX_ ALLA FINESTRA
        self.box_principale.append(self.box_1)

        # CREO IL SECONDO BOX INTERNO AL BOX PRINCIPALE
        self.box_2 = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)

        # ASSEGNO IL BOX_2 ALLA BOX PRINCIPALE
        self.box_principale.append(self.box_2)

        # CREO IL BOTTONE 2
        self.bottone_principale = Gtk.Button(label="CLICCAMI")

        # ASSEGNO IL BOTTONE PRINCIPALE AL BOX 1
        self.box_1.append(self.bottone_principale)

        # ASSEGNO UNA FUNZIONE AL BOTTONE
        self.bottone_principale.connect('clicked', self.funzione_bottone_principale)

        # CREO IL CONTENITORE DELL'INTERRUTTORE DI PROVA
        self.box_interruttore_prova = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
        self.box_interruttore_prova.set_spacing(5)

        # ASSEGNO IL BOX INTERRUTTORE DI PROVA AL BOX PRINCIPALE
        self.box_2.append(self.box_interruttore_prova)

        # CREO UN INTERRUTTORE DI PROVA
        self.interuttore_prova = Gtk.Switch()

        # ASSEGNO L'INTERRUTTORE AL BOX INTERRUTTORE DI PROVA
        self.box_interruttore_prova.append(self.interuttore_prova)

        # CREO LA TARGHETTA DI TESTO DELL'INTERRUTTORE DI PROVA
        self.tag_interruttore_prova = Gtk.Label(label="Un interruttore")


        # ASSEGNO LA TARGHETTA DI TESTO AL BOX DELL'INTERRUTTORE DI PROVA
        self.box_interruttore_prova.append(self.tag_interruttore_prova)



    # DEFINISCO LA FUNZIONE DEL BOTTONE PRINCIPALE 
    def funzione_bottone_principale(self, bottone_principale):
       
       test()



# DEFINISCO LA SOTTO-CLASSE CHE PERMETTE LA CREAZIONE E MESSA SCHERMO DELLA FINESTRA PRINCIPALE
class genera_finestra_principale(Adw.Application):

    # IMPORTO GLI ATTRIBUTI E METODI DELLA CLASSE MADRE ADW.APPLICATION
    # UTILIZZANDO LA FUNZIONE INIT E LA SUPERCLASSE
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        # VIENE RICHIAMATA LA FUNZIONE "CONNECT" UTILIZZANDO COME PARAMETRI "ACTIVATE"
        # E LA FUNZIONE DI GENERAZIONE DELLA FINESTRA PRINCIPALE 
        self.connect('activate', self.attivazione_finestra_principale)



    # DEFINISCO LA FUNZIONE / METODO DELLA CLASSE PER GENERARE LA FINESTRA PRINCIPALE
    def attivazione_finestra_principale(self, finestra):

        # CREAZIONE DELLA FINESTRA PRINCIPALE
        self.finestra_principale = contenuto_finestra_principale(application=finestra)

        # MANDO A SCHERMO LA FINESTRA CON LA FUNZIONE "PRESENT"
        self.finestra_principale.present()


def test():

    # LETTURA DELLA LISTA DELLE LIBRERIE INSTALLATE
    # READING INSTALLED LIBRARY LIST
    library_list_output = subprocess.Popen("pkexec dnf list installed | grep lib", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
    
    library_list, library_list_err = library_list_output.communicate()   
    print(library_list)

    update_list_output = subprocess.Popen(f"pkexec dnf update", shell=True,  stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
    update_list, update_list_err =update_list_output.communicate()
    print(update_list)


def main():
    
    # DEFINIZIONE DELL'ID DEL PROGRAMMA E DELLA VARIABILE CHE RAPPRESENTA LA FINESTRA DEL PROGRAMMA
    finestra = genera_finestra_principale(application_id="com.prova.setup.app")

    # AVVIO DELLA FINESTRA PRINCIPALE
    finestra.run(sys.argv)
    input("Premi un tasto qualunque per uscire ")

if __name__ == "__main__":
    main()
    input("Premi un tasto qualunque per uscire ")

The setup.py file is the following :

from setuptools import setup, find_packages

setup(
    name="prova-setup",
    version="0.1",
    packages=['prova_setup'],
    
    entry_points={
        "console_scripts": [
            "prova-setup=prova_setup.main:main",
        ],
    },
)

And here we go with the last piece, the .deskop file :

[Desktop Entry]
Type=Application
Version=0.1
Name=Prova di Setup.py
Comment=Una semplice ed umile descrizione
Exec=prova-setup
Icon=prova-setup.svg
Terminal=true
Type=Application
Categories=Utility;

Please help figure out what I'am doing wrong, this is the only way to finish my first (FOSS) app. Thank you all for reading and sorry for the bad english but I'm not a native speaker. :)


r/StackoverReddit • • Aug 02 '24

Question Hey! Advice needed (automation of document reviews)

2 Upvotes

Hey all, wanna say thanks in advance for the read. CONTEXT: There is an internship project I am working on, that basically consists of checking translated documents. The documents provided for translation, are the original language doc, and the english doc. I was also given multiple documents - regulatory docs, a "check-list" , a glossary for industry-specific words/ abbreviations. - Essentially, the docs I should look at when reviewing the translated document (while also comparing it to the original language doc) MAIN QUESTION: Is there a way to automate this process of reviewing the translation? One document has up to 120 pages, and its just not effective, time-wise. Im perfectly fine with the process being sped up, if not automated to the full extent. Thank you for any and all feedback.


r/StackoverReddit • • Jul 08 '24

Question Is there a way to get fetch public events based on location?

2 Upvotes

Hi, I'm new to this and tried looking everywhere, but I cannot get a clear-cut answer. Is it possible to fetch public events based on location using Facebook API? I am trying to build an app that shows events based on the user's location.

Any help and guidance would be appreciated!


r/StackoverReddit • • Jul 17 '24

C++ Is there a way to run vcpkg without visual studio on windows?

2 Upvotes

I don't like the Visual Studio editor, so I installed MSVC via PortableBuildTools. For package management, I installed vcpkg, but every time I try to install a package, this error message appears:

-- Running vcpkg install
Fetching registry information from https://github.com/microsoft/vcpkg (HEAD)...
error: in triplet x64-windows: Unable to find a valid Visual Studio instance
Could not locate a complete Visual Studio instance

-- Running vcpkg install - failed
CMake Error at %VCPKG_ROOT%/scripts/buildsystems/vcpkg.cmake:902 (message):
  vcpkg install failed.  See logs for more information:
  .\build\vcpkg-manifest-install.log

The message is not exactly the same because I shortened paths for where vcpkg is installed and the location of the log file. Everything else is the same. Vcpkg is installed from the official repo, and PortabeBuildTools just installs proper MSVC in a custom location.

OK, I found out why I didn't notice that the Visual Studio installer doesn't force you to install the IDE. You need to launch the executable and delete any instance of the ide or build tools (installed via the installer), and the build tools don't appear on the available tab.


r/StackoverReddit • • Jun 16 '24

I got banned, what do now?

2 Upvotes

Apparently many people disliked my post to which i took it down. Now im banned from posting but SO is telling me to rephrase it in order to get unbanned. What do now? The post is gone...


r/StackoverReddit • • Jun 23 '24

Question Can someone recommend me a data science course

2 Upvotes

r/StackoverReddit • • Jul 09 '24

Javascript Building Science Simulations

2 Upvotes

Hello Everyone, i was recently hired as a Jr Technical Projects Engineer at an edtech company and one of the products underway requires integration of STEM simulations like the ones provided by https://phet.colorado.edu/ but custom made. I would like to know and get advice on which strategy or tools do i need to learn to be able to design and develop the animations.

Thank you