RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / user-261617

MiT's questions

Martin Hope
MiT
Asked: 2024-11-10 18:06:17 +0000 UTC

有关 Dart 和 Flutter 的书籍和学习资源

  • 8

在这里,我们将尝试收集有关 Dart 语言、Flutter 框架和流行库的文献和其他教育资源的最佳答案和推荐。

格式:

Название, Авторы. Год ISBN.

翻译文献格式:

Название, Авторы. Издательство, Год, ISBN.

电子资源以链接的形式呈现。

  • 不要创建新答案 - 编辑现有答案。
  • 请勿发布非法内容的链接,例如 torrent 跟踪器。
  • 尝试将事物按类别分开。
  • 按书名维护字母(字典顺序)排序。 (她什么时候会)

不要忘记,没有任何理论可以取代编程经验!阅读、尝试、练习。不清楚的话再问。尝试对您的项目进行编程,这是最好的方法。

此列表是社区支持的编程学习资源集合的一部分。

flutter
  • 1 个回答
  • 80 Views
Martin Hope
MiT
Asked: 2020-06-12 23:15:54 +0000 UTC

如何在 DataGrid 中显示一定数量的行?(C#/WPF)

  • 0

如何在 DataGrid 中显示一定数量的行?例如,只有前 15 个?

<DataGrid x:Name="CsvGrid" ColumnWidth="*" ItemsSource="{Binding csvTable}">


DataTable csvTable = new DataTable();
...
CsvGrid.ItemsSource = csvTable.DefaultView;
c#
  • 1 个回答
  • 10 Views
Martin Hope
MiT
Asked: 2020-06-11 23:01:26 +0000 UTC

将 DataGrid 中的选定列保存为 Excel 格式 (C#/WPF)

  • 0

数据集进入 DataGrid,并非所有数据都具有相同的列集及其顺序。DataGrid 中的数据是手动显示的,而不是通过 ItemSource 和 DataContext。DataGrid 中的列选择通过复选框进行。

XAML:

<StackPanel Grid.Column="4" Grid.Row="0" x:Name="CheckBoxes"/>
<DataGrid Grid.ColumnSpan="5" Grid.Column="0" Grid.Row="1" x:Name="CsvGrid" ColumnWidth="*" MouseDoubleClick="CsvGrid_OnMouseDoubleClick" ItemsSource="{Binding csvTable}"/>

CheckBoxes 在代码中创建并添加到 StackPanel:

for (int i = 0; i <= count; i++)
{
    CheckBox _checks = new CheckBox();
    _checks.Tag = fileDataField[i];
    _checks.Content = fileDataField[i];
    CheckBoxes.Children.Add(_checks);
}

接下来,我想准确保存 CheckBox 中标记的那些列:

CsvGrid.SelectAllCells(); // беру все столбцы
foreach (var checkBox in CheckBoxes.Children.OfType<CheckBox>().Where(x => x.IsChecked == true))
{
    for(int i = 0; i < CsvGrid.SelectedCells.Count; i++)
    {
        if(checkBox.Tag != CsvGrid.Columns[i].Header) //Как удалить лишние ???
    }
}
CsvGrid.ClipboardCopyMode = DataGridClipboardCopyMode.IncludeHeader;
ApplicationCommands.Copy.Execute(null, CsvGrid);
String result = (string) Clipboard.GetData(DataFormats.Text);
CsvGrid.UnselectAllCells();

SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.FileName = "Document";
saveFileDialog.DefaultExt = ".xls";
saveFileDialog.Filter = "Excel|*.xls|Excel 2010|*.xlsx|CSV files (*.csv)|*.CSV";
saveFileDialog.InitialDirectory = 
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if (saveFileDialog.ShowDialog() == true) File.WriteAllText(saveFileDialog.FileName, result.Replace(',', ' '));
MessageBox.Show("File created!");

我如何从选择中进入 foreach:

CSVGrid.SelectAllCells();

删除不需要的列?

c#
  • 2 个回答
  • 10 Views
Martin Hope
MiT
Asked: 2020-03-11 16:54:43 +0000 UTC

使用一堆 JavaScript 和 Angular 6 时的名称冲突

  • 0

我有自己写的js库,添加到angular.json中,添加好了。我在 html 文件中使用它:

<div class="video-cover" id="videoPlayer" data-title="{{title.name}} ({{title.year}})"></div>

这就是问题开始的地方,在编译时,由于名称冲突, data-title将其名称更改为title 。因此,JS 停止执行其功能......将名称data-title更改为data-name在编译期间显示错误:

ERROR in : Can't bind to 'data-name' since it isn't a known property of 'div'.

<div ... [ERROR ->]data-name="{{title.name}} ({{title.year}})"></div>

如何解决问题?

angular
  • 1 个回答
  • 10 Views
Martin Hope
MiT
Asked: 2020-09-19 18:04:45 +0000 UTC

如何编写一个脚本,在折叠窗口中定期显示英文单词及其翻译,然后将其关闭?

  • -2

我在学一点js,遇到了这么一个奇怪的任务,一方面很有趣,另一方面,看不懂。

编写一个脚本,定期在折叠窗口中显示英文单词及其翻译,然后将其关闭。

问题是:

  • 怎么理解?
  • 怎么做?
javascript
  • 1 个回答
  • 10 Views
Martin Hope
MiT
Asked: 2020-07-28 22:13:41 +0000 UTC

是否可以将 AvaloniaUI 与 MaterialDesignInXamlToolkit 连接起来?

  • 0

我使用MaterialDesignInXamlToolkit在 WPF 上开发了一个项目,然后我意识到这个项目需要跨平台。我了解了AvaloniaUI,阅读并喜欢它。但是问题出现了,是否可以将 AvaloniaUI 与 MaterialDesignInXamlToolkit 一起使用?并且,如果可能的话,UI 将如何在不同的平台上显示?

PS我正在Visual Studio 2017上开发

c#
  • 1 个回答
  • 10 Views
Martin Hope
MiT
Asked: 2020-07-13 18:01:06 +0000 UTC

刷新 ListView 中的数据 (C#/WPF)

  • 0

有一个ListView在里面写入数据,事实是没有办法一次把所有的东西都写完,所以需要更改/更新已经输入到ListView中的数据。做这个的最好方式是什么?

<ListView x:Name="ClientsInfo">
    <ListView.View>
        <GridView>
            <GridViewColumn DisplayMemberBinding="{Binding Path=ConnectionID}">ID</GridViewColumn>
            <GridViewColumn DisplayMemberBinding="{Binding Path=ClientName}">Name</GridViewColumn>
            <GridViewColumn DisplayMemberBinding="{Binding Path=Version}">Version</GridViewColumn>
            <GridViewColumn DisplayMemberBinding="{Binding Path=ComputerID}">Computer ID</GridViewColumn>
            <GridViewColumn DisplayMemberBinding="{Binding Path=ClientIP}">Client IP</GridViewColumn>
            <GridViewColumn DisplayMemberBinding="{Binding Path=PingTime}">Ping Time</GridViewColumn>
        </GridView>
    </ListView.View>
</ListView>



public class ClientsInfo
{
    public string ConnectionID { get; set; }
    public string ClientName { get; set; }
    public string Version { get; set; }
    public string ComputerID { get; set; }
    public string ClientIP { get; set; }
    public string PingTime { get; set; }
}

ClientsInfo.Items.Add(new ClientsInfo
{
    ConnectionID = clientNumber.ToString(),
    ClientName = "Receiving...",
    Version = "Receiving...",
    ComputerID = "Receiving...",
    ClientIP = clientIP,
    PingTime = "..."
});
ClientsInfo.Items.Refresh();

...

ClientsInfo.Items.Add(new ClientsInfo
{
    ClientName = clientsName,
    Version = versionStr,
    ComputerID = computerName,
});
ClientsInfo.Items.Refresh();

...

ClientsInfo.Items.Add(new ClientsInfo
{
    PingTime = $"{elapsedTimeInMilliseconds:0.##}ms"
});
ClientsInfo.Items.Refresh();
c#
  • 1 个回答
  • 10 Views
Martin Hope
MiT
Asked: 2020-07-06 20:12:39 +0000 UTC

从字符串到字节[] (C#)

  • 1

有一小段代码,其含义是仅将数组中的数字(其中相似的数字 123.1.512.61 以不同的组合出现)传输到文本框(例如:firstBox.Text 中的 123;secondBox.Text 中的 1 等) . ) . 但是出了点问题,目前我将所有内容都排成一行,一次一个字符(1;2;3;.;等等。)

如何解决?

public void SetByteArray(string userOutput)
        {
            byte[] userOutputBytes = new byte[4];

            if (userOutput != null)
            {
                userOutputBytes = userOutput.Split(new[] {'.'}, StringSplitOptions.RemoveEmptyEntries)
                    .Select(s => Convert.ToByte(s, 8))
                    .ToArray();
            }
            else
            {
                userOutput = "123.0.10.321";
                userOutputBytes = userOutput.Split(new[] {'.'}, StringSplitOptions.RemoveEmptyEntries)
                    .Select(s => Convert.ToByte(s, 8))
                    .ToArray();
            }

            firstBox.Text = Convert.ToString(userOutput[0]);
            secondBox.Text = Convert.ToString(userOutput[1]);
            thirdBox.Text = Convert.ToString(userOutput[2]);
            fourthBox.Text = Convert.ToString(userOutput[3]);
        }
c#
  • 1 个回答
  • 10 Views
Martin Hope
MiT
Asked: 2020-06-04 19:49:42 +0000 UTC

使用队列和 OOP (C++)

  • 0

给定一个文本文件,其中包含需要重写到队列 Qu1 的整数图像。在队列 Qu2 中,首先写入回文数,然后是数字和为奇数的数,将其余数写入输出文件。使用 OOP 方法创建程序。

我做了我能做的,但出现了很多错误......我请求你的帮助!

#include "stdafx.h"
#include <iostream>
#include <conio.h>
#include <queue>
#include <fstream>
#include <algorithm>
#include <iterator>

using namespace std;

unsigned getReverse(unsigned n) {
    unsigned r = n % 10;
    while (n /= 10) {
        r = r * 10 + n % 10;
    }
    return r;
}
bool isPalindrom(const unsigned n) {
    return n == getReverse(n);
}

class cQueue
{
protected:
    queue<int> p_;
public:
    void IO();

    void Del()
    {
        while (!p_.empty())
        {
            p_.pop();
        }
    };
};

void cQueue::IO()
{
    ifstream ifile("text.txt");
    ofstream ofile("output.txt", ios::trunc);

    queue<int> qu1 = p_;
    for_each(istream_iterator<int>(ifile), istream_iterator<int>(), [&qu1](int n)
    {
        qu1.push(n);
    });

    cout << "Number of items in the queue: " << qu1.size() << endl;
    while (!qu1.empty())
    {
        cout << "\nHere they are: " << qu1.front() << '\n';
    }

    queue<int> qu2;
    copy_if(queue<int>(qu1), queue<int>(), queue<int>(qu2), [&qu1](int n) -> bool
    {
        if (isPalindrom(n)) {
            return n;
        }
        else if (n) {
            // Сумма нечетных чисел ?
        }
        else
        {
            // В выходной файл ?
        }
    });

    cout << "Number of items in the queue: " << qu2.size() << endl;
    while (!qu2.empty())
    {
        cout << "\nHere they are: " << qu2.front() << '\n';
    }
}


int main()
{
    cout << "Demo Queue OOP" << endl;

    cQueue queue;
    queue.IO();
    cout << endl;
    queue.Del();

    _getch();
    return 0;
}

错误 C2675 一元“++”:“std::queue>>”未定义此运算符或转换为内置 \algorithm 运算符可接受的类型 594

错误 C2100 无效间接\算法 596

错误 C2100 无效间接\算法 598

错误 C2675 一元 '++': 'std::queue>>' 未定义此运算符或转换为内置 \algorithm 运算符 599 可接受的类型

错误 C4996 'std::copy_if::_Unchecked_iterators::_Deprecate': 使用可能不安全的参数调用 'std::copy_if' - 此调用依赖调用者检查传递的值是否正确。要禁用此警告,请使用 -D_SCL_SECURE_NO_WARNINGS。请参阅有关如何使用 Visual C++ 'Checked Iterators' \algorithm 589 的文档

c++
  • 2 个回答
  • 10 Views
Martin Hope
MiT
Asked: 2020-05-29 18:07:48 +0000 UTC

查找并删除列表中的最大元素。(C++)

  • 0

有必要从列表的前 n 个元素中删除最大的元素。不知何故,我不知道该怎么做。请告诉我该怎么做。

#include "stdafx.h"
#include <iostream>
#include <conio.h>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>

using namespace std;

#define List struct list
List
{
    int Dn;
    List* Nx;
};

class cList
{
protected:
    List* p;
public:
    cList() : p(NULL) {}
    ~cList();
    int Empty() { return p == NULL; }

    void AddHead(int D)
    {
        List* q = new(List);
        q->Dn = D;
        q->Nx = p;
        p = q;
    }

    void Display();
    void AddEnd(int D);
    long Len();

    void DelFirst()
    {
        List* q = p;
        p = p->Nx;
        delete(q);
    }
};

void cList::Display()
{
    List* t = p;
    if (p)
        while (t)
        {
            cout << t->Dn << " ";
            t = t->Nx;
        }
    else cout << "->|";
    cout << endl;
};

void cList::AddEnd(int D)
{
    List* q = new List;
    q->Dn = D;
    q->Nx = NULL;
    List* t = p;
    if (p)
    {
        while (t->Nx) t = t->Nx;
        t->Nx = q;
    }
    else p = q;
};

long cList::Len()
{
    if (p)
    {
        List* t = p;
        long i = 0;
        while (t)
        {
            t = t->Nx;
            i++;
        };
        return i;
    };
    return 0;
};

cList::~cList()
{
    while (!Empty()) DelFirst();
};

int main()
{
    cout << "Demo List" << endl;
    int A[12] = {23, 19, 14, 43, 17, 22, -31, 46, -7, 2, 64, 53};
    cList L1;
    cout << "The list is empty?:" << L1.Empty() << endl;
    L1.Display();
    cout << endl;
    for (int i = 0; i < 12; i++) L1.AddEnd(A[i]);
    L1.Display();
    cout << endl;
    cout << "Count Element = " << L1.Len() << endl;
    L1.~cList();
    system("pause");
    return 0;
}
c++
  • 2 个回答
  • 10 Views
Martin Hope
MiT
Asked: 2020-04-16 00:39:45 +0000 UTC

如何尽可能优化和改进代码(RDP)?(C#)

  • -1

因此,我想制作一个带有客户端和服务器的小型 RDP(没有操纵器)。有一个用于创建、压缩、发送和接收图像的小代码。看起来一切都很好,但是即使在局域网上也有野物(尽管正常接收到一半的图像),我还没有通过网络尝试过,我认为它会是一样的。

本地主机上的工件 我没有足够的知识来尽可能优化这段代码,所以我请求你的帮助!

代码:发送 SendStream.cs

using System;
using System.Drawing;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;

namespace Client.Sender
{
    public class SendStream
    {
        private IPEndPoint ipEndPoint;
        private UdpClient _udpClient;
        private int width;
        private int height;
        private const UInt16 UdpSize = 65507;
        private const UInt16 ControlBlockSize = 5;
        private Random random = new Random();
        private byte lastA = 0; // Последний код цепочки
        private byte lastB = 0; // Последний код цепочки
        private float FPS = 60;

        public SendStream()
        {
            // Загружаем номер порта, на которой надо встать
            using (StreamReader streamReader = new StreamReader("ip.txt"))
            {
                string ip = streamReader.ReadLine();
                int port = Convert.ToInt32(streamReader.ReadLine());

                if (ip != null) ipEndPoint = new IPEndPoint(IPAddress.Parse(ip), port);
            }

            width = Screen.PrimaryScreen.Bounds.Width;
            height = Screen.PrimaryScreen.Bounds.Height;
        }

        public async Task Run()
        {
            _udpClient = new UdpClient();
            Bitmap backGround = new Bitmap(width, height);
            Graphics graphics = Graphics.FromImage(backGround);

            while (true)
            {
                await Task.Delay((int) (1000 / FPS));
                graphics.CopyFromScreen(0, 0, 0, 0, new System.Drawing.Size(width, height)); // Получаем снимок экрана

                byte[] bytes = ConvertToByte(backGround); // Получаем изображение в виде массива байтов
                List<byte[]> data = Package(bytes); // Упаковка изображения в протокол

                foreach (var block in data)
                {
                    await _udpClient.SendAsync(block, block.Length, ipEndPoint);
                }
            }
        }

        /* 
         * Конвертируем изображение в массив байтов со сжатием
         * Jpeg - качество средние, скорость средние, потери малые (полупрозрачные, 40-60%)
         * Gif - качество плохое, скорость максимальное, потери огромные (тв, 90%)
         * Png - качество выше-среднего, скорость выше-среднего, потери средние (серый цвет, 40-60%)
         *
        */
        private byte[] ConvertToByte(Bitmap bmp)
        {
            MemoryStream memoryStream = new MemoryStream();
            bmp.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Gif);
            return memoryStream.ToArray();
        }


        // Пакеты для передачи UDP
        private List<byte[]> Package(byte[] bt)
        {
            int countMsg = (int) Math.Ceiling(bt.Length / (double) UdpSize); // Количество сообщений
            List<byte[]> chain = new List<byte[]>(); // Цепочка сообщений

            if (countMsg > 65536)
                throw new Exception(
                    "Вы пытаетесь передать сообщение больше 4 ГБ - протокол не подерживает передачу свыше 4 ГБ");

            byte[] controlBlock = new byte[ControlBlockSize]; // Формируем контрольный блок
            controlBlock[0] = 1;

            byte a, b;
            do
            {
                a = (byte) random.Next(0, 256);
                b = (byte) random.Next(0, 256);
            } while (a == lastA && b == lastB);
            // Цикл нужен, чтобы случайно не совпал код сообщений из другой цепочки, 
            // в одной из параллельных вселенной этот цикл выполняется бесконечно

            controlBlock[1] = a;
            controlBlock[2] = b;
            controlBlock[3] = BitConverter.GetBytes(countMsg)[0];
            controlBlock[4] = BitConverter.GetBytes(countMsg)[1];

            chain.Add(controlBlock);

            int offset = 0;
            for (int i = 0; i < countMsg; i++)
            {
                byte[] msgBlock = new byte[UdpSize]; // Формируем блок сообщения
                msgBlock[0] = 0;
                msgBlock[1] = a;
                msgBlock[2] = b;

                msgBlock[3] = BitConverter.GetBytes(i)[0];
                msgBlock[4] = BitConverter.GetBytes(i)[1];

                int msgBlockLength;
                if (bt.Length - offset <= UdpSize)
                {
                    msgBlockLength = bt.Length - offset;
                }
                else
                {
                    msgBlockLength = UdpSize - 7; // 5 - в данном случае первые 5 байтов
                }

                msgBlock[5] = BitConverter.GetBytes(msgBlockLength)[0];
                msgBlock[6] = BitConverter.GetBytes(msgBlockLength)[1];

                if (i == countMsg - 1)
                {
                    Array.Copy(bt, offset, msgBlock, 7, bt.Length - offset);
                }
                else
                {
                    Array.Copy(bt, offset, msgBlock, 7, UdpSize - 7);
                }

                chain.Add(msgBlock);

                offset += UdpSize;
                if (offset > bt.Length)
                {
                    offset = bt.Length;
                }
            }

            return chain;
        }

        /*  Описание протокола передачи LO поверх UDP
            1 байт - контрольный пакет (1 если контрольный и 0 если не контрольный)

            Расположение байтов для контрольного пакета
            2 - 3 байт кодовый номер цепочки пакетов
            4 - 5 байт количество пакетов

            Расположение байтов для неконтрольного пакета
            2 - 3 байт кодовый номер пакета
            4 - 5 байт номер пакета
            5 - 6 байт размер пакета, а именно данных без первых 6 байт (включая нулевой байт).
         */
    }
}

代码:接受 TakeStream.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media.Imaging;
using System.IO;

namespace Server.Receiving
{
    class TakeStream
    {
        private int TTL = 70; // Время жизни пакетов
        private List<Packet> turn = new List<Packet>(); // Очередь сообщений
        private List<Packet> controls = new List<Packet>(); // Контрольные пакеты

        public delegate void EventReady(BitmapImage img);

        public event EventReady FrameReady;

        private struct Packet
        {
            public bool isControl; // Это контрольный пакет?
            public UInt16 id; // ID цепочки
            public byte[] date; // Данные пакета
            public UInt16 count; // Количество пакетов
            public UInt16 number; // Порядковый номер пакета
            public int TTL; // Длительность жызни пакета или контрола
        }

        public TakeStream()
        {
        }

        public void addPacked(byte[] data)
        {
            Packet packet = decodeMsg(data);

            if (packet.isControl)
            {
                controls.Add(packet);
            }
            else
            {
                turn.Add(packet);

                for (int i = 0; i < controls.Count; i++)
                {
                    if (controls[i].id == packet.id && controls[i].count - 1 == packet.number)
                    {
                        MemoryStream ms = new MemoryStream(Compare(packet.id));

                        controls.RemoveAt(i);
                        i--;

                        BitmapImage bitmapImg = new BitmapImage();
                        bitmapImg.BeginInit();
                        bitmapImg.CacheOption = BitmapCacheOption.OnLoad;
                        bitmapImg.StreamSource = ms;
                        bitmapImg.EndInit();
                        bitmapImg.Freeze();

                        FrameReady(bitmapImg);
                    }
                }
            }
        }

        // Сообщение
        private Packet decodeMsg(byte[] data)
        {
            Packet packet = new Packet();
            packet.TTL = 0;
            packet.isControl = data[0] == 1;
            packet.id = BitConverter.ToUInt16(data, 1);

            if (packet.isControl)
            {
                packet.count = BitConverter.ToUInt16(data, 3);
            }
            else
            {
                packet.number = BitConverter.ToUInt16(data, 3);
                packet.date = new byte[BitConverter.ToUInt16(data, 5)];

                try
                {
                    Array.Copy(data, 7, packet.date, 0, packet.date.Length);
                }
                catch (Exception ex)
                {
                }
            }

            return packet;
        }

        // Исходные данные
        private byte[] Compare(UInt16 id)
        {
            List<byte> data = new List<byte>();

            for (int i = 0; i < turn.Count; i++)
            {
                if (turn[i].id == id)
                {
                    data.AddRange(turn[i].date);
                    turn.RemoveAt(i);
                    i--;
                }
            }

            return data.ToArray();
        }

        private void RemoveChain(UInt16 id)
        {
            for (int i = 0; i < turn.Count; i++)
            {
                if (turn[i].id == id)
                {
                    turn.RemoveAt(i);
                }
            }
        }

        /*  Описание протокола передачи LO поверх UDP
            1 байт - контрольный пакет (1 если контрольный и 0 если не контрольный)

            Расположение байтов для контрольного пакета
            2 - 3 байт кодовый номер цепочки пакетов
            4 - 5 байт количество пакетов

            Расположение байтов для неконтрольного пакета
            2 - 3 байт кодовый номер пакета
            4 - 5 байт номер пакета
            5 - 6 байт размер пакета, а именно данных без первых 6 байт (включая нулевой байт).
         */
    }
}

代码:接受具有给定大小的空 UserControlScreenStream.cs PS 表单

using System;
using System.Text;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Net;
using System.Net.Sockets;
using System.IO;
using PRP_Server.Receiving;

namespace Server.UserControls
{
    public partial class UserControlScreenStream : UserControl
    {
        private UdpClient udpClient;
        private const UInt16 UdpSize = 65507;
        private const UInt16 ControlBlockSize = 5;

        private delegate void AsynkWorker();

        private delegate void DrawEvent(BitmapImage bitmapImage);

        private delegate void Invoke(byte[] data);

        private TakeStream takeStream = new TakeStream();
        private UInt16 _port;

        public UserControlScreenStream()
        {
            InitializeComponent();
            takeStream.FrameReady += new TakeStream.EventReady(decoder_FrameReady);
            new AsynkWorker(Run).BeginInvoke(null, null);
        }

        void decoder_FrameReady(BitmapImage img)
        {
            this.Background = new ImageBrush(img);
        }

        void MainWindow_Invoke(byte[] data)
        {
            try
            {
                takeStream.addPacked(data);
            }
            catch (Exception ex)
            {
                // ignored
            }
        }

        private void Run()
        {
            using (StreamReader sr = new StreamReader("port.txt"))
            {
                _port = UInt16.Parse(sr.ReadLine());
            }

            UdpClient udp = new UdpClient(new IPEndPoint(IPAddress.Any, _port));
            IPEndPoint ep = new IPEndPoint(IPAddress.None, 0);

            while (true)
            {
                byte[] mass = udp.Receive(ref ep);
                Dispatcher.Invoke(new Invoke(MainWindow_Invoke), mass);
            }

            /* byte[] test = new byte[5];
            test[0] = 1;
            test[1] = 2;
            test[2] = 3;
            test[3] = 4;
            test[4] = 5;

            decoder.addPacked(test); */
        }
    }
}
c#
  • 1 个回答
  • 10 Views
Martin Hope
MiT
Asked: 2020-02-03 18:06:43 +0000 UTC

如何比较大,小字符串?

  • 0

如何比较字符串(字符串)更大或更小?

我需要做这样的事情: if (fi1 >= fi2); 如果 (fi1 <= fi2); 如果 (fi1 == fi2) ...

private string GetFolderName(string filePath)
{
    using (var photo = File.Open(filePath, FileMode.Open, FileAccess.Read))
    {
        try
        {
            photo.Flush();
            photo.Close();
            var fi = new FileInfo(filePath);
            var fi1 = fi.CreationTime.ToString(_dirMask);
            var fi2 = fi.LastWriteTime.ToString(_dirMask);

            if (fi1 == fi2) //if (fi1 >= fi2) как это сделать?
            {
                return fi1;
            }
            else return fi2;
        }
        catch
        {
            ...
        }
    }
}
c#
  • 1 个回答
  • 10 Views
Martin Hope
MiT
Asked: 2020-12-29 02:22:18 +0000 UTC

数据库连接 (C#)

  • 0

我是否正确连接到数据库?

连接时出现错误adapter.Fill(table);

using MySql.Data.MySqlClient;
...
    private void buttonOk_Click(object sender, EventArgs e)
    {
        timer2.Start();
    }

    public static string Datasource = "localhost";
    public static string Port = "3306";
    public static string InitialCatalog = "user";
    public static string Username = "user";
    public static string Password = "pass";

    //MySql
    MySqlConnection connection = new MySqlConnection("datasource=" + Datasource + ";port=" + Port + ";Initial Catalog='" + InitialCatalog + "';username=" + Username + ";password=" + Password);
    MySqlDataAdapter adapter;
    DataTable table = new DataTable();

    public void MySqlConnect()
    {
        adapter = new MySqlDataAdapter("SELECT `username`, `password` FROM `users` WHERE `username` = '" + textBoxUsername.Text + "' AND `password` = '" + textBoxPassword.Text + "'", connection);
        adapter.Fill(table); //PROBLEM

        if (table.Rows.Count <= 0)
        {
            panel1.Height = 0;
            labelMessage.ForeColor = Color.Red;
            labelMessage.Text = "Username Or Password Are Invalid";
            timer1.Start();
        }
        else
        {
            panel1.Height = 0;
            labelMessage.ForeColor = Color.Green;
            labelMessage.Text = "Login Successfully";
            timer1.Start();
        }

        table.Clear();
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        if (panel1.Height != 100)
        {
            panel1.Height = panel1.Height + 5;
            if (panel1.Height == 100)
            {
                timer1.Stop();
            }
        }
    }

    private void timer2_Tick(object sender, EventArgs e)
    {
        if (panel1.Height != 0)
        {
            panel1.Height = panel1.Height - 5;
            if (panel1.Height == 0)
            {
                timer2.Stop();
            }
        }
    }

    private void checkBoxShowPass_CheckedChanged(object sender, EventArgs e)
    {
        if (checkBoxShowPass.Checked)
        {
            textBoxPassword.UseSystemPasswordChar = true;
        }
        else
        {
            textBoxPassword.UseSystemPasswordChar = false;
        }
    }
...

错误文本

MySql.Data.MySqlClient.MySqlException
  HResult=0x80004005
  Сообщение = Authentication to host 'localhost' for user 'user' using method 'mysql_native_password' failed with message: Access denied for user 'user'@'localhost' (using password: YES)
  Источник = MySql.Data
  Внутреннее исключение 1:
MySqlException: Access denied for user 'user'@'localhost' (using password: YES)
c#
  • 2 个回答
  • 10 Views
Martin Hope
MiT
Asked: 2020-12-28 02:29:56 +0000 UTC

将函数从一种形式传递到另一种形式(C#)

  • 1

将函数从一种形式传递到另一种形式时遇到此问题。如何解决?

登录:

private MainClient OnConnect;
private MainClient OnDataReceived;
private MainClient OnServerDisconnect;
public Login(MainClient OnConnect, MainClient OnDataReceived, MainClient OnServerDisconnect)
{
    InitializeComponent();
    this.OnConnect = OnConnect;
    this.OnDataReceived = OnDataReceived;
    this.OnServerDisconnect = OnServerDisconnect;
}

private void buttonLogin_Click(object sender, EventArgs e)
{
    ...
    MainClient._client = new Sock.Client { BufferSize = 1048576 };
    MainClient._client.OnConnect += OnConnect; //Problem
    MainClient._client.OnDataReceived += OnDataReceived; //Problem
    MainClient._client.OnServerDisconnect += OnServerDisconnect; //Problem
    ...
}

主要的:

...
public static Sock.Client _client = new Sock.Client();
public static ClientInfo _clientInfo = new ClientInfo();
...
private void runLoginScreen()
{
    Application.Run(new Login(this, this, this));
}

Не удается неявно преобразовать тип "Project_Name.Main" в "Sock.Client.ServerDisconnectedEventHanlder".代码中标记为“问题”的问题

c#
  • 1 个回答
  • 10 Views
Martin Hope
MiT
Asked: 2020-12-23 01:23:47 +0000 UTC

如何进行永久服务器状态检查(C#)

  • 1

所以,有一个服务器,你需要不断地、异步地知道它的状态......

这样试了,不行

Thread pingThread = new Thread(_client_PingServer);
pingThread.Start();

private void _client_PingServer()
        {
            try
            {
                System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping();
                System.Net.NetworkInformation.PingReply pingReply = ping.Send(settingsControl1.txtIPAddress.Text);
                if (pingReply.RoundtripTime <= 70 && pingReply.RoundtripTime >= 1)
                {
                    labelServerStatus.ForeColor = System.Drawing.Color.Green;
                }
                else if (pingReply.RoundtripTime >= 70 && pingReply.RoundtripTime <= 120)
                {
                    labelServerStatus.ForeColor = System.Drawing.Color.Orange;
                }
                else if (pingReply.RoundtripTime >= 120)
                {
                    labelServerStatus.ForeColor = System.Drawing.Color.Red;
                }
                else if (pingReply.RoundtripTime == 0)
                {
                    labelServerStatus.Text = @"Offline";
                }
                if (pingReply.RoundtripTime != 0)
                {
                    labelServerStatus.Text = pingReply.RoundtripTime.ToString();
                }
            }
            catch (PingException)
            {
                labelServerStatus.ForeColor = System.Drawing.Color.Red;
                labelServerStatus.Text = @"Offline";
            }
        }

你的想法?

c#
  • 1 个回答
  • 10 Views
Martin Hope
MiT
Asked: 2020-12-22 19:15:27 +0000 UTC

如何用“梯子”(每行一个字)写下富有诗意的文字?

  • 0

锻炼:

诗文(每行不超过 80 个字符)有四行小写。把它写成一个“梯形图”(每行一个单词),在每个四行诗之后插入一个空行。

我的代码:

#include "stdafx.h"
#include <iostream>
#include <string>
#include "conio.h"

using namespace std;

size_t LengthOfUtf8String(const std::string &utf8_string) {
  return distance(utf8_string.begin(), utf8_string.end());
}

int main(int argc, const char* argv[])
{
  char sub;
  int i = 0, n = 0;
  string a[80];
  string s;

  system("CLS");
  cout << "Input str" << endl;
  cin >> s;

  do {
    i += 1;
    if ((s[i] == ' ') || (s[i] == ',')) {
      n += 1;
      a[n] = sub;
      sub = ' ';
    }
    else sub = sub + s[i];
  } while (!(i == LengthOfUtf8String(s)));
  n += 1;
  a[n] = sub;
  cout << endl;


  for (i = 1; i <= n; i++)
  {
    if (i % 4 == 1)  cout << a[i] << endl;
    if (i % 4 == 2)  cout << ' ' << a[i] << endl;
    if (i % 4 == 3)  cout << "   " << a[i] << endl;
    if (i % 4 == 0) {
      cout << "    " << a[i] << endl;
      cout << endl;

    }
  }
  system("pause");
}

问题:我做错了什么?以及应该如何正确完成?

c++
  • 1 个回答
  • 10 Views
Martin Hope
MiT
Asked: 2020-12-21 17:10:52 +0000 UTC

如何将矩阵顺时针旋转一位?(C++)

  • 2

任务: 矩阵旋转。在每个嵌套子矩阵的周长内将给定矩阵的元素顺时针移动一个位置。矩阵NxM。

问: 怎么办?它是一个位置的旋转,也不要忘记子矩阵。

条件说明

Пример (N=3; M=4):
0| 1 | 2 | 3 | 4 
=|================
1| 1   2   3   4  
2| 5   6   7   8  
3| 9   10  11  12

Результат (Как видите 6 и 7 поменяли свое местоположение в своей подматрице, так как матрица 3х4):
0| 1 | 2 | 3 | 4 
=|================
1| 5   1   2   3  
2| 9   7*  6*  4  
3| 10  11  12  8

Пример №2 (N=4; M=4):
0| 1 | 2 | 3 | 4 
=|================
1| 1   2   3   4  
2| 5   6   7   8  
3| 9   10  11  12
4| 13  14  15  16

Результат №2 (Как видите 6, 7, 10, 11 тоже повернулись на один элемент вправо):
0| 1 | 2 | 3 | 4 
=|================
1| 5   1   2   3  
2| 9   10* 6*  4  
3| 13  11* 7*  8
4| 14  15  16  12

"Цифра"* для пояснения

我尝试了一个一维数组,但得出的结论是子矩阵很难组装。 我要考虑的代码:

int main() {
int i, j;
int N;

cout << "Введите размеры матрицы:" << endl;
cout << "N = ";
cin >> N;
cout << "Матрица размером: " << N << "x" << N << endl;
//ДА, я знаю что матрица у меня N на N. Позже она станет размером N на M

int o = N * N;
int k = 0, mas[o];

int **A = new int *[N];
for (i = 0; i < N; i++) {
    A[i] = new int[N];
}

int **B = new int *[N];
for (i = 0; i < N; i++) {
    B[i] = new int[N];
}
cout << "Введите матрицу:" << endl;
for (i = 0; i < N; i++) {
    for (j = 0; j < N; j++) {
        cin >> A[i][j];
    }
}
cout << "Матрица до поворота:" << endl;
for (i = 0; i < N; i++) {
    for (j = 0; j < N; j++) {
        B[i][j] = A[i][j];
        cout << B[i][j] << " ";
    }
    cout << endl;
}
//Тут и нужно сделать поворот матрицы
/*Test*/
cout << "Одномерная матрица:" << endl;
for (i = 0; i < N; i++) {
    for (j = 0; j < N; j++) {
        mas[k++] = B[i][j];
    }
}
for (k = 0; k < o; k++) {
    cout << mas[k] << " ";
}
cout << endl;

cout << "Сортировка:" << endl;
for (k = 0; k < o - 1; k++) {
    int temp = mas[k];
    mas[k] = mas[k + 1];
    mas[k + 1] = temp;
}
for (k = 0; k < o; k++) {
    cout << mas[k] << " ";
}
cout << endl;

k = 0;
for (i = 0; i < N; i++) {
    for (j = 0; j < N; j++) {
        B[i][j] = mas[k++];
    }
}
/*Test*/

cout << "Матрица после поворота:" << endl;
for (i = 0; i < N; i++) {
    for (j = 0; j < N; j++) {
        cout << B[i][j] << " ";
    }
    cout << endl;
}
for (i = 0; i < N; i++) {
    delete[] A[i];
    delete[] B[i];
}
system("pause");
return 0;
}
c++
  • 2 个回答
  • 10 Views
Martin Hope
MiT
Asked: 2020-12-06 22:41:34 +0000 UTC

遍历文件中的行 (C#)

  • 1

有一个文件“io.bin”,其中包含:

ID: 1
Current date and time (time UTC): 05.12.2017 12:09:26
Global time: 00:10:00

ID: 2
Current date and time (time UTC): 06.12.2017 13:04:19
Global time: 00:05:30

ID: 3
...

有代码应该Current date and time (time UTC): 06.12.2017在 textBox 中找到并显示所有内容,直到下一个空格,即:

ID: 2
Current date and time (time UTC): 06.12.2017 13:04:19
Global time: 00:05:30

代码本身:

private static string getDate, setInfo = "info";    
...
private void selectDate_Click(object sender, EventArgs e)
{
    getDate = dateTimePicker1.Text;

    foreach (string line in File.ReadLines("io.bin"))
    {
        if (line.Contains("Current date and time (time UTC): " + getDate))
        {
            //тут надо реализовать хождение по строкам, Но как это сделать?
        }

        StreamReader streamReader = new StreamReader("io.bin");
        while (setInfo != null)
        {
            setInfo = streamReader.ReadLine();
            textBox1.Text += setInfo + " \r\n";
        }
    }
}

UPD:没有完成我的问题。您需要确保这部分代码与您的实现成为朋友

StreamReader streamReader = new StreamReader("io.bin");
        while (setInfo != null)
        {
            setInfo = streamReader.ReadLine();
            textBox1.Text += setInfo + " \r\n";
        }

也就是说:程序使用if (line.Contains("Current date and time (time UTC): " + getDate))line搜索行Current date and time (time UTC): 05.12.2017,跳过所有其他行,然后获取并复制整个块(从一个空间到另一个空间)。并显示在文本框中

ID: 2
Current date and time (time UTC): 06.12.2017 13:04:19
Global time: 00:05:30
c#
  • 2 个回答
  • 10 Views
Martin Hope
MiT
Asked: 2020-12-01 20:37:41 +0000 UTC

传递变量并使用它们 (C#)

  • 3

我想将变量(Swt,Srt)从设置表单传递到 Main,并使用它们。问题是当程序启动时,WorkDelay 和 RecreationDelay 被创建为空,以后不会改变。

public static int Swt, Srt;
public TimeSpan WorkDelay = TimeSpan.FromMinutes(Swt); //Work time in minutes
public TimeSpan WorkDelay = TimeSpan.FromMinutes(Swt); //Work time in minutes

主要形式

public partial class Main : Form
{
    private DateTime _globalTimeDate;

    public static int Swt, Srt;

    private DateTime _workExpiry;
    public TimeSpan WorkDelay = TimeSpan.FromMinutes(Swt); //Work time in minutes

    private DateTime _recreationExpiry;
    public TimeSpan RecreationDelay = TimeSpan.FromMinutes(Srt); // Recreation time in minutes

    public Main()
    {
        InitializeComponent();

        stop.Enabled = false;

        global.Text = @"Stoped";
        work.Text = @"Stoped";
        recreation.Text = @"Stoped";
    }

    private void globalTimer_Tick(object sender, EventArgs e)
    {
        long tick = DateTime.Now.Ticks - _globalTimeDate.Ticks;
        DateTime stopWatch = new DateTime();
        stopWatch = stopWatch.AddTicks(tick);
        global.Text = $@"{stopWatch:HH:mm:ss}";
    }

    private void workTimer_Tick(object sender, EventArgs e)
    {
        TimeSpan remaining = _workExpiry - DateTime.Now;
        work.Text = remaining.ToString("hh\\:mm\\:ss");

        if (work.Text == @"00:00:00")
        {
            workTimer.Stop();
            work.Text = @"Stoped, start recreation";

            _recreationExpiry = DateTime.Now.Add(RecreationDelay);
            recreationTimer.Start();
        }
    }

    private void recreationTimer_Tick(object sender, EventArgs e)
    {
        TimeSpan remaining = _recreationExpiry - DateTime.Now;
        recreation.Text = remaining.ToString("hh\\:mm\\:ss");

        if (recreation.Text == @"00:00:00")
        {
            recreationTimer.Stop();
            recreation.Text = @"Stoped, strart work";

            _workExpiry = DateTime.Now.Add(WorkDelay);
            workTimer.Start();
        }
    }

    private void start_Click(object sender, EventArgs e)
    {
        _globalTimeDate = DateTime.Now;
        _workExpiry = DateTime.Now.Add(WorkDelay);

        globalTimer.Start();
        workTimer.Start();

        start.Enabled = false;
        stop.Enabled = true;
    }

    private void stop_Click(object sender, EventArgs e)
    {
        globalTimer.Stop();
        workTimer.Stop();
        recreationTimer.Stop();

        work.Text = @"Stoped";
        recreation.Text = @"Stoped";

        stop.Enabled = false;
        start.Enabled = true;
    }

    private void exitToolStripMenuItem_Click(object sender, EventArgs e)
    {
        globalTimer.Stop();
        workTimer.Stop();
        recreationTimer.Stop();

        Application.Exit();
    }

    private void settingsToolStripMenuItem_Click(object sender, EventArgs e)
    {
        Settings settings = new Settings();
        settings.Show();
    }
}
}

设置表格

public partial class Settings : Form
{

    public Settings()
    {
        InitializeComponent();
    }

    private void buttonSet_Click(object sender, EventArgs e)
    {
        try
        {
            Main.Swt = (int) Convert.ToDouble(textBoxW.Text.Replace(',', '.'));
            Main.Srt = (int) Convert.ToDouble(textBoxR.Text.Replace(',', '.'));
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

        Close();
    }

    private void buttonReset_Click(object sender, EventArgs e)
    {
        Main.Swt = 0;
        Main.Srt = 0;
    }
}
}
c#
  • 1 个回答
  • 10 Views

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    我看不懂措辞

    • 1 个回答
  • Marko Smith

    请求的模块“del”不提供名为“default”的导出

    • 3 个回答
  • Marko Smith

    "!+tab" 在 HTML 的 vs 代码中不起作用

    • 5 个回答
  • Marko Smith

    我正在尝试解决“猜词”的问题。Python

    • 2 个回答
  • Marko Smith

    可以使用哪些命令将当前指针移动到指定的提交而不更改工作目录中的文件?

    • 1 个回答
  • Marko Smith

    Python解析野莓

    • 1 个回答
  • Marko Smith

    问题:“警告:检查最新版本的 pip 时出错。”

    • 2 个回答
  • Marko Smith

    帮助编写一个用值填充变量的循环。解决这个问题

    • 2 个回答
  • Marko Smith

    尽管依赖数组为空,但在渲染上调用了 2 次 useEffect

    • 2 个回答
  • Marko Smith

    数据不通过 Telegram.WebApp.sendData 发送

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5