2021-10-31

I am struggling with c++ [closed]

I am doing this assignment but I am not sure if I am doing the right thing. See the questions below. And some of my solutions.

Scenario
A group of geologist are interested in a C++ application that is capable of accepting and processing data related to sites that they monitor across the island. A value between 1 and 10 (inclusively) is used to represent a geologist’s observation for an activity at a site. At minimum, each geologist will observe 10 sites for 10 days. Using an array, the minimum data for a geologist’s site could be represented as follow:

1 2 3 4 5 6 7 8 9 10
1 5 7 10 3 10 2 2 5 7 10
2 6 5 10 5 7 1 6 10 5 4
3 8 2 7 5 6 2 1 4 2 4
4 9 10 8 8 4 8 8 2 5 5
5 6 7 5 10 2 10 1 4 6 6
6 1 5 6 10 2 8 7 2 8 3
7 8 2 3 7 6 3 1 1 9 6
8 1 1 5 8 10 7 2 2 7 1
9 3 1 10 9 2 5 1 2 5 8
10 5 7 6 3 1 1 8 8 2 10
A

For example, at site 1 on day 1 (A11) and at site 9 on day 7 (A97), the values 5 and 1 are seen respectively – indicating the geologist’s rating for an activity at site 1 and site 9.

Tasks
You will implement a menu-driven C++ application that will model the following tasks to be accomplished by each geologist.

  • Create A. Upon the user selecting this option, your C++ application will create an integer pointer variable called A within your application’s main function. This pointer variable will be used to store the values representing a geologist’s observation for each site for each day. Your solution is required to call a function which accepts two integer values as its arguments, m and n, and returns a pointer to the newly created m by n integer array. You are to ensure that values for the minimum days and sites are validated before creating the m by n integer array. Note, the returned result of your function is expected to be assigned to A in your main function.
  • Populate A. Upon the user selecting this option, your main function will call another function to assist it in randomly assigning integer values to each location in A. You are to ensure that only valid values are generated and stored – as used by a geologist for recording their observations.
  • Scale A. Upon the user selecting this option, your main function will call another function to assist it in performing a scalar multiplication – this is to be done by multiplying all integer values in A with a user’s inputted integer value. Only values between 2 and 10 (inclusively) are to be accepted and used to perform this scalar multiplication.
  • Compute percentage. Upon the user selecting this option, your main function will display the highest and lowest values in A, and then create an n by 1 integer array called percentage. Your solution will then prompt the user to enter a value within the range of the highest and lowest displayed values. Next, for each site in A, your main function will compute and store the percentage of values that are greater than the user’s accepted value. Your solution will store the respective percentages obtained for each site in the array called percentage.
  • Exit program. Upon the user selecting this option, your main function will prompt the user to confirm their choice to exit your application. Only if the user confirms the choice to exit should your application close; otherwise, it repeats the menu options for your user.

Solutions



from Recent Questions - Stack Overflow https://ift.tt/3GEcpmX
https://ift.tt/eA8V8J

argument for 's' must be a bytes object in Python 3.8

Why am I getting the error argument for 's' must be a bytes object when trying to run the lambda function? I'm following the usage example but I'm getting this error. Any explanation to this issue and how to resolve it?

{
  "errorMessage": "Failed sending data.\nERROR: argument for 's' must be a bytes object",
  "errorType": "Exception",
  "stackTrace": [
    "  File \"/var/task/AlertMetricSender.py\", line 5, in lambda_handler\n    sender.send()\n",
    "  File \"/var/task/modules/ZabbixSender.py\", line 91, in send\n    self.__active_checks()\n",
    "  File \"/var/task/modules/ZabbixSender.py\", line 79, in __active_checks\n    response = self.__request(request)\n",
    "  File \"/var/task/modules/ZabbixSender.py\", line 59, in __request\n    raise Exception(\"Failed sending data.\\nERROR: %s\" % e)\n"
  ]
}

ZabbixSender.py:

#
# For sending metric value to zabbix server.
#
# You must create item as "zabbix trapper" on server.
# Because the server must be connected to agent:10050, if it is selected "zabbix agent".
#
# Usage:
#    from modules.ZabbixSender import ZabbixSender
#    ZABBIX_HOST = "zabbix.example.com"
#    ZABBIX_PORT = 10051
#    sender = ZabbixSender(ZABBIX_HOST, ZABBIX_PORT)
#    sender.add("example-hostname-01", "healthcheck", 1)
#    sender.add("example-hostname-01", "item.keyname", 0.123)
#    sender.add("example-hostname-02", "item.keyname", 1234)
#    sender.send()
#

import socket
import struct
import time
import json

class ZabbixSender:

    log = True

    def __init__(self, host='127.0.0.1', port=10051):
        self.address = (host, port)
        self.data    = []

    def __log(self, log):
        if self.log: print(log)

    def __connect(self):
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            self.sock.connect(self.address)
        except:
            raise Exception("Can't connect server.")

    def __close(self):
        self.sock.close()

    def __pack(self, request):
        string = json.dumps(request)
        header = struct.pack('<4sBQ', 'ZBXD', 1, len(string))
        return header + string

    def __unpack(self, response):
        header, version, length = struct.unpack('<4sBQ', response[:13])
        (data, ) = struct.unpack('<%ds'%length, response[13:13+length])
        return json.loads(data)

    def __request(self, request):
        self.__connect()
        try:
            self.sock.sendall(self.__pack(request))
        except Exception as e:
            raise Exception("Failed sending data.\nERROR: %s" % e)

        response = ''
        while True:
            data = self.sock.recv(4096)
            if not data:
                break
            response += data

        self.__close()
        return self.__unpack(response)

    def __active_checks(self):
        hosts = set()
        for d in self.data:
            hosts.add(d['host'])

        for h in hosts:
            request = {"request":"active checks", "host":h}
            self.__log("[active check] %s" % h)
            response = self.__request(request)
            if not response['response'] == 'success': self.__log("[host not found] %s" % h)

    def add(self, host, key, value, clock=None):
        if clock is None: clock = int(time.time())
        self.data.append({"host":host, "key":key, "value":value, "clock":clock})

    def send(self):
        if not self.data:
            self.__log("Not found sender data, end without sending.")
            return False

        self.__active_checks()
        request  = {"request":"sender data", "data":self.data}
        response = self.__request(request)
        result   = True if response['response'] == 'success' else False

        if result:
            for d in self.data:
                self.__log("[send data] %s" % d)
            self.__log("[send result] %s" % response['info'])
        else:
            raise Exception("Failed send data.")

        return result

if __name__ == '__main__':
    sender = ZabbixSender()
    sender.add("gedowfather-example-01", "healthcheck", 1)
    sender.add("gedowfather-example-01", "gedow.item", 1111)
    sender.send()

AlertMetricSender.py:

from modules.ZabbixSender import ZabbixSender
def lambda_handler(event, context):
    sender = ZabbixSender("10.10.10.10", 10051)
    sender.add("Zabbix server", "lambda.test", 5)
    sender.send()


from Recent Questions - Stack Overflow https://ift.tt/3mtRdb1
https://ift.tt/eA8V8J

Getting errors with opencv and mediapipe for making Hand Tracking Module in Python 3.7.9

I am getting the following error whenever I try to run my code, I am following a tutorial for hand tracking, I followed the steps correctly but I still to have some sort of error.

Link to Video: https://www.youtube.com/watch?v=01sAkU_NvOY&t=2100s

Traceback (most recent call last):
  File "C:/Users/aryan/Desktop/user/Study/Com_vis/Hand_T_M.py", line 56, in <module>
    main()
  File "C:/Users/aryan/Desktop/user/Study/Com_vis/Hand_T_M.py", line 41, in main
    detector = handDetector()
  File "C:/Users/aryan/Desktop/user/Study/Com_vis/Hand_T_M.py", line 12, in __init__
    self.detectionCon, self.trackCon)
  File "C:\Users\aryan\Desktop\user\Study\Com_vis\venv\lib\site-packages\mediapipe\python\solutions\hands.py", line 127, in __init__
    outputs=['multi_hand_landmarks', 'multi_handedness'])
  File "C:\Users\aryan\Desktop\user\Study\Com_vis\venv\lib\site-packages\mediapipe\python\solution_base.py", line 260, in __init__
    for name, data in (side_inputs or {}).items()
  File "C:\Users\aryan\Desktop\user\Study\Com_vis\venv\lib\site-packages\mediapipe\python\solution_base.py", line 260, in <dictcomp>
    for name, data in (side_inputs or {}).items()
  File "C:\Users\aryan\Desktop\user\Study\Com_vis\venv\lib\site-packages\mediapipe\python\solution_base.py", line 513, in _make_packet
    return getattr(packet_creator, 'create_' + packet_data_type.value)(data)
TypeError: create_int(): incompatible function arguments. The following argument types are supported:
    1. (arg0: int) -> mediapipe.python._framework_bindings.packet.Packet

Invoked with: 0.5

Process finished with exit code 1

I am unable to figure out the problem with the code. I am running python 3.7.9, and here is my code.

Filename: Hand_T_M.py

import cv2
import mediapipe as mp
import time
class handDetector():
    def __init__(self, mode=False, maxHands=2, detectionCon=0.5, trackCon=0.5):
        self.mode = mode
        self.maxHands = maxHands
        self.detectionCon = detectionCon
        self.trackCon = trackCon
        self.mpHands = mp.solutions.hands
        self.hands = self.mpHands.Hands(self.mode, self.maxHands,
                                        self.detectionCon, self.trackCon)
        self.mpDraw = mp.solutions.drawing_utils
    def findHands(self, img, draw=True):
        imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        self.results = self.hands.process(imgRGB)
        # print(results.multi_hand_landmarks)
        if self.results.multi_hand_landmarks:
            for handLms in self.results.multi_hand_landmarks:
                if draw:
                    self.mpDraw.draw_landmarks(img, handLms,
                                               self.mpHands.HAND_CONNECTIONS)
        return img
    def findPosition(self, img, handNo=0, draw=True):
        lmList = []
        if self.results.multi_hand_landmarks:
            myHand = self.results.multi_hand_landmarks[handNo]
            for id, lm in enumerate(myHand.landmark):
                # print(id, lm)
                h, w, c = img.shape
                cx, cy = int(lm.x * w), int(lm.y * h)
                # print(id, cx, cy)
                lmList.append([id, cx, cy])
                if draw:
                    cv2.circle(img, (cx, cy), 15, (255, 0, 255), cv2.FILLED)
        return lmList
