Click here to Skip to main content
15,867,704 members
Home / Discussions / C#
   

C#

 
AnswerRe: Deleting characters from a list<char> Pin
Eddy Vluggen25-Feb-23 6:24
professionalEddy Vluggen25-Feb-23 6:24 
AnswerRe: Deleting characters from a list<char> Pin
lmoelleb27-Feb-23 4:45
lmoelleb27-Feb-23 4:45 
AnswerRe: Deleting characters from a list<char> Pin
jochance7-Mar-23 8:21
jochance7-Mar-23 8:21 
QuestionC# xml serialization Pin
di24125313416-Feb-23 2:02
di24125313416-Feb-23 2:02 
AnswerRe: C# xml serialization Pin
Richard Deeming16-Feb-23 2:17
mveRichard Deeming16-Feb-23 2:17 
AnswerRe: C# xml serialization Pin
Dave Kreskowiak16-Feb-23 2:28
mveDave Kreskowiak16-Feb-23 2:28 
AnswerRe: C# xml serialization Pin
OriginalGriff16-Feb-23 9:00
mveOriginalGriff16-Feb-23 9:00 
QuestionSQL Injection Detection Pin
Member 805432115-Feb-23 5:01
Member 805432115-Feb-23 5:01 
Please help make this code work. I'm trying to run it in Visual Studio 2022. Thanks.

<pre lang="C#">


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Numpy;
using Python.Runtime;
using Keras;
using Keras.Layers;
using Keras.Models;
using Keras.Optimizers;
using Keras.losses;

namespace SQLInjectionDetection
{
    class Program
    {
        static void Main(string[] args)
        {
            // Load CSV file
            var trainData = File.ReadAllLines("tokens.csv")
                .Select(l => l.Split(','))
                .Select(s => new { Token = s[0], Label = int.Parse(s[1]) })
                .ToList();

            // Shuffle trainData
            var random = new Random();
            trainData = trainData.OrderBy(d => random.Next()).ToList();

            // Split trainData into training and validation sets
            var splitIndex = (int)(trainData.Count * 0.8);
            var trainDataSubset = trainData.Take(splitIndex).ToList();
            var testDataSubset = trainData.Skip(splitIndex).ToList();

            // Define vocabulary and tokenize trainData
            var vocabulary = new HashSet<char>(trainDataSubset.SelectMany(d => d.Token).Distinct());
            var tokenToIndex = vocabulary.Select((c, i) => new { Token = c, Index = i }).ToDictionary(t => t.Token, t => t.Index);
            var maxSequenceLength = trainDataSubset.Max(d => d.Token.Length);
            var trainTokenized = Tokenize(trainDataSubset, tokenToIndex, maxSequenceLength);
            var testTokenized = Tokenize(testDataSubset, tokenToIndex, maxSequenceLength);

            // Build RNN model
            using (Py.GIL())
            {
                dynamic keras = Py.Import("keras");
                dynamic np = Py.Import("numpy");
                var input = new Input(shape: 1000);
                var embedding = new Embedding(vocabulary.Count, 32).Apply(input);
                var lstm = new LSTM(32).Apply(embedding);
                var output = new Dense(1, activation: keras.activations.sigmoid).Apply(lstm);
                var model = new Model(inputs: input, outputs: output);
                model.Compile(optimizer: new Adam(), loss: new BinaryCrossentropy(), metrics: new[] { "accuracy" });

                // Train model
                var trainX = trainTokenized.Item1;
                var trainY = trainTokenized.Item2;
                var testX = testTokenized.Item1;
                var testY = testTokenized.Item2;
                model.Fit(trainX, trainY, batchSize: 32, epochs: 10, validationData: (testX, testY));

                // Take user input and make prediction
                Console.Write("Enter user input: ");
                var userInput = Console.ReadLine();
                var inputTokenized = TokenizeInput(userInput, tokenToIndex, maxSequenceLength);
                var prediction = model.Predict(inputTokenized).GetData<float>()[0, 0];
                Console.WriteLine($"Prediction: {(prediction > 0.5 ? "Malicious" : "Safe")} (Score: {prediction:F4})");

                // Evaluate model
                var testMetrics = model.Evaluate(testX, testY);
                Console.WriteLine($"Test loss: {testMetrics[0]:F4}");
                Console.WriteLine($"Test accuracy: {testMetrics[1]:F4}");
            }
        }

        private static (NDarray, NDarray) Tokenize(List<dynamic> data, Dictionary<char, int> tokenToIndex, int maxSequenceLength)
        {
            var numExamples = data.Count;
            var X = np.zeros((numExamples, maxSequenceLength));
            var Y = np.zeros((numExamples, 1));
            for (var i = 0; i < numExamples; i++)
            {
                var tokens = data[i].Token;
                var label = data[i].Label;
                Y[i] = label;
                for (var j = 0; j < tokens.Length; j++)
                {
                    var token = tokens[j];
                    var index = tokenToIndex[token];
                    X[i, j] = index;
                }
            }
            return (X, Y);
        }

    }
}

AnswerRe: SQL Injection Detection Pin
OriginalGriff15-Feb-23 5:21
mveOriginalGriff15-Feb-23 5:21 
Question.NetMAUI and NAudio Pin
D^Handy14-Feb-23 17:47
D^Handy14-Feb-23 17:47 
AnswerRe: .NetMAUI and NAudio Pin
Gerry Schmitz15-Feb-23 12:35
mveGerry Schmitz15-Feb-23 12:35 
GeneralRe: .NetMAUI and NAudio Pin
D^Handy15-Feb-23 12:40
D^Handy15-Feb-23 12:40 
GeneralRe: .NetMAUI and NAudio Pin
D^Handy15-Feb-23 12:41
D^Handy15-Feb-23 12:41 
GeneralRe: .NetMAUI and NAudio Pin
Gerry Schmitz15-Feb-23 13:51
mveGerry Schmitz15-Feb-23 13:51 
Questionusing cout down timer using c# Pin
Member 1592384614-Feb-23 3:44
Member 1592384614-Feb-23 3:44 
AnswerRe: using cout down timer using c# Pin
OriginalGriff14-Feb-23 4:04
mveOriginalGriff14-Feb-23 4:04 
AnswerRe: using cout down timer using c# Pin
jschell14-Feb-23 4:57
jschell14-Feb-23 4:57 
QuestionAsync functions Pin
Antti Pehkonen12-Feb-23 3:42
Antti Pehkonen12-Feb-23 3:42 
AnswerRe: Async functions Pin
Richard Deeming12-Feb-23 21:45
mveRichard Deeming12-Feb-23 21:45 
GeneralRe: Async functions Pin
Antti Pehkonen13-Feb-23 0:23
Antti Pehkonen13-Feb-23 0:23 
QuestionConverting Linq to Sql Code (SOLVED) Pin
samflex8-Feb-23 16:43
samflex8-Feb-23 16:43 
AnswerRe: Converting Linq to Sql Code Pin
Dave Kreskowiak8-Feb-23 17:35
mveDave Kreskowiak8-Feb-23 17:35 
GeneralRe: Converting Linq to Sql Code Pin
samflex8-Feb-23 17:48
samflex8-Feb-23 17:48 
GeneralRe: Converting Linq to Sql Code Pin
Dave Kreskowiak8-Feb-23 17:49
mveDave Kreskowiak8-Feb-23 17:49 
GeneralRe: Converting Linq to Sql Code Pin
samflex8-Feb-23 18:22
samflex8-Feb-23 18:22 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.