c# – Need help with my risk game program – i need to insert 2 players, throw x number of dices, order them and confront the results of the 2 players

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

namespace ConsoleApp8
{
class Program
{
static List names;
static List dices; // (2, 3)
static List player1Dices = new List();
static List player2Dices = new List();

    static List<string> PromptNames()
    {
        Console.Write("Nome del primo giocatore: ");
        string player1 = Console.ReadLine();
        Console.Write("Nome del secondo giocatore: ");
        string player2 = Console.ReadLine();

        List<string> names = new List<string>();

        names.Add(player1);
        names.Add(player2);
        return names;
    }

    static int GetDieValue(string x, string msg)
    {
        Console.Write("{0}, {1} ", x, msg);
        string rawDie = Console.ReadLine();
        int parsedDie;
        // qui devi usare do, while perché non sai a priori quante volte un giocatore potrebbe inserire un valore sbagliato
        if (!Int32.TryParse(rawDie, out parsedDie))
        {
            Console.WriteLine("Meti un numero");
            return GetDieValue(x, msg);
        }
        return parsedDie;
    }

    static List<int> PromptDices()
    {
        int p1Dices = GetDieValue(names(0), "con quanti dadi vuoi attaccare?");
        int p2Dices = GetDieValue(names(1), "con quanti dadi ti vuoi difendere?");

        return new List<int>() { p1Dices, p2Dices };
    }
    static void Play()
    {
        Console.WriteLine("{0} attacca con {1} dadi", names(0), dices(0));
        Console.WriteLine("{0} difende con {1} dadi", names(1), dices(1));
        CalculateResult();

    }
    static void CalculateResult()
    {
        System.Random random = new System.Random();
        for (int i = 0; i <= dices.Count; i++)
        {
            player1Dices.Add(random.Next(1, 7));
        }
        Console.WriteLine("Prima: {0}{1}{2}", player1Dices(0), player1Dices(1), player1Dices(2));
        player1Dices = player1Dices.OrderByDescending(x => x).ToList();
        Console.WriteLine("Dopo: {0}{1}{2}", player1Dices(0), player1Dices(1), player1Dices(2));


        for (int i = 0; i <= dices.Count; i++)
        {
            player2Dices.Add(random.Next(1, 7));
        }
        Console.WriteLine("Prima: {0}{1}{2}", player2Dices(0), player2Dices(1), player2Dices(2));
        player2Dices = player2Dices.OrderByDescending(x => x).ToList();
        Console.WriteLine("Dopo: {0}{1}{2}", player2Dices(0), player2Dices(1), player2Dices(2));

    }
   
    private static void PlayAgain(string x)
    {
        Console.WriteLine("Se vuoi finire il gioco scrivi Exit");
        string Exit = x;
        do
        {
            RunGame();
            player1Dices.Clear();
            player2Dices.Clear();
        }
        while (x != Console.ReadLine());
        


    }

    static void RunGame()
    {
        names = PromptNames();
        dices = PromptDices();
        CalculateResult();
        Play();
        PlayAgain();
                
        // generate random numbers - and sort them
        // display results - compare dices
        // repeat or quit?
    }

    private static void PlayAgain()
    {
        throw new NotImplementedException();
    }

    static void Main(string() args)
    {
        RunGame();
        Console.WriteLine("Thanks for playing");
        Console.ReadKey();
    }
}

}

postgresql – Redshift – Insert data into a temp table with a condition being column doc_id should be unique and not null

I’m trying to create a temp table and insert data into it in Redshift, under one condition regarding one column (say doc_id which should be unique and not null)

Here’s my code:

-- Creating temp table to load only rows with unique and not null doc_id
DROP TABLE IF EXISTS TMP_table CASCADE;

CREATE TEMP TABLE IF NOT EXISTS TMP_table
(
    uuid varchar,
    id integer,
    doc_id integer,
    revenue double,
    doc_date varchar,
);