def main():
    pTime = 0
    cTime = 0
    cap = cv2.VideoCapture(0)
    detector = handDetector()
    while True:
        success, img = cap.read()
        img = detector.findHands(img)
        lmList = detector.findPosition(img)
        if len(lmList) != 0:
            print(lmList[4])
        cTime = time.time()
        fps = 1 / (cTime - pTime)
        pTime = cTime
        cv2.putText(img, str(int(fps)), (10, 70), cv2.FONT_HERSHEY_PLAIN, 3,
                    (255, 0, 255), 3)
        cv2.imshow("Image", img)
        cv2.waitKey(1)
if __name__ == "__main__":
    main()


from Recent Questions - Stack Overflow https://ift.tt/3bqpNwp
https://ift.tt/eA8V8J

Fetch more than 100,000 records in Redshift

I have a requirement to fetch more than 400,000 records from Redshift and export it to Excel. But in Redshift, maximum limit is 100,000. So I am unable to fetch records in one go to Excel.

Please help me with this, how I can do this.

Note:- I am using Aginity Workbench for Redshift Tool for querying data.

Thanks in Advance.



from Recent Questions - Stack Overflow https://ift.tt/3nIC19r
https://ift.tt/eA8V8J

PHP Problem : 8th and 9th entrance of the highway doesn't work

so i have a problem with my PHP code. It's simply the highway calculator, when you entrance in the highway, you receive a ticket with 4 numbers : the first two is the number of the entrance of the highway (0 to 9), and the last two is the vehicle (10 for motorbike, 11 for car and 12 for truck). When i enter the ticket 0711, i have this : Ticket highway. But when i enter the ticket 0811 or 0911, i have this : Ticket highway 2 and i don't know why please guys help me. (i'm very bad in english i'm french so i'm sorry if you don't understand anything).

This is my code :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        table{
        border-collapse: collapse;
        background-color:lightblue;
        }

        th, td{
        border: 1px solid black;
        padding: 10px;
        }

    </style>
</head>
<body>
<?php
        if (isset($_POST['ticket']))
        {
            $ticket=$_POST['ticket'];
            $xx=substr($ticket,0,-2);
            $yy=substr($ticket,2,4);

            if ($xx==00)
            {
                $km=200;
            }
            elseif ($xx==01)
            {
                $km=180;
            }
            elseif ($xx==02) 
            {
                $km=160;
            }
            elseif ($xx==03) 
            {
                $km=140;
            }
            elseif ($xx==04) 
            {
                $km=120;
            }
            elseif ($xx==05) 
            {
                $km=100;
            }
            elseif ($xx==06) 
            {
                $km=80;
            }
            elseif ($xx==07) 
            {
                $km=60;
            }
            elseif ($xx==08) 
            {
                $km=40;
            }
            elseif ($xx==09) 
            {
                $km=20;
            }

            if ($yy==10)
            {
                $prix=0.05*$km*0.5;
            }
            elseif ($yy==11)
            {
                $prix=0.05*$km*1;
            }
            elseif ($yy==12) 
            {
                $prix=0.05*$km*1.2; 
            }

            echo "type de véhicule : $yy<BR>";
        }
    ?>
    <table>
        <tr>
            <td>
                n° entrée de péage : 
            </td>
            <td>
                <?php echo $xx; ?>
            </td>
        </tr>
        <tr>
            <td>
                Kilomètres : 
            </td>
            <td>
                <?php echo "$km kms"; ?>
            </td>
        </tr>
        <tr>
            <td>
                Catégorie véhicule : 
            </td>
            <td>
                <?php 
                    if ($yy==10)
                    {
                        echo "Moto";
                    }
                    elseif ($yy==11) 
                    {
                        echo "Voiture";
                    }
                    elseif ($yy==12) 
                    {
                        echo "Camion";
                    }
                ?>
            </td>
        </tr>
        <tr>
            <td>
                Prix à payer : 
            </td>
            <td>
                <?php echo "$prix €"; ?>
            </td>
        </tr>
    </table>
</body>
</html>


from Recent Questions - Stack Overflow https://ift.tt/31ihgtK
https://ift.tt/eA8V8J

How to plot a time after conversion

I want to convert one column to time and then plot it. What I did is this:

df = pd.read_csv('vv.txt',sep=" ",names=list(["time", "size", "type"]))

df.time = df.time.apply(lambda X: "{0:02.0f}:{1:02.0f}".format(*divmod(float(X) * 60, 60)))

df["time"] = pd.to_datetime(df["time"], format='%H:%M' ).apply(pd.Timestamp)

df["time"] = df["time"].map(lambda x: x.strftime("%H:%M"))
plt.scatter(df['time'], df['size'])

and it shows this as a result, no X-axis is showing right. How can I solve this?

picture of the graph



from Recent Questions - Stack Overflow https://ift.tt/3vXLAVI
https://ift.tt/2Y3ecQY

Analise string see if vowels and 2 consecutive letters

how can i analise a string one by on, then see if it has 2 vowels (non-capital), and see if it as at least two consecutive letters of the alphabet (non-capital as well)

e.g.: aabcd is valid cdefgh not valid



from Recent Questions - Stack Overflow https://ift.tt/31gJ5Tf
https://ift.tt/eA8V8J

Number of restricted arrangements

I am looking for a faster way to solve this problem:

Let's suppose we have n boxes and n marbles (each of them has a different kind). Every box can contain only some kinds of marbles (It is shown it the example below), and only one marble fits inside one box. Please read the edits.

The question is: In how many ways can I put marbles inside the boxes in polynomial time?

Example:

n=3

Marbles: 2,5,3

Restrictions of the i-th box (i-th box can only contain those marbles): {5,2},{3,5,2},{3,2}

The answer: 3, because the possible positions of the marbles are: {5,2,3},{5,3,2},{2,5,3}

I have a solution which works in O(2^n), but it is too slow. There are also one limitation about the boxes tolerance, which I don't find very important, but I will write them also. Each box has it's own kind-restrictions, but there is one list of kinds which is accepted by all of them (in the example above this widely accepted kind is 2).

Edit: I have just found this question but I am not sure if it works in my case, and the dynamic solution is not well described. Could somebody clarify this? This question was answered 4 years ago, so I won't ask it there. https://math.stackexchange.com/questions/2145985/how-to-compute-number-of-combinations-with-placement-restrictions?rq=1

Edit#2: I also have to mention that excluding widely-accepted list the maximum size of the acceptance list of a box has 0 1 or 2 elements.



from Recent Questions - Stack Overflow https://ift.tt/3mtm7QK
https://ift.tt/eA8V8J

Why is argument null not asignable to paramenter of type setStateAction in typescript?

I want to pass empty object as initial state for isAdmin, but it's not assignable.

const Admin = () => {
    const [isAdmin, setIsAdmin] = useState({});

    useEffect(() => {
        const user = getCurrentUser();
        if (user && user.role === 'admin') {
            setIsAdmin(user);
        } else {
            setIsAdmin(null);
        }
    }, []);


from Recent Questions - Stack Overflow https://ift.tt/2XYFbwU
https://ift.tt/eA8V8J

Parametrize a function with a variable. Then delete the variable

I would like to make the following code run:

mu = 5
rnorm2 <- function(N) rnorm(N, mean = mu, sd = 1)

And then be able to use the rnorm2 function regardless of the presence of the mu variable in the environment. In other words, set the value of the 'mean' argument with the "mu" value once and for all.

Is that possible ?



from Recent Questions - Stack Overflow https://ift.tt/3EpkHgm
https://ift.tt/eA8V8J

How to use Electron-Forge Typescript + webpack plugin with Electron-Builder

I have started the application with npx create-electron-app my-new-app --template=typescript-webpack. I want to use electron-builder because of the packaging options.

The application runs in development mode correctly thanks to webpack-dev-server. However, in the packaged application I get a white screen (Not receiving static files?) enter image description here

It's worth noting that when I open the packaged application and have the development server running in the background it WORKS. But when I end the terminal I start to see errors in the packaged app.

enter image description here

Here is my package.json

{
  "name": "@cloudapp",
  "productName": "@cloudapp",
  "version": "1.3.6",
  "author": {
    "name": "cloudapp"
  },
  "description": "cloudapp application description",
  "main": ".webpack/main",
  "scripts": {
    "start:app": "npm start",
    "start": "electron-forge start",
    "package": "electron-forge package",
    "make": "electron-forge make",
    "publish": "electron-forge publish",
    "lint": "eslint --ext .ts,.tsx .",
    "build-installer": "electron-builder",
  },
  "build": {
    "appId": "cloudapp",
    "win": {
      "target": [
        "nsis"
      ],
      "icon": "./src/images/cloudappLogo Icon.ico",
      "requestedExecutionLevel": "requireAdministrator"
    },
    "nsis": {
      "installerIcon": "./src/images/cloudappIcon.ico",
      "uninstallerIcon": "./src/images/cloudappLogo Icon.ico",
      "uninstallDisplayName": "cloudapp",
      "license": "license.txt",
      "oneClick": false,
      "allowToChangeInstallationDirectory": true
    }
  },
  "keywords": [],
  "license": "MIT",
  "config": {
    "forge": {
      "packagerConfig": {
        "name": "cloudapp"
      },
      "makers": [
        {
          "name": "@electron-forge/maker-squirrel",
          "platforms": [
            "win32"
          ],
          "config": {
            "name": "CloudReign",
            "setupIcon": "./src/images/cloudappLogo Icon.ico",
            "icon": "C:/Users/Ibrah/OneDrive/Desktop/cloudapp/solutions/app/src/images/cloudappLogo Icon.ico",
            "loadingGif": "./src/images/Spin-1s-200px.gif"
          }
        },
        {
          "name": "@electron-forge/maker-zip",
          "platforms": [
            "darwin"
          ]
        },
        {
          "name": "@electron-forge/maker-deb",
          "config": {}
        },
        {
          "name": "@electron-forge/maker-rpm",
          "config": {}
        }
      ],
      "plugins": [
        [
          "@electron-forge/plugin-webpack",
          {
            "mainConfig": "./webpack/webpack.main.config.js",
            "devContentSecurityPolicy": "default-src * self blob: data: gap:; style-src * self 'unsafe-inline' blob: data: gap:; script-src * 'self' 'unsafe-eval' 'unsafe-inline' blob: data: gap:; object-src * 'self' blob: data: gap:; img-src * self 'unsafe-inline' blob: data: gap:; connect-src self * 'unsafe-inline' blob: data: gap:; frame-src * self blob: data: gap:;",
            "renderer": {
              "config": "./webpack/webpack.renderer.config.js",
              "entryPoints": [
                {
                  "html": "./public/index.html",
                  "js": "./src/index.tsx",
                  "name": "main_window",
                  "preload": {
                    "js": "./electron/bridge.ts"
                  }
                }
              ]
            }
          }
        ]
      ]
    }
  },

enter image description here



from Recent Questions - Stack Overflow https://ift.tt/2XYFaZS
https://ift.tt/3EsqYbh

How to spread evenly two view types with different sizes in RecyclerView?

I've added a new view type for the native ad view in my RecyclerView but I can't figure out how to spread the items evenly across the entire screen. After every 12th element, the new view type should be inserted.

This is what I want:

enter image description here

And this is what I get:

enter image description here

The result from the 2nd picture is achieved using this code:

gridLayoutManager = new GridLayoutManager(mActivity, 6);
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                switch (emotesAdapter.getItemViewType(position)) {
                    case AD_TYPE:
                        return gridLayoutManager.getSpanCount();
                    case CONTENT_TYPE:
                        return 1;
                    default:
                        return -1;
                }
            }
        });

        recyclerView.setLayoutManager(gridLayoutManager);

Any ideas?



from Recent Questions - Stack Overflow https://ift.tt/3GztSwL
https://ift.tt/3EmLvho

Why is JFrame methods not showing in autocomplete in Eclipse JAVA [duplicate]

issue in the picture method is working here

So when working with JFrame there are many methods, some show while other don't after the (.) for some reason but when physically typed out they do work. Very inconvenient for learning process. All autocomplete option in the setting are checked.

Images for reference. Sorry if the term "method" is not the correct one in this insistence.



from Recent Questions - Stack Overflow https://ift.tt/3Ek6TDR
https://ift.tt/eA8V8J

How to fix JFrame color problem on MacBook Pro? [closed]

Run-on Mac: Run on Mac

Run-on Window: Run on Window

How can I fix this problem? When I run Java Gui on my MacBook Pro, the label is invisible. But it runs fine on the window.



from Recent Questions - Stack Overflow https://ift.tt/3CjXPOS
https://ift.tt/eA8V8J

How payment api's can bill automatically?

Is there Mobile API for Android that have an option to charge clients automatically or in the end of the month? And also can handle wallet information? (I don't want to keep card information on my own server)

For example taxi apps that charges automatically in the end of ride (card information was entered before), or even Google Ads that charges in the end of the month.

Which payment services they are use?

enter image description here



from Recent Questions - Stack Overflow https://ift.tt/3mr6QQG
https://ift.tt/3Bzl8Tn

Accepting multiple user inputs in C

I am writing a program in C that accepts user input in either of these formats:

  1. string, int
  2. string, int, int or float

Some examples of valid inputs:

  1. Susan 5
  2. David 10 24
  3. Sarah 6 7.5

How do I accomplish this in C?

Here is the code I have so far:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>

int main()
{
    char name[10];
    int num1;
    int num2;

    if(scanf("%s %d", name, &num1) != 2 || scanf("%s %d %d", name, &num1, &num2) != 3)
    {
            printf("Failure");
    }
    else
    {
        printf("Pass");
    }
}

This intends to print "Failure" if there is invalid user input and "Pass" if the user input is valid. The issue here is this code forces me to enter both formats in order to print "Pass." So if I input "Susan 5" I would have to input "David 10 24" in order to print "Pass" even though I have an or conditional and not an and conditional, which I don't understand. What I want is once I input "Susan 5" and hit enter, my program should be able to print "Pass."



from Recent Questions - Stack Overflow https://ift.tt/3vWGfhu
https://ift.tt/eA8V8J

pyspark - read csv with custom row delimiter

how can I read a csv file with custom row delimiter (\x03) using pyspark? I tried the following code but it did not work.

df = spark.read.option("lineSep","\x03").csv(path)
display(df)


from Recent Questions - Stack Overflow https://ift.tt/3jRYqzT
https://ift.tt/eA8V8J

How Do I Space Out the Labels on the Y axis in ggplot2?

I need to increase the spacing between my labels on the y-axis (see picture below). I have also included the code that I have used to make the plot in ggplot2.

Thanks for your help!

ggplot(who6, aes(total_cases, country))+geom_col(width = .25, position = position_dodge(width = 60*60*24))

enter image description here



from Recent Questions - Stack Overflow https://ift.tt/3bn57pf
https://ift.tt/2ZJuXkX

How to check if multiple records exists php mysql pdo

I am designing a school timetable and this is my first time. So I send multiple records for multiple classes from HTML to php.For instance teacher1 geography Monday Start 11:35 grade 7and then techer2 geography Monday Start 12:15 grade 4. If the data am sending times for same class same day or same teacher exists then the system should skip that and insert only that which does not exist. but now my code checks and if it finds one of the records exists , it does not proceed. I want it to process with the one which does not exist and ignore the one which exits. I need help and below is my code .

$usercode1 = "7892Hga";
$recieved_by = ($_SESSION['username']);
$errors = [];  // Array to hold validation errors
$data = [];   // array to pass back data
$teacherid = $_POST['teacherid'];
$subjectid = $_POST['subjectid'];
$locationid = $_POST['locationid'];
$start_time = $_POST['start_time'];
$end_time = $_POST['end_time'];
$courseid = $_POST['courseid'];
$dayid = $_POST['dayid'];
var_dump($teacherid);
/*Check if the record exits or techer was booked before 15-10-2021 21:00 Musa Capsicum */
foreach ($teacherid as $teacherid2) {
    foreach ($start_time as $start_time2) {
        foreach ($dayid as $dayid2) {
            foreach ($courseid as $courseid2) {
                // echeck if exist
                $check_exists = "SELECT 
    subject_timetable.teacherid,
    subject_timetable.subjectid,
    subject_timetable.locationid,
    subject_timetable.start_time,
    subject_timetable.end_time,
    subject_timetable.courseid
    FROM subject_timetable 
    WHERE subject_timetable.usercode = '$usercode'
    && subject_timetable.teacherid = '$teacherid2'
    && DATE_FORMAT(`start_time`, '%H:%i')= '$start_time2'
    && subject_timetable.dayid = '$dayid2'
    OR (
        subject_timetable.usercode = '$usercode' 
        && DATE_FORMAT(`start_time`, '%H:%i')= '$start_time2'
        && subject_timetable.courseid = '$courseid2'
        && subject_timetable.dayid = '$dayid2'
    )";
                $exist_check = $con->prepare($check_exists);
                $exist_check->execute();
                $counterRow = $exist_check->rowCount();
                if ($counterRow > 0) {
                    echo("$counterRow $usercode $teacherid2 We have this ");
                    exit();
                } else {
                    echo("$counterRow $usercode $teacherid2 No record Exists ");
                }
                while ($row_exist = $exist_check->fetch(PDO::FETCH_ASSOC)) {

                }
            }
        }
    }
}
//end  exist
?>
<?php
if (empty($teacherid)) {
    $errors['teacherid'] = 'Teacher is required.';
}
if (empty($_POST['subjectid'])) {
    $errors['subjectid'] = 'Subject for is required.';
}
if (empty($_POST['dayid'])) {
    $errors['dayid'] = 'Day for is required.';
}
//$date_start_time = date_create_from_format('Y-m-d',$start_time);
if (empty($_POST['start_time'])) {
    $errors['start_time'] = 'Start date required.';
}
//Check date  to
//$date_end_time = date_create_from_format('Y-m-d',$end_time);
if (empty($_POST['start_time'])) {
    $errors['start_time'] = 'End time required.';
}
if (!empty ($errors)) {
    // if there are items in our errors array, return those errors
    $data['success'] = false;
    $data['errors'] = $errors;
    exit();
} else {
    // if all is good process the form
    /////////
    $count = count($_POST['teacherid']);
    if (is_array($teacherid)
        && is_array($subjectid)
        && is_array($locationid)
        && is_array($start_time)
        && is_array($courseid)
        && is_array($dayid)
        && is_array($end_time)) {
        for ($i = 0; $i < $count; $i++) {
            $teacherid1 = $teacherid[$i];
            $subjectid1 = $subjectid[$i];
            $locationid1 = $locationid[$i];
            $start_time1 = $start_time[$i];
            $end_time1 = $end_time[$i];
            $dayid1 = $dayid[$i];
            $courseid1 = $courseid[$i];
            #########################################################
            $query = 'INSERT INTO subject_timetable(teacherid,subjectid,locationid,start_time,end_time,dayid,courseid,usercode)
    VALUES(:teacherid,:subjectid,:locationid,:start_time,:end_time,:dayid,:courseid,:usercode)';
            $insert = $con->prepare($query);
            $insert->execute([
                ':teacherid' => $teacherid1,
                ':subjectid' => $subjectid1,
                ':locationid' => $locationid1,
                ':start_time' => $start_time1,
                ':end_time' => $end_time1,
                ':dayid' => $dayid1,
                ':courseid' => $courseid1,
                ':usercode' => $usercode,
            ]);
            $data['success'] = true;
            $data['message'] = 'Success!';
        }
    }
}


from Recent Questions - Stack Overflow https://ift.tt/3Bt0lks
https://ift.tt/eA8V8J

How to return validation message using Enum class in spring boot?

I am not asking "how to validate enums".

Let's say I have request body like this one:

public class VerifyAccountRequest {
    
    @Email(message = "2")
    private String email;
}

What i am trying to do, instead of hardcoded way, i just want to return message's value from enum class. But IDEA is saying "Attribute value must be constant"

public enum MyEnum {
    EMAIL("2", "info"),
    public String messageCode;
    public String info;
}

public class VerifyAccountRequest {
    
    @Email(message = MyEnum.Email.code) // NOT_WORKING
    private String email;
}

I can also define "2" in the interface, but i don't want to do that:

public interface MyConstant {
    String EMAIL = "2";
}

public class VerifyAccountRequest {
    
    @Email(message = MyConstant.EMAIL) // WORKS, BUT I HAVE TO USE ENUM !!!
    private String email;
}

is it possible to return message value using enum class ?



from Recent Questions - Stack Overflow https://ift.tt/3pMGkTX
https://ift.tt/eA8V8J

2021-10-30

Ingress not binding to Load Balancer

I have my A record on Netlify mapped to my Load Balancer IP Address on Digital Ocean, and it's able to hit the nginx server, but I'm getting a 404 when trying to access any of the apps APIs. I noticed that the status of my Ingress doesn't show that it is bound to the Load Balancer.

enter image description here

Does anybody know what I am missing to get this setup?

Application Ingress:

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: d2d-server
spec:
  rules:
    - host: api.cloud.myhostname.com
      http:
        paths:
          - backend:
              service:
                name: d2d-server
                port:
                  number: 443
            path: /
            pathType: ImplementationSpecific

Application Service:

apiVersion: v1
kind: Service
metadata:
  name: d2d-server
spec:
  selector:
    app: d2d-server
  ports:
    - name: http-api
      protocol: TCP
      port: 443
      targetPort: 8080
  type: ClusterIP

Ingress Controller:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: ingress-nginx-controller
  namespace: ingress-nginx
  uid: fc64d9f6-a935-49b2-9d7a-b862f660a4ea
  resourceVersion: '257931'
  generation: 1
  creationTimestamp: '2021-10-22T05:31:26Z'
  labels:
    app.kubernetes.io/component: controller
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/managed-by: Helm
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/version: 1.0.4
    helm.sh/chart: ingress-nginx-4.0.6
  annotations:
    deployment.kubernetes.io/revision: '1'
spec:
  replicas: 1
  selector:
    matchLabels:
      app.kubernetes.io/component: controller
      app.kubernetes.io/instance: ingress-nginx
      app.kubernetes.io/name: ingress-nginx
  template:
    metadata:
      creationTimestamp: null
      labels:
        app.kubernetes.io/component: controller
        app.kubernetes.io/instance: ingress-nginx
        app.kubernetes.io/name: ingress-nginx
    spec:
      volumes:
        - name: webhook-cert
          secret:
            secretName: ingress-nginx-admission
            defaultMode: 420
      containers:
        - name: controller
          image: >-
            k8s.gcr.io/ingress-nginx/controller:v1.0.4@sha256:545cff00370f28363dad31e3b59a94ba377854d3a11f18988f5f9e56841ef9ef
          args:
            - /nginx-ingress-controller
            - '--publish-service=$(POD_NAMESPACE)/ingress-nginx-controller'
            - '--election-id=ingress-controller-leader'
            - '--controller-class=k8s.io/ingress-nginx'
            - '--configmap=$(POD_NAMESPACE)/ingress-nginx-controller'
            - '--validating-webhook=:8443'
            - '--validating-webhook-certificate=/usr/local/certificates/cert'
            - '--validating-webhook-key=/usr/local/certificates/key'
          ports:
            - name: http
              containerPort: 80
              protocol: TCP
            - name: https
              containerPort: 443
              protocol: TCP
            - name: webhook
              containerPort: 8443
              protocol: TCP
          env:
            - name: POD_NAME
              valueFrom:
                fieldRef:
                  apiVersion: v1
                  fieldPath: metadata.name
            - name: POD_NAMESPACE
              valueFrom:
                fieldRef:
                  apiVersion: v1
                  fieldPath: metadata.namespace
            - name: LD_PRELOAD
              value: /usr/local/lib/libmimalloc.so
          resources:
            requests:
              cpu: 100m
              memory: 90Mi
          volumeMounts:
            - name: webhook-cert
              readOnly: true
              mountPath: /usr/local/certificates/
          livenessProbe:
            httpGet:
              path: /healthz
              port: 10254
              scheme: HTTP
            initialDelaySeconds: 10
            timeoutSeconds: 1
            periodSeconds: 10
            successThreshold: 1
            failureThreshold: 5
          readinessProbe:
            httpGet:
              path: /healthz
              port: 10254
              scheme: HTTP
            initialDelaySeconds: 10
            timeoutSeconds: 1
            periodSeconds: 10
            successThreshold: 1
            failureThreshold: 3
          lifecycle:
            preStop:
              exec:
                command:
                  - /wait-shutdown
          terminationMessagePath: /dev/termination-log
          terminationMessagePolicy: File
          imagePullPolicy: IfNotPresent
          securityContext:
            capabilities:
              add:
                - NET_BIND_SERVICE
              drop:
                - ALL
            runAsUser: 101
            allowPrivilegeEscalation: true
      restartPolicy: Always
      terminationGracePeriodSeconds: 300
      dnsPolicy: ClusterFirst
      nodeSelector:
        kubernetes.io/os: linux
      serviceAccountName: ingress-nginx
      serviceAccount: ingress-nginx
      securityContext: {}
      schedulerName: default-scheduler
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxUnavailable: 25%
      maxSurge: 25%
  revisionHistoryLimit: 10
  progressDeadlineSeconds: 600

Load Balancer:

apiVersion: v1
kind: Service
metadata:
  name: ingress-nginx-controller
  namespace: ingress-nginx
  labels:
    app.kubernetes.io/component: controller
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/managed-by: Helm
    app.kubernetes.io/name: ingress-nginx
    app.kubernetes.io/version: 1.0.4
    helm.sh/chart: ingress-nginx-4.0.6
  annotations:
    kubernetes.digitalocean.com/load-balancer-id: b259b084-0ac7-441f-b818-53244fce0071
    service.beta.kubernetes.io/do-loadbalancer-enable-proxy-protocol: 'true'
    service.beta.kubernetes.io/do-loadbalancer-name: ingress-nginx
    service.beta.kubernetes.io/do-loadbalancer-protocol: https
status:
  loadBalancer:
    ingress:
      - ip: <IP_HIDDEN>
spec:
  ports:
    - name: http
      protocol: TCP
      appProtocol: http
      port: 80
      targetPort: http
      nodePort: 31661
    - name: https
      protocol: TCP
      appProtocol: https
      port: 443
      targetPort: https
      nodePort: 32761
  selector:
    app.kubernetes.io/component: controller
    app.kubernetes.io/instance: ingress-nginx
    app.kubernetes.io/name: ingress-nginx
  clusterIP: <IP_HIDDEN>
  clusterIPs:
    - <IP_HIDDEN>
  type: LoadBalancer
  sessionAffinity: None
  externalTrafficPolicy: Local
  healthCheckNodePort: 30477
  ipFamilies:
    - IPv4
  ipFamilyPolicy: SingleStack



from Recent Questions - Stack Overflow https://ift.tt/3jS4nge
https://ift.tt/2ZC0fde

check if there is such a directory

I want to check if there is such a directory in path C:\inetpub\wwwroot\Server/views/admin/files/session/starter/14 or not using async await:

So I wrote this:

const fs = require('fs');
const directoryExist = await fs.promises.access(directory);

But the code above doesn't move after the second line ?!!

How can I do such a simple task?



from Recent Questions - Stack Overflow https://ift.tt/31g5j7R
https://ift.tt/eA8V8J

RichEdit doesn't show pictures

I created a simple RTF-document in WordPad, here is the screenshot:

enter image description here

It seems, that all format things of RTF work properly except pictures, which replaced by empty string. Here is RichEdit screenshot:

enter image description here

I tried both .bmp and .png. I also tried different version of RichEdit libraries: Riched20.dll and Msftedit.dll. Inside my .rtf file there is a string {\*\generator Riched20 10.0.19041}, I suppose it's a library and SDK version and in Visual Studio I use the same.



from Recent Questions - Stack Overflow https://ift.tt/2ZBi1wV
https://ift.tt/3Cu0sO6

How to create left, right, and center frames with pack?

I have a left and right frame right now and tried creating a center frame but the problem is the left frame takes up more space and pushes the center frame to the right so any widgets I put in it aren't actually centered. Is there any way to make it work?

    self.leftside = ttk.Frame(self)
    self.leftside.pack(expand=True, fill=BOTH, side=LEFT, anchor=W)

    self.center = ttk.Frame(self)
    self.center.pack(expand=True, fill=BOTH, side=LEFT, anchor=CENTER)

    self.rightside = ttk.Frame(self)
    self.rightside.pack(expand=True, fill=BOTH, side=RIGHT, anchor=E)


from Recent Questions - Stack Overflow https://ift.tt/3BmIVpK
https://ift.tt/eA8V8J

How are before_script/afters_script executed in relation to the script commands?

I understand what the before_script does. It executes commands to run before a job's commands get executed.
But how does that actually work under the hood?

Is it one "entity" that runs all the commands defined in the before_script script and after_script in the same process?
Or are these being executed by different processes (subshells?) sequentially?

If for instance in the before_script a command is run that in a normal setting, running in the background, could last the duration of the script would that be killed once the scope of before_script is finished?



from Recent Questions - Stack Overflow https://ift.tt/2Y0ZolS
https://ift.tt/eA8V8J

Monaco Editor + Blockly: highlight new code [closed]

Is it possible, with Monaco editor, to hightlight new code injected in editor ? I see everywhere how to highlight lines, how to use diffEditor, but I want to highlight any modification, even a value, and not all the line where the modification occurs. I'm developping another tool helping newbies programm graphically microntrollers (https://github.com/BlocklyDuino/BlocklyDuino-v2), so any new block on workspace creates an event that parse all blocks, that translation in code and inject it in Monaco eitor. In older project, everything was created "manually" with HTML fields (https://code.kniwwelino.lu/ or https://ardublockly.embeddedlog.com/demo/index.html), comparaison of old and new code listening each new block on workspace.

I found something about modifying text edited (Monaco Editor: only show part of document), but I need something more precise, only each word and not all the line.

From https://jsfiddle.net/renatodc/s6fxedo2/, what is interecting is the modification and I tried to modify:

let didScrollChangeDisposable = editor.onDidScrollChange(function() {
    didScrollChangeDisposable.dispose();
    setTimeout(function() {
      $(".monaco-editor .view-lines > div").each(function(i) {
        if(linesToDisable.includes(i+1)) {
          $(this).css("background-color", "#FFFF00");
          //$(this).css("pointer-events","none");
        }
      });
    },1000);
  }); 

But all the line has background, how can I change it to have backgournd on text only?



from Recent Questions - Stack Overflow https://ift.tt/314JMyK
https://ift.tt/eA8V8J

Hibernate native query also gets JPA select

I have a two database tables, "A" and "B" with @OneToMany(mappedBy = "a") on a List<B> field in entity A, and a @ManyToOne on field B.a. I ran into the "N+1" problem when doing default queries on A, so I am trying a native query such as:

@Query(value="select * from A as a left join B as b " +
            "on a.ID = b.b ",
            nativeQuery=true)

This works in the sense that the data is mapped back to the entities as expected.

My problem is that I can see that Hibernate is doing a separate select for each B rather than using the results of the join. That is, I see in the console a sequence of:

  • The select that I specified
  • For each instance of A, another select for B using the ID from A

In other words, I've still got the "n+1" problem.

I figured that the @OneToMany and @ManyToOne annotations might be causing Hibernate to do these extra selects, but when I take them out, my IDE (IntelliJ) says:

'Basic' attribute should not be a container

... on the List property in A.

How can I get it to map the results back in a single select with join? Should I just give up on Hibernate and JPA?

I am using spring-boot-start-data-jpa.2.5.4



from Recent Questions - Stack Overflow https://ift.tt/3vUGn0N
https://ift.tt/eA8V8J

Lua code Editing Fortnite issues with MoveMouseRelative

MoveMouseRelative moves very fast but I noticed that when I make my mouse move up then right it often gets a shortcut. So I miss some squares when I edit. So instead of going up then right it seems to go across. I tried to add more sleep time in the movemouse or between two moves. In first case it moves too slowly and in the second it stills taking shortcuts.

This code is what is working the best (less worse), I make several up or down movements in order that smaller shortcuts are taken. But I'm sure it can be improved with a more simple code (less lines) and having à good drawing of the edit.

How can that be fixed please?

----------------
    -- Boutton 8 edit en rond ou du haut vers le bas mur ou escalier - MB8 round edit or up and down stair and wall             
    ----------------
    -- CapsLock OFF
    -- Edit en rond - Round edit
    
      if not IsKeyLockOn("capslock")then
            if (event == "MOUSE_BUTTON_PRESSED" and arg == 8) then
    
                        PressAndReleaseKey("BackSpace")-- Edit
                        FastSleep(5)
                        PressAndReleaseKey("T")-- Reset Edit
    
                if not IsMouseButtonPressed(3) then
    
                        --Regarder - Look
                            for i = 0, 20 do
                            MoveMouseRelative (0,127) -- bas - down
                           FastSleep(0.5)
                            end
                           FastSleep(5)
    
    
                        -- Dessiner Edit - Draw Edit
                            PressKey(13)-- Select Edit
    
                            for i = 0, 5 do
                            MoveMouseRelative (0,-127) -- haut - up
                           FastSleep(0.5)
                            end
                           FastSleep(5)
    
                            for i = 0, 5 do
                            MoveMouseRelative (0,-127) -- haut - up
                           FastSleep(0.5)
                            end
                           FastSleep(5)
    
                            for i = 0, 4 do
                            MoveMouseRelative (0,-127) -- haut - up
                           FastSleep(0.5)
                            end
                           FastSleep(5)
    
                            for i = 0, 4 do
                            MoveMouseRelative (0,-127) -- haut - up
                           FastSleep(0.5)
                            end
                           FastSleep(5)
    
                            for i = 0, 5 do
                            MoveMouseRelative (127,0) -- droite - right
                           FastSleep(0.5)
                            end
                           FastSleep(5)
    
                            for i = 0, 6 do
                            MoveMouseRelative (0,127) -- bas - down
                           FastSleep(0.5)
                            end
                           FastSleep(5)
    
                            for i = 0, 6 do
                            MoveMouseRelative (0,127) -- bas - down
                           FastSleep(0.5)
                            end
                           FastSleep(5)
    
                            for i = 0, 6 do
                            MoveMouseRelative (0,-127) -- haut - up
                           FastSleep(0.5)
                            end
                           FastSleep(5)
    
                            for i = 0, 5 do
                            MoveMouseRelative (-127,0) -- gauche- left
                           FastSleep(0.5)
                            end
                           FastSleep(5)
    
                            for i = 0, 5 do
                            MoveMouseRelative (-127,0) -- gauche - left
                           FastSleep(0.5)
                            end
                           FastSleep(5)
    
                            for i = 0, 6 do
                            MoveMouseRelative (0,127) -- bas - down
                           FastSleep(0.5)
                            end
                           FastSleep(5)
    
                            for i = 0, 6 do
                            MoveMouseRelative (0,-127) -- haut - up
                           FastSleep(0.5)
                            end
                           FastSleep(1)
    
                            for i = 0, 5 do
                            MoveMouseRelative (0,-127) -- haut - up
                           FastSleep(0.5)
                            end
                           FastSleep(5)
    
                            for i = 0, 5 do
                            MoveMouseRelative (127,0) -- droite- right
                           FastSleep(0.5)
                            end
                           FastSleep(5)
                end

(....)

 if event == "MOUSE_BUTTON_RELEASED" and arg == 8 then

                    FastSleep(1)
                    ReleaseKey(13)-- Select Edit
                    FastSleep(1)
                    PressAndReleaseKey("F1")
                    PressAndReleaseKey(7) -- Alterner les raccourcis - Switch Quickbar
                    end
    end
  end


from Recent Questions - Stack Overflow https://ift.tt/3Ev5aMc
https://ift.tt/eA8V8J

A component is changing the uncontrolled value state of Select to be controlled

I'm trying to create a edit form to edit data from database by id. I tried this:

    import React, {FormEvent, useEffect, useState} from "react";
    import TextField from "@material-ui/core/TextField";
    import { createStyles, makeStyles, Theme } from "@material-ui/core/styles";
    import {
      TicketFullDTO,
      TicketStatusTypesDTO,
    } from "../../service/support/types";
    import {
      getTicket,
      getTicketStatusTypes,
      updateTicket,
    } from "../../service/support";
    import { useHistory, useParams } from "react-router-dom";
    import InputLabel from "@mui/material/InputLabel";
    import Select from "@mui/material/Select";
    import MenuItem from "@mui/material/MenuItem";
    import { FormControl } from "@mui/material";
    import { Moment } from "moment";
    import { RouteParams } from "../../service/utils";
       
    export default function TicketProfile(props: any) {
      const classes = useStyles();
      let history = useHistory();
      let requestParams = useParams<RouteParams>();

      const [status, setStatus] = useState<string>("");
      const [submitDate, setSubmitDate] = useState<Moment | null>(null);
      const [ticket, setTicket] = useState<TicketFullDTO>();
    
      const formSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        console.log(e);

        updateTicket(requestParams.id, data)
          .then(({ data }) => {
            console.log(data.title);
            history.replace("/support");
          })
          .catch((err) => {
            console.log(err);
          });
      };
    
      const [ticketCategoriesList, setTicketCategoriesList] = useState<
        TicketCategoryTypesDTO[]
      >([]);
      const [ticket, setTicket] = useState<TicketFullDTO>();
            
      const getSingleTicket = async () => {
        getTicket(requestParams.id)
          .then(({ data }) => {
            setTicket(data);
          })
          .catch((error) => {
            console.error(error);
          });
      };
    
      const [ticketStatusList, setTicketStatusList] = useState<
        TicketStatusTypesDTO[]
      >([]);
    
      useEffect(() => {
        ticketStatusData();
        getSingleTicket();
      }, []);
    
      const ticketStatusData = async () => {
        getTicketStatusTypes()
          .then((resp) => {
            setTicketStatusList(resp.data);
          })
          .catch((error) => {
            console.error(error);
          });
      };
    
      return (
        <Container>
            <form onSubmit={onSubmit}>

                          .........

                          <TextField
                            value={ticket?.title}
                            id="title"                                             
                            onChange={({ target: { value } }) => {
                              setTicket({ ...ticket, title: value });
                            }}
                          />

                          .........

                          <FormControl>
                            <TextField
                              label="Submit Date"
                              id="submit-date"
                              type="date"
                              defaultValue={ticket?.submitDate}                             
                              //@ts-ignore
                              onInput={(e) => setSubmitDate(e.target.value)}
                            />
                          </FormControl>
                       
                          ..........

                            <Select
                              labelId="status-label"
                              id="status-helper"
                              value={ticket?.status}
                              onChange={(e) => setStatus(e.target.value)}
                              required
                            >
                              {ticketStatusList.map((element) => (
                                <MenuItem value={element.code}>
                                  {element.name}
                                </MenuItem>
                              ))}
                            </Select>
                          </FormControl>

                         ...........
                      
                          <Button
                            type="submit"
                          >
                            Update Ticket
                          </Button>                       
    
        </Container>
      );
    }