-- insert into the temp table and add the distinct and not null filter on the doc_id
INSERT INTO TMP_table
(
    uuid,
    id,
    doc_id,
    revenue,
    doc_date
)
SELECT
    uuid,
    id,
    select DISTINCT (table_x.doc_id) where table_x.doc_id IS NOT NULL,
    revenue,
    doc_date
FROM schema.table_x;

Upon running the above code I get a syntax error near distinct. And I can’t seem to figure out what the error is.

Any guidance please?

sql server – How do I use insert data into a sqlserver table from a python socket using .split() to separate entries and executemany with a variable?

I am trying to insert rfid tag reads from a socket using python into a sqlserver database. since im using a tcp socket, the data will sometimes combine and put multiple entries into a single row and i need each read to be a different row. i have combed through multiple sites and the closest thing that i could find was this Python Socket is receiving inconsistent messages from Server but i wasnt able to make it work. i am able to use len to separate them, but i have no way of possibly knowing how many reads will be combined together. here is my current code (section that is commented out is using len)

while 1: 
def data_entry():
        c.execute('INSERT INTO ORFinishing(Tag) VALUES(?)',(data2))
       
        conn.commit()
    
data = s.recv(1024)

data2= data.decode("utf-8").rstrip('n')
print(data2)


if len(data2) ==24:

    print("correct")
    
    data_entry()
    del data2
    
    
else:
    print("wrong")
    data3 = str(data2)
    data4 = data3.split('n')
    print(data4)
    
    
    def many():
        c.executemany('INSERT INTO ORFinishing(Tag) VALUES(?)', data4)
        conn.commit()
        
        many()
    
    # one,two = data2(:24), data2(-24:)
        
    
    # if len(one)==24:
    #     def data_entry1():
    #         c.execute('INSERT INTO ORFinishing(Tag) VALUES(?)',(one))
       
    #         conn.commit()
    
    #     data_entry1()
        
    # if len(two)==24:
    #     def data_entry2():
    #         c.execute('INSERT INTO ORFinishing(Tag) VALUES(?)',(one))
       
    #         conn.commit()
    
    #     data_entry2()
        

I have seen several instances of people using executemany but it was always manually entering a tuple or list. I also tried turning it into a tuple. here is the output that i get.

runfile(‘C:/a/tcpsocket.py’, wdir=’C:/a’)
623037353035000000000000
correct
623031323638000000000000
623031323734000000000000
623033323830360000000000
wrong
(‘623031323638000000000000’, ‘623031323734000000000000’, ‘623033323830360000000000’)

but it doesnt put any of the data from the string split (wrong section) into the database. for the case above, it only had one read in the database. using len does put it into the database but it could be 5 reads combined or 100 reads combined so its not really a viable option.

named characters – How insert into Text cell chevron symbols used for Inline GroupOpener icons?

If in OptionInspector I select option “Inline” for Cell Options > Display Options > ShowGroupOpener for section-like cells, then when such a group is closed it shows an icon that is a little box, with rounded corners, containing a symbol similar to a right-pointing chevron, like this:

Group closed icon

And when the group is open, the icon changes to one where the chevron points downward, like this:

Group open icon

I want to be able to explain those icons in a Text cell. How can I insert those symbols there?

mysql – Insert into table with polymorphic association in database

I want to design a database where some tables have multiple foreign keys.
I am looking for the best design approach.

I found out that this kind of problem is called “polymorphic association” in database. I found the Stack Overflow question Foreign Key to multiple tables and Nathan Skerl’s answer very helpful.

But according to the link above, if I want to insert a new user (not a new ticket, but a new user), what would be the insert statement based on the design?

First I insert into the party? How can I retrieve the id to insert into user or group table? Because it has identifying relationship with user and group.

psql – POSTGRESQL Query and insert based on results

In this case I’m trying to perform a SELECT based query followed by an insert of new records into the same table based on those results. For example a simple table:

Table "samples"

Fields: 
      id   unique
      name 
      locations
      randoma
      randomb
      randomc