.....


export async function updateTicket(
    id: string,
    data: TicketFullDTO
): Promise<AxiosResponse<TicketFullDTO>> {
  return await axios.post<TicketFullDTO>(
      `${baseUrl}/management/support/tickets/ticket/${id}`,
      {
        data,
      }
  );
}

export interface TicketFullDTO {
    id?: number,
    title?: string,
    status?: string,
    submitDate?: Moment | null
}

I get error in Chrome console:

MUI: A component is changing the uncontrolled value state of Select to be controlled. Elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled Select element for the lifetime of the component. The nature of the state is determined during the first render. It's considered controlled if the value is not undefined.

The value for Select should be selected using the value ticket?.status when list ticketStatusList But the data object is not running before rendering the UI content and the value into Select dropdown is not selected.

Do you know how I can fix this issue?



from Recent Questions - Stack Overflow https://ift.tt/3GgO0Ue
https://ift.tt/eA8V8J

Unable to install pgAdmin 4 in ubuntu 21.10

I am facing some issues when I tried to install pgAdmin4 in the latest ubuntu version 21.10.

I have Installed the public key for the repository using following command

sudo curl https://www.pgadmin.org/static/packages_pgadmin_org.pub | sudo apt-key add

But when I tried to create the repository configuration file using the following command I am getting an error mentioned below.

sudo sh -c 'echo "deb https://ftp.postgresql.org/pub/pgadmin/pgadmin4/apt/$(lsb_release -cs) pgadmin4 main" > /etc/apt/sources.list.d/pgadmin4.list && apt update'

ERROR LOG

  404  Not Found [IP: 2604:1380:2000:7501::69 443]
Hit:11 http://us.archive.ubuntu.com/ubuntu impish-backports InRelease
Get:12 http://us.archive.ubuntu.com/ubuntu impish-updates/main amd64 DEP-11 Metadata [7,972 B]
Get:13 http://us.archive.ubuntu.com/ubuntu impish-updates/universe amd64 DEP-11 Metadata [2,008 B]
Reading package lists... Done       
E: The repository 'https://ftp.postgresql.org/pub/pgadmin/pgadmin4/apt/impish pgadmin4 Release' does not have a Release file.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.

Thank you.



from Recent Questions - Stack Overflow https://ift.tt/3bmeIfR
https://ift.tt/eA8V8J

Create array of objects from sorting another array of objects

I want to create an array of objects, and the first elements from the each data object to be a separate object, the second element from the each data object to be another separate object and so on...

let array = [{   
    data: {
       center1: "1",
       storage1: "1",
       system1: "1",
    }
  },
  {  
    data: {
       center2: "2",
       storage2: "2",
       system2: "2",
    }
  }
]

Expected result:

[
    { center1: "1",  center2: "2"},
    { storage1: "1",  storage2: "2"},
    { system1: "1",  system2: "2"}
]

And this is what I tried do to but is not working really well:)

 const rows = [];
 array.forEach((item, index) => {
      for (let key in item.data) {
          rows.push({index : key + ': ' + item.data[key]});
      }
 });

The output is this:

[
    {index : 'center1: 1'},
    {index : 'storage1: 1'},
    {index : 'system1: 1'},
    {index : 'center2: 2'},
    {index : 'storage2: 2'},
    {index : 'system2: 2'}
]

Thank you for your help!



from Recent Questions - Stack Overflow https://ift.tt/3BnlwUZ
https://ift.tt/eA8V8J

how to use input forms within iframes with Puppeteer?

I'm a little bit new to puppeteer and have been getting along with it quite well until I have encountered iframes and inputting data into them.

I'm trying to interact with an input named credit-card-number on the checkout.game.co.uk/payment page.