To be clear my objective from the selection is to create a new sample with a given name and id for each location, but the rest of the fields can be left to default. This is the selection portion:

SELECT locations FROM samples WHERE name = 'example';

The command chain below works for a single record, but I need the query and creation to be iterative. Aforementioned attempt:

INSERT INTO samples (nextval('my_sequence'), 'newsample', (SELECT locations FROM samples WHERE name = 'example');

I’ve haven’t found a solution yet and would appreciate any admonishment on this PSQL simplicity.

I realize that this is a poor example in terms of database normalization, but it’s merely for effect.

Best regards and thanks in advance.

How to iterate through array with nested arrays to insert into DB (php)

I’m trying to figure out how to take an icalendar file from AirBnB, iterate through the values and then insert those in our MySQL DB.

I’m able to parse the ical file with results using the PHP Class iCalEasyReader with the following results:

Array
    (
     (PRODID;X-RICAL-TZSOURCE=TZINFO) => -//Airbnb Inc//Hosting Calendar 0.8.8//EN
     (CALSCALE) => GREGORIAN
     (VERSION) => 2.0
     (VEVENT) => Array
    (
        (0) => Array
            (
                (DTEND) => Array
                    (
                        (value) => 20210611
                        (type) => DATE
                    )

                (DTSTART) => Array
                    (
                        (value) => 20210610
                        (type) => DATE
                    )

                (UID) => 6fec1092d3fa-4126b88bbf4a059ac40146791e2f07ff@airbnb.com
                (SUMMARY) => Airbnb (Not available)
            )

        (1) => Array
            (
                (DTEND) => Array
                    (
                        (value) => 20210711
                        (type) => DATE
                    )

                (DTSTART) => Array
                    (
                        (value) => 20210703
                        (type) => DATE
                    )

                (UID) => 6fec1092d3fa-6e00333d20e7921f3dc74dff5bca3a9f@airbnb.com
                (SUMMARY) => Airbnb (Not available)
            )

        (2) => Array
            (
                (DTEND) => Array
                    (
                        (value) => 20220612
                        (type) => DATE
                    )

                (DTSTART) => Array
                    (
                        (value) => 20220307
                        (type) => DATE
                    )

                (UID) => 6fec1092d3fa-c0b7fcb782d4c41ea6dcbc5af78bfb61@airbnb.com
                (SUMMARY) => Airbnb (Not available)
            )

    )

 )

The only parts of the parsed file needed are the start and end date (DTSTART) and (DTEND) which are a nested array element and the (UID) and (SUMMARY) values which are all within the (VEVENT) array.

My goal is to iterate each array and insert the results into a MySQL DB. I can do the insert no problem and have much of the array parsed but getting the (VALUE) from (DTSTART) and (DTEND) are beyond my current understanding. I’ve reviewed this PHP Looping post regarding foreach iterating but can’t see how to get the values within the nested arrays for the dates.

My code so far is as follows:

<?php
   foreach ($lines(VEVENT) as $events) {
      foreach ($events as $val => $k) {
        echo 'Result: '.$val . ' - '. $k . '<br>';
      }
    }
 ?>

Which results in :

Result: DTSTART - Array
Result: UID - 6fec1092d3fa-4126b88bbf4a059ac40146791e2f07ff@airbnb.com
Result: SUMMARY - Airbnb (Not available)
Result: DTEND - Array
Result: DTSTART - Array
Result: UID - 6fec1092d3fa-6e00333d20e7921f3dc74dff5bca3a9f@airbnb.com
Result: SUMMARY - Airbnb (Not available)
Result: DTEND - Array
Result: DTSTART - Array
Result: UID - 6fec1092d3fa-c0b7fcb782d4c41ea6dcbc5af78bfb61@airbnb.com
Result: SUMMARY - Airbnb (Not available)

Which is quite close but not handling the nested array for the date keys or setting the break points to put in the Insert code.

SUMMARY: How to get the date values and create a point in the code to insert the parsed values as a single record and then continue to iterate available data from a parsed iCalendar file?

insert – Constraint in ON CONFLICT clause has no associated index

I have this simple setup

    CREATE TABLE stop (
      id INT UNIQUE,
      name TEXT,
      PRIMARY KEY(id)
    );

    CREATE TABLE line (
      id INT UNIQUE,
      name TEXT,
      PRIMARY KEY(id)
    );

    CREATE TABLE line_stops_sequence(
      id SERIAL PRIMARY KEY,
      line INT,
      stop INT,
      CONSTRAINT fk_line FOREIGN KEY(line) REFERENCES line(id),
      CONSTRAINT fk_stop FOREIGN KEY(stop) REFERENCES stop(id)
    );

When I launch the following sentence

INSERT INTO line(id, name) VALUES (1, 'Line 1');
INSERT INTO stop(id, name) VALUES (2, 'Stop 2');
INSERT INTO line_stops_sequence(line, stop) VALUES (1,1), (1,2) ON CONFLICT ON CONSTRAINT fk_stop DO NOTHING;

I get constraint in ON CONFLICT clause has no associated index;

I know I’m inserting an stop id that is not included in the stop table. The idea is that I want to ignore the INSERTs that have conflicts. In the example it is just two items, but I’m inserting bulk data.

How can I do it without having to manually check the result of the query? Is there anyway to do it with the SQL sentence?

plotting – How to mark nodes and insert weights in an adjacency graph?

I have a graph with 12 nodes. The x and y coordinates are give as

xcord={154.780094065851,    302.747331652902,   348.235746943268,   959.228504576796,   1021.26721027296,   1114.13365936238,   358.208241883160,   181.741156296042,   838.759299985938,   906.502702816486,   662.579285251179,   536.372745335719};

ycord={347.543166449207,    461.536311618993,   261.753095520236,   431.778284592051,   250.920713280060,   432.113192132818,   1044.66583584371,   1044.70069210915,   1135.19457237168,   984.121301679063,   792.153882418914,   708.946190878097};

Also, these are the edges connecting the nodes.

Edges={{1,2},{1,3},{1,8},{1,11},{1,12},{2,3},{2,4},{2,7},{2,8},{2,11},{2,12},{3,4},{3,5},{3,11},{3,12},{4,5},{4,6},{4,10},{4,11},{4,12},{5,6},{5,11},{5,12},{6,10},{6,11},{6,12},{7,8},{7,9},{7,10},{7,11},{7,12},{8,9},{8,11},{8,12},{9,10},{9,11},{9,12},{10,11},{10,12},{11,12}};

Let’s say, The weight of the edges are randomly generated.

I want to plot the graph. The nodes should be depicted as circles with the index within it. I also want to place the weight over the edges.

How can I do it?

sql – Is there a way to prevent flood insert from user in PosgreSQL? Is there some kind rate limit?

As a part of SQL injection prevention, I have revoked rights on DELETE and UPDATE for the user using the connection. In that way, an attacker cannot harm the integrity of the data even if the bad code allows SQL injection.

Now only left is INSERT. E.g. an attacker can flood insert a particular table, crating a dirty database or taking it down with flood INSERT, potentially taking down the HDD and the server where PostgreSQL is running. All DDL and DCL are already revoked for that user.

So, my question is: is it possible to prevent flood insert, rate-limiting specific connection / session / execution, attempting insert of more than 1 row per 5-10 seconds during the mentioned.

In multiple places, I have read as protection to give the right to function/procedure but to take rights on INSERT/DELETE/UPDATE, but I am not sure how to do it, as as soon you REVOKE rights on INSERT, the procedure will not work either as it is running by the same user.

So I am not quite sure how you prevent Script/Query execution, but you grant function/procedure execution?

If this is possible, can someone give me a practical example? How would you do something like this?

Answer in line of “limit the available RAM for insert” is not acceptable.

Thank you,