I have tried the following:

const iframe1 = await page.frames().find(frame => frame.src =="https://flex.cybersource.com/cybersource/assets/microform/0.4.0/iframe.html?keyId=03MksUg0hQKucIBmvTgEVkD7Vxh8h9S0");
await iframe1.type('input', '4111', { delay: 500 }); 

For credit card number, how can I input numbers into this box? Additionally, any feedback on how I can smarten up the code since I have been told to use functions but not sure how they all combine with puppeteer.

My Code:

const puppeteer = require('puppeteer');


(async () => {
  //go to page and add to cart
  const browser = await puppeteer.launch({ headless: false });
  const page = await browser.newPage();
  await page.goto('https://www.game.co.uk/en/dual-charging-station-for-xbox-series-x-s-white-2851669');
  await console.log('Users navigated to site :)');
  await page.waitForSelector('.cookiePolicy_inner--actions');
  await page.click('.cookiePolicy_inner--actions');
  await page.waitForSelector('.addToBasket');
  await page.click('.addToBasket');
  await page.waitForSelector('.secure-checkout');
  await page.click('.secure-checkout');
  await page.waitForSelector('.cta-large');
  await page.click('.cta-large');

  //start filling out basic details
  await page.goto('https://checkout.game.co.uk/contact');
  await page.waitForSelector('.mat-form-field-infix');
  await page.click('.mat-form-field-infix');
  //title
  await page.waitForSelector('#mat-option-0');
  await page.click('#mat-option-0');
  await page.waitForTimeout(1000);
  //first name
  var ele = await page.waitForXPath("//input[@placeholder='First Name']");
  await ele.type('jim');
  await page.waitForTimeout(1000);
  //lastname
  var ele2 = await page.waitForXPath("//input[@placeholder='Last Name']");
  await ele2.type('jim');
  await page.waitForTimeout(1000);
  //email
  var elemail = await page.waitForXPath("//input[@placeholder='Email']");
  await elemail.type('jim@gmail.com');
  await page.waitForTimeout(1000);
  //mobile number
  var elenumber = await page.waitForXPath("//input[@placeholder='Mobile Number']");
  await elenumber.type('07797818233', { delay: 200});
  await page.waitForTimeout(1000);
  //starts filling out adress
  await page.click('.mat-raised-button.mat-accent-cta');
  var manualadress = await page.waitForXPath("//a[@data-test='manual-address-link']");
  await manualadress.click();
  await page.waitForTimeout(1000);
  //Country
  var choosecountry = await page.waitForXPath("//mat-select[@placeholder='Choose a Country']");
  await choosecountry.click();
  await page.waitForSelector('#mat-option-6');
  await page.click('#mat-option-6');
  //address line 1
  var addline1 = await page.waitForXPath("//input[@placeholder='Address Line 1']");
  await addline1.type('40 close du ross');
  await page.waitForTimeout(1000);
  //address line 2
  var addline2 = await page.waitForXPath("//input[@placeholder='Address Line 2']");
  await addline2.type('Grande Voute');
  await page.waitForTimeout(1000);
  // Town/city
  var town = await page.waitForXPath("//input[@placeholder='Town / City']");
  await town.type('clamont');
  await page.waitForTimeout(1000);
  //County / State / Region
  var region = await page.waitForXPath("//input[@placeholder='County / State / Region']");
  await region.type('ci');
  await page.waitForTimeout(1000);
  //Postcode
  var postcode = await page.waitForXPath("//input[@placeholder='Postcode / ZIP']");
  await postcode.type('SE1 9SG');
  await page.waitForTimeout(1000);
  //button to next
  var addresscontinue = await page.waitForXPath("//button[@data-test='continue-button']");
  await addresscontinue.click();
  await page.waitForTimeout(1000);

  //Delivery options
  //Continue to payment, keep just this for Standard
  var dstandard = await page.waitForXPath("//button[@data-test='continue-to-payment']");
  await dstandard.click();
  await page.waitForTimeout(1000);

  //Card Details
  //Card Number
})();


from Recent Questions - Stack Overflow https://ift.tt/3mtlYx0
https://ift.tt/eA8V8J

Keras - MulOp type mismatch

I get the following error while trying to compile my keras model. I've researched stackoverflow and the problem was posted several times. I tried the fixes suggested there, but nothing worked. Maybe someone can spot the problem.

TypeError: in user code:

C:\Users\User\Anaconda3\lib\site-packages\tensorflow\python\ops\gen_math_ops.py:6245 mul
"Mul", x=x, y=y, name=name)
C:\Users\User\Anaconda3\lib\site-packages\tensorflow\python\framework\op_def_library.py:558 _apply_op_helper
inferred_from[input_arg.type_attr]))

TypeError: Input 'y' of 'Mul' Op has type float32 that does not match type float64 of argument 'x'.

This is my code:

from tensorflow import keras
import numpy as np
import matplotlib.pyplot as plt

num_classes = len(label_encoder.classes_)

def make_model(input_shape):
    bias = tf.cast(np.log(pos/neg),tf.float64)
    output_bias = tf.keras.initializers.Constant(bias)
    
    input_layer = keras.layers.Input(input_shape)

    conv1 = keras.layers.Conv1D(filters=64, kernel_size=3, padding="same")(input_layer)
    conv1 = keras.layers.BatchNormalization()(conv1)
    conv1 = keras.layers.ReLU()(conv1)

    conv2 = keras.layers.Conv1D(filters=64, kernel_size=3, padding="same")(conv1)
    conv2 = keras.layers.BatchNormalization()(conv2)
    conv2 = keras.layers.ReLU()(conv2)

    conv3 = keras.layers.Conv1D(filters=64, kernel_size=3, padding="same")(conv2)
    conv3 = keras.layers.BatchNormalization()(conv3)
    conv3 = keras.layers.ReLU()(conv3)

    gap = keras.layers.GlobalAveragePooling1D()(conv3)

    output_layer = keras.layers.Dense(1, activation="sigmoid", bias_initializer=output_bias)(gap)

    return keras.models.Model(inputs=input_layer, outputs=output_layer)

model = make_model(input_shape=X_train.shape[1:])
epochs = 40
batch_size = 50

METRICS = [
      keras.metrics.TruePositives(name='tp'),
      keras.metrics.FalsePositives(name='fp'),
      keras.metrics.TrueNegatives(name='tn'),
      keras.metrics.FalseNegatives(name='fn'), 
      keras.metrics.BinaryAccuracy(name='accuracy'),
      keras.metrics.Precision(name='precision'),
      keras.metrics.Recall(name='recall'),
      keras.metrics.AUC(name='auc'),
      keras.metrics.AUC(name='prc', curve='PR'), # precision-recall curve
]

callbacks = [
    keras.callbacks.ModelCheckpoint(
        "best_model.h5", save_best_only=True, monitor="val_prc"
    ),
    keras.callbacks.ReduceLROnPlateau(
        monitor="val_prc", factor=0.5, patience=50, min_lr=0.0001
    ),
    keras.callbacks.EarlyStopping(monitor="val_prc", patience=20, verbose=1, restore_best_weights=True,mode="max"),
]
model.compile(
    optimizer="adam",
    loss="binary_crossentropy",
    metrics=METRICS,
)
history = model.fit(
    X_train,
    y_train,
    batch_size=batch_size,
    epochs=epochs,
    callbacks=callbacks,
    validation_split=0.2,
    verbose=1,
)

Also explicit type casting of the input data doesn't help:

X_train = tf.cast(X_train,tf.float64)
X_test = tf.cast(X_test,tf.float64)
y_train = tf.cast(y_train,tf.float64)
y_test = tf.cast(y_test,tf.float64)


from Recent Questions - Stack Overflow https://ift.tt/3Cu9BWY
https://ift.tt/eA8V8J

Oracle BETWEEN from subquery

Is something like this possible?

SELECT *
FROM [TABLE1]
WHERE [FIELDA] BETWEEN
    (SELECT [FIELDB], [FIELDC] 
     FROM [TABLE2]
     WHERE [set of conditions to ensure single record]);

Instead of doing:

SELECT *
FROM [TABLE1]
WHERE [FIELDA]
  BETWEEN (SELECT [FIELDB] FROM [TABLE2] WHERE [set of conditions to ensure single record])
  AND (SELECT [FIELDB] FROM [TABLE2] WHERE [set of conditions to ensure single record]);

Thanks,



from Recent Questions - Stack Overflow https://ift.tt/3BvTUNw
https://ift.tt/eA8V8J

Get DNS script has missing output in report

<# 
Gets the various dns record type for a domain or use -RecordType all for all and -Report to file output.
Use like .\get-dnsrecords.ps1 -Name Facebook -RecordType all or .\get-dnsrecords.ps1 -name facebook -RecordType MX
#>
param(
    [Parameter(Mandatory = $True,
        ValueFromPipelineByPropertyName = $True,
        HelpMessage = "Specifies the domain.")]
    [string]$Name,

    [Parameter(Mandatory = $False,
        HelpMessage = "Which Record.")]
    [ValidateSet('A', 'MX', 'TXT', 'All')]
    [string]$RecordType = 'txt',

    [Parameter(Mandatory = $false,
        HelpMessage = "DNS Server to use.")]
    [string]$Server = '8.8.8.8',
  
    [Parameter(Mandatory = $false,
        HelpMessage = "Make a csv report in c:\Reports")]
    [Switch]$Report
)

IF ($Name -notlike "*.*") {
    $Name = $Name + '.com'
}

If ($Report) {
    $filename = [environment]::getfolderpath("mydocuments") + '\' + $($RecordType) + '-' + ($Name.Split('.')[0]) + '.csv'
}

If ($RecordType -eq 'txt' -or $RecordType -eq 'All') {
    $TXTRecord = Resolve-DnsName $Name -Type txt -Server $Server -ErrorAction Stop | ForEach-Object {
        [PSCustomObject][ordered]@{
            name    = $_.name
            type    = $_.Type
            ttl     = $_.ttl
            section = $_.Section
            strings = ($_.strings | Out-String).trim()
        }
    }

    If ($RecordType -eq 'txt') {
        $TXTRecord
        If ($Report) {
            $TXTRecord | Export-Csv $filename -NoTypeInformation -Delimiter ','
        }
        $TXTRecord
        Return write-host $filename -ForegroundColor blue
    }
}

If ($RecordType -eq 'mx' -or $RecordType -eq 'All' ) {
    $MXRecord = Resolve-DnsName $Name -Type mx -Server $Server -ErrorAction Stop | ForEach-Object {
        [PSCustomObject]@{
            Name         = $_.name
            Type         = $_.type
            TTL          = $_.ttl
            Section      = $_.section
            NameExchange = $_.nameexchange
        }
    }

    If ($RecordType -eq 'MX') {
        If ($Report) {
            $MXRecord | Export-Csv $filename -NoTypeInformation
        }
        $MXRecord
        Return  Write-Host $filename -ForegroundColor blue
    }
}

If ($RecordType -eq 'a' -or $RecordType -eq 'All' ) {
    $ARecord = Resolve-DnsName $Name -Type A -Server $Server -ErrorAction Stop | ForEach-Object {
        [PSCustomObject]@{
            Name       = $_.name
            Type       = $_.type
            TTL        = $_.ttl
            Section    = $_.section
            IP4Address = $_.IP4Address
        }
    }

    If ($RecordType -eq 'a') {
        If ($Report) {
            $ARecord | Export-Csv $filename -NoTypeInformation
        }
        $ARecord
        Return write-host $filename -ForegroundColor blue
    }
}

If ($Report) {
    $TXTRecord | Export-Csv $filename -NoTypeInformation
    $MXRecord | Select-Object name, Type, ttyl, section, NameExchange | Export-Csv $filename -NoTypeInformation -Append -Force
    $ARecord | Select-Object name, Type, ttyl, section, IP4Address | Export-Csv $filename -NoTypeInformation -Append -Force
}
$TXTRecord
$MXRecord
$ARecord 
Return Write-Host $filename -ForegroundColor blue

Running .\get-dnsrecords.ps1 -Name Facebook -RecordType all -Report

Example report Output file is like the following and the host blast is ugly as well.

"name","type","ttl","section","strings"
"Facebook.com","TXT","3600","Answer","String"
"Facebook.com","TXT","3600","Answer","String"
"FaceBook.com","MX","21001","Answer",
"FaceBook.com","MX","21001","Answer",
"FaceBook.com","A","20","Answer",

Mx is missing NameExchange

A record is missing IP4Address

Ideas on how to make the report output include the missing items and bonus how to make the host output more readable ?

The problem is when I try to combine the output variables at the end and then export to file. I am just not sure how to correct it.



from Recent Questions - Stack Overflow https://ift.tt/3mraM3J
https://ift.tt/eA8V8J

YouTube API - how to fetch all playlists of a channel, even the ones who were added from other channels

I stumbled across this problem as I wanted to transfer all playlists (my own and those who I added from other channels) to another channel.

The code I use returns only my own playlists and not the ones I added to my channel from another channel.

I tested this behaviour in the target account which contains a private playlist I created and two playlists from another channel. The script I created uses oauth in order to 'see' my private playlist, but is not able to find the certainly public playlist from the other channel.

My code:

    request = youtube.playlists().list(
        part="snippet,contentDetails,status",
        channelId="UC_x5XG1OV2P6uZZ5FSM9Ttw",
        maxResults=25
    )

maxResults does not play a role here as I only have got all together three playlist on the test account. The playlist from another channel is clearly visible when I use the "Library" link and scroll down to "Playlists".

I would appreciate any hint to solve this 'mystery'. TIA!


This is how I added the playlist from the other channel:

  • go to the other channel
  • list the playlists
  • click on "VIEW THE FULL PLAYLIST"
  • click on the icon which looks like a sandwich combined with a plus sign (hovering on it gives 'save playlist')


from Recent Questions - Stack Overflow https://ift.tt/2XW6zvt
https://ift.tt/eA8V8J

How to make a syntax highlighter that highlights symbols

I wanted to make a syntax highlighter that highlights symbols. Look at the example:

function hello(){
  return "hello";
}

I want to highlight all the symbols:

{([</!&|\>])};.,:=+*-@$~_^?%'"

And I made a little one that highlighted strings. When I wanted to make one that highlights symbols I got confused. Now I want to know What topics should I learn to make it? Any example, github repo, tutorial, topic or ...? EDIT: I found the way to do that but I still have problem. My code is the following:

function syntaxue(){
  var codes = document.getElementsByClassName("syntaxue");
  for (var i=0; i < codes.length; i++){
    var data = codes[i].innerHTML;
    data = data.replace(/([^\w\s&;])/g, '<span class="sym">$1</span>');
    data = data.replace(/(&lt;)/g, '<span class="sym">$1</span>');
    data = data.replace(/(&gt;)/g, '<span class="sym">$1</span>');
    data = data.replace(/([\d])/g, '<span class="num">$1</span>');
    codes[i].innerHTML = data;
  }
}

When I want to highlight strings, the code becomes sth else.(Sorry I'm not English) And I was testing HTML markup I saw this:

&lt;html&gt;

Instead of this:

<html>

And the &; symbols were highlighted not their results. Can anyone help me?



from Recent Questions - Stack Overflow https://ift.tt/3mnCnD0
https://ift.tt/eA8V8J

Checking value of drop down is not in another drop down. Custom Validation using YUP

Im have 3 drop downs in a React Formik form, each with the same set of options. I want to provide some custom validation using YUP to ensure that each of these drop downs has a unique value selected.

The Formik values being set on each field take the shape of {id: somevalue, text: someText }

I have tried setting up my validation object as below:

const { values } = useFormikContext();

const validation = Yup.object({
    picker1: Yup.object()
        .test('test-name', 'Value must be Unique',
            function (value) {
                 return !((values["picker2"] && values["picker2"].id === value.id) ||
                (values["picker3"] && values["picker3"].id === value.id));
            }),
        ... repeat for other pickers
})

The problem I am having is that the formik value is always null for the pickers when the test function executes, presumably because the value of values is scoped to when the function is created. Is there a better way of attempting this as the documentation around custom validation in YUP seems a bit sparse.



from Recent Questions - Stack Overflow https://ift.tt/3jLYi5e
https://ift.tt/eA8V8J

Close collapse panel onClick - Ant Design Collapse

So make the panel close automatically after clicking on the button using onClick function. I found this useful post but I have no idea what went wrong after adding into my code.
Here's my custom collapse code in ./CustomCollapse.js:

const CustomCollapse = (props) => {
  const [open, setOpen] = useState(true);


  useEffect(() => {
    setOpen(props.isOpened)
  }, [props.isOpened])

  const setFun1= () => setDisabled(prev => !prev);
  const setFun2= () => () => setOpen(prev => !prev);

  const combineFunc = () =>{
    setFun1();
    setFun2();
  }
  

  return (
    <StyledCollapse activeKey={open} onChange={combineFunc()}>
      <AntCollapse.Panel
        header={props.header}
        key="1"
        showArrow={false}
        bordered={false}
        extra={
          <span>
            <span style=>
              {followed ? <div id={styles.emptyBox}><p>+10</p></div> : <img src={tickIcon} alt="" style= />}
              {disabled ? <div id={styles.themeBox}><p>+10</p></div> : <img src={arrowDownIcon} alt="" style= />}
            </span>
          </span>
        }
      >
      {props.children}
      </AntCollapse.Panel>
    </StyledCollapse>
  );
};

Here's where I want to change the state which is in ./FollowTelegram.js:

const [open, setOpen] = useState(["1"]);
const handleSubmit = () => {
    setOpen([]);
  }

//{...somecode}

  <AntCollapse isDisabled={disabledCollapse} isFollowed={followed} isOpened={open} id={styles.telegramHeader1} header="Follow XXX on Telegram Announcement Channel">
          <Row type='flex' align='middle' justify='center'>
            //Here's where I change the state
            <Button onClick={() => {setFollowed(); toggleDisabledCollapse(); handleSubmit();}} style={buttonStyle2} disabled={clicked}>Continue</Button> 
          </Row>
  </AntCollapse>


from Recent Questions - Stack Overflow https://ift.tt/31g1Whh
https://ift.tt/eA8V8J

How can I disable deletion of inline objects when using django-reverse-admin?

This is my ModelAdmin:

class ComputerAdmin(ReverseModelAdmin):
    list_display = ('employee', 'ip', 'mac', 'name', 'hardware')
    list_filter = ('employee__branch', )
    inline_type = 'tabular'
    inline_reverse = ['hardware', ]
    show_full_result_count = False

This is how it shows when adding a new computer:

Enter image description here

As you can see, I don't want to have the delete column and delete icon, because I have a foreign key so only one element is allowed. How can I do that?

Does django-reverse-admin have anything like has_delete_permisison for inlines only and not the whole ModelAdmin? I have already searched in documentation with no results, which is why I am posting here.

I updated my code as below:

class HardwareInline(admin.TabularInline):

    model = Hardware

    def has_delete_permission(self, request, obj=None):
        return False

class EmployeeAdmin(admin.ModelAdmin):

    list_display = ('group', 'branch', 'name')
    list_filter = ('group', )

class ComputerAdmin(ReverseModelAdmin):

    list_display = ('employee', 'ip', 'mac', 'name', 'hardware')
    list_filter = ('employee__group', 'employee__branch', )
    inline_type = 'tabular'
    inline_reverse = [ { 'field_name': 'hardware', 'admin_class': HardwareInline } ]

The delete column disappeared from inline, but I get a delete button under it:

Enter image description here



from Recent Questions - Stack Overflow https://ift.tt/3CubyCO
https://ift.tt/3nYmFOr

2021-10-29

Nested grouping in Mongodb

I am working on grouping the MongoDB documents and updating the sample in the below link

https://mongoplayground.net/p/c2s8KmavPBp

I am expecting the output to look like

[
  {
    "group" : "one",
      "details":[{
        "avgtime" : 9.359833333333333,
        "title": "Scence 1"
    },{
        "avgtime" : 9.359833333333333,
        "title": "Scence 2"
    },{
        "avgtime" : 9.359833333333333,
        "title": "Scence 3"
    }]
  },
  {
    "group" : "two",
      "details":[{
        "avgtime" : 9.359833333333333,
        "title": "Scence 1"
    }]
  }
  ]

How to rename the field _id to the group and merge the two elements containing title: scence 1 and display their average time

Note: Question and sample link updated



from Recent Questions - Stack Overflow https://ift.tt/3CpskD7
https://ift.tt/eA8V8J

unable to download the csv file in via rest api

I'm trying to download the CSV content file using the REST API in Codeigniter 4 but it not working, I'm fetching the data from the database which I need to download via rest API. In the controller I found this:

return $this->response->download('test.csv', $data); // $data is string

Front in angular:
const headers = new HttpHeaders().append('responseType', 'blob');
this.http.get(path, { headers }).subscribe(
  (res) => {},
  (error) => {console.error(error)}
);

But not working, am I missing something?

Please guide me.



from Recent Questions - Stack Overflow https://ift.tt/3Bp2zBi
https://ift.tt/eA8V8J

ISupportsErrorInfo.InterfaceSupportsErrorInfo(REFIID riid) implementation

I am a babysitter now overlooking a huge old-time (started in last century) code base for Windows, using C++ and C#, largely using COM as a glue.

I noticed that ISupportsErrorInfo::InterfaceSupportsErrorInfo() implementations (around 400 of them, wow) are just naive, exactly as here:

STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid)
{
    static const IID* arr[] =
    {
        &IID_IStore,
    };
    
    for (int i=0; i<sizeof(arr)/sizeof(arr[0]); i++)
    {
        if (InlineIsEqualGUID(*arr[i], riid))
            return S_OK;
    }
    
    return S_FALSE;
}

It looks to me that, once upon a time, someone (MVP, evangelist) has written a book about COM and then everybody later just copied these lines without thinking.

First of all, why do I need an array if I only have one item in it? Without an array, I don't need a for-loop.

To me, it looks like one line will be fine, eg.

return MyCoolHelper::InterfaceSupportsErrorInfo(riid, IID_IStore);

Maybe you have seen a decent implementation of it that supports 1 or more IID-s?



from Recent Questions - Stack Overflow https://ift.tt/3mqkoMm
https://ift.tt/eA8V8J

Is there a way in Flutter to scan a QR Code and also take a picture of the image?

Is there a way in Flutter to scan QR codes that enables you to take the picture of what is being scanned? How can this be implemented? The problem I am running into is whenever I successfully scan a QR Code and then try to take a picture with the camera of the phone, it is in use (by the QR Code library). If I then shut down the library and turn on the camera, there is a black screen, delay, and a refocusing of the camera. Terrible user experience.



from Recent Questions - Stack Overflow https://ift.tt/2ZtuqTJ
https://ift.tt/eA8V8J

Python: Get the first "encountered" duplicated character in a string

I am wondering if there is a more efficient way to resolve the following coding test:

Problem: Get the first duplicate char ENCOUNTERED in a string only if more than one dup char is detected, else return None'

Examples:

#1 'abbcdefa' = return 'b' because it is the first encountered string, while the duplicate 'a' appears much later than the duplicate 'b'

#2 'abcdefa' = None (because a is the only dup char in string)

def first_dup_char(A):
    seen, dups = [], []
    for i in A:
        if i in seen:
            dups.append(i)
        else:
            seen.append(i)
    # if dups list items > 1 then return the first dup else print None
    return dups[0] if len(dups) > 1 else 'None'

My solution above works by utiizing two lists. I wanted to use set() and dict, but unfortunately both of them are unordered, unless I miss something?



from Recent Questions - Stack Overflow https://ift.tt/3EwwzNT
https://ift.tt/eA8V8J

Can Project Loom be used from Kotlin?

I am just getting started at playing with Project Loom...

Given the Java code which seems to work correctly

try (ExecutorService executor = Executors.newVirtualThreadExecutor()) {
    IntStream.range(0, 16).forEach(i -> {
        System.out.println("i = " + i + ", Thread ID = " + Thread.currentThread());
        executor.submit(() -> {
            var thread = Thread.currentThread();
            System.out.println("Thread ID = " + thread);
        });
    });
}

When IntelliJ converts this to Kotlin I get

Executors.newVirtualThreadExecutor().use { executor ->
    IntStream.range(0, 16).forEach(IntConsumer { i: Int ->
        println("i = $i, Thread ID = ${Thread.currentThread()}")
        executor.submit(Runnable {
            println("Thread ID = ${Thread.currentThread()}")
        })
    })
}

private fun ExecutorService.use(block: (ExecutorService) -> Unit) {

which seems to compile fine, but when executed, nothing is printed on the console?

Is there some latent incompatibility between Kotlin and Project Loom?

Further experiments show that

Executors.newVirtualThreadExecutor()
    .submit(Runnable { println("Thread = ${Thread.currentThread()}") })

does not print anything, but

Executors.newCachedThreadPool()
    .submit(Runnable { println("Thread = ${Thread.currentThread()}") })

does print the expected result, so there is something fundamentally incompatible between Kotlin and Virtual Threads. However,

Executors.newCachedThreadPool().use { executor ->
    IntStream.range(0, 16).forEach(IntConsumer { i: Int ->
        println("i = $i, Thread ID = ${Thread.currentThread()}")
        executor.submit(Runnable {
            println("Thread ID = ${Thread.currentThread()}")
        })
    })
}

does not print anything, so there are other issues at play too... Indeed

Executors.newCachedThreadPool().use { executor ->
    IntStream.range(0, 16).forEach(IntConsumer { i: Int ->
        println("i = $i, Thread ID = ${Thread.currentThread()}")
    })
}

does not print anything, but

IntStream.range(0, 16).forEach(IntConsumer { i: Int ->
    println("i = $i, Thread ID = ${Thread.currentThread()}")
})

does print the expected results? Also,

IntStream.range(0, 16).forEach(IntConsumer { i: Int ->
    println("i = $i, Thread ID = ${Thread.currentThread()}")
    executor.submit(Runnable {
        println("Thread ID = ${Thread.currentThread()}")
    })
})

prints the expected results, so there is some weirdness with use?

This begs the questions

  1. Are there some problems with how Project Loom is designed/implemented that is causing problems for Kotlin?
    • Are there some problems with JDK-18 that is not compatible with Kotlin?
  2. Are there some problems with how Kotlin is designed/implemented that cannot interoperate with Project Loom?
    • Are there some problems with Kotlin, that are not compatible with JDK-18?


from Recent Questions - Stack Overflow https://ift.tt/2ZINMoe
https://ift.tt/eA8V8J

Batch script to monitor a service and automatically start the service if stopped. Need the output of to a logfile

Batch script to monitor a service and automatically start the service if stopped. Need to write the output of the net start command into a logfile. Executed the below script but failed to get the output into the log

net start | find /i "bits"
if "%errorlevel%"=="1" ( echo Service "Print Spooler" starting at %time% on %date% by Script 
%0>>C:\Users\DivyaBhargavMuddu\Desktop\ServiceRestart.Log
sc config "spooler" start=auto
FOR /F "tokens=*" %%F IN ('net start spooler ') DO ( Set var=%%F)
Set /P var =< "C:\Users\DivyaBhargavMuddu\Desktop\ServiceRestart.Log"
)


from Recent Questions - Stack Overflow https://ift.tt/3Gta3qO
https://ift.tt/eA8V8J

A question about using an improved convolutional neural network for sentiment classification

For the changes to CNN proposed in the paper "Detecting Dependency-Related Sentiment Features for Aspect-level Sentiment Classification": After extracting the features in the convolutional layer, the features are multiplied by the dependency weights proposed in the text to obtain the weighted features, and then input to the pooling Floor.

Dependency weighting is a real value that quantitatively measures the dependency-relatedness between a word and the aspect term in a sentence.

Dependency weighting of each word is calculated by inputting syntactic distance between it and the aspect term to some decreasing functions. The shortest path algorithms can calculate syntactic distances between all word pairs. On the dependency parse tree, words with smaller syntactic distance to the aspect term are more closely related than the other words. The dependency parse tree can be annotated manually according to dependency grammar or created automatically by parsers.

enter image description here

I would like to ask you, if I use a data set with aspect labels now, how do I write code to calculate the syntactic distance when I enter a sentence? That is how to apply this shortest path algorithm. (I have learned that one is to create a dependency parse tree first, and then use the shortest path algorithm. But I haven't figured out how to write code to create a dependency parse tree)



from Recent Questions - Stack Overflow https://ift.tt/3nEcaiX
https://ift.tt/3BoY0qR

Need to know exact geolocation where Google stores Cloud Storage content

Due to the nature of our business, we basically need to disclose where in the globe the files uploaded by our users are located.

In other words, we need the exact address where the data storage that keeps these files is located.

We're using Google Firebase's Cloud Storage and, even though they mention which city each location option refers to, we are unable to check the exact address.

The bucket that corresponds to our Google Cloud Storage is currently configured as: us (multiple regions in United States), which I suppose makes it even worse to pinpoint where the data resides. But that is an easy fix: we can simply start from scratch selecting a specific region as our storage location.

The main issue, however, is that, even if selecting a specific location, we can't really know the address where those files will be stored.

Has anyone ever come across something like this?

I tried getting support in my project's Google Cloud Platform, but apparently I need to purchase it. And I'm afraid that they won't be able to help me.

In case someone has contacted their support and got this answer, please let me know.



from Recent Questions - Stack Overflow https://ift.tt/2Zvkv0l
https://ift.tt/eA8V8J

Trying to change a button colour on CSS?

so I'm trying to add some additional CSS on Wordpress and override the colour of this form button but nothings happening. Am I entering the right code in here?

enter image description here]1

When I inspect the button this comes up..

<form id="mc4wp-form-1" class="mc4wp-form mc4wp-form-1527" method="post" data-id="1527" data-name="Get Started"><div class="mc4wp-form-fields"><div class="input-group">
  <div class="input-icon"><i class="far fa-paper-plane"></i></div>
    <input type="email" placeholder="Your email address" class="form-control" name="email" data-error="e-mail field is required" required="">
  <button type="submit" value="Subscribe" class="item-btn">Subscribe</button>
</div></div><label style="display: none !important;">Leave this field empty if you're human: <input type="text" name="_mc4wp_honeypot" value="" tabindex="-1" autocomplete="off"></label><input type="hidden" name="_mc4wp_timestamp" value="1635448917"><input type="hidden" name="_mc4wp_form_id" value="1527"><input type="hidden" name="_mc4wp_form_element_id" value="mc4wp-form-1"><div class="mc4wp-response"></div></form>

The reason why I've tried button.item-btn::before is because it shows this in the inspector

enter image description here



from Recent Questions - Stack Overflow https://ift.tt/3vS16m5
https://ift.tt/3BrC9Pv

Control/Customize Component name minification in Production React

Background

I often use "React Developer Tools" to understand the component structure of various website that I like and take inspiration from. Though, lot of websites have random names for the components, few websites have distinguishable names which can be helpful for aspiring React Developers or hobbyists. One such website is https://www.joshwcomeau.com. Below is a screenshot from one of the pages in his website. The name of few of the components explains itself what it is going to render. And since this is his blog, where he talks about various tips and tricks for React Development, it becomes helpful to have a look at this.

Question

Now when I develop a website using create-react-app(CRA), all my component names are minified to a couple of random letters by Webpack. How can I control this behavior?

Note: My main question is - How to control this behavior in any React application (not just CRA). I know that Josh uses Next.js for his blog, so does any framework like Gatsby, Next etc... provide control over this?.

Note: I'm aware that webpack can generate "sourcemap" but doing that would expose my entire code structure. So I prefer not to use sourcemaps

Screenshot of Josh's Website Screenshot of My Website
React Devtools from joshwcomeau.com React Devtools from my website


from Recent Questions - Stack Overflow https://ift.tt/3biihng
https://ift.tt/3mlKuzZ