Open DavidZhiXing opened 3 years ago
static private Storage.Storage storage = Storage.Storage.getStorage();
public static bool Auth(string login, string password)
{
foreach (Account account in storage.getState().accounts)
{
if (account.Login == login && account.Password == password)
{
GCHandle handle = GCHandle.Alloc(account);
IntPtr accPtr = (IntPtr) handle;
storage.dispatch(new Storage.Action.Action(
ActionType.SET_CURRENT_USER,
accPtr
));
handle.Free();
return true;
}
}
return false;
}
What will console output below? 不仔细比较容易出错
Process.Start("explorer.exe", $"/select, \"{Utils.Utilities.GetTempPath(NewReleaseZipFilename)}\"");
Type.IsInstanceOfType(Object) Method
public class Animal { }
public class Giraffe : Animal { }
public static class TypeOfExample
{
public static void Main()
{
object b = new Giraffe();
Console.WriteLine(b is Animal); // output: True
Console.WriteLine(b.GetType() == typeof(Animal)); // output: False
Console.WriteLine(b is Giraffe); // output: True
Console.WriteLine(b.GetType() == typeof(Giraffe)); // output: True
}
}
联调总结:
Summary of the joint commissioning.
string[] fruits = { "apple", "passionfruit", "banana", "mango",
"orange", "blueberry", "grape", "strawberry" };
IEnumerable<string> query =
fruits.TakeWhile((fruit, index) => fruit.Length >= index);
foreach (string fruit in query)
{
Console.WriteLine(fruit);
}
/*
This code produces the following output:
apple
passionfruit
banana
mango
orange
blueberry
*/
int[] amounts = { 5000, 2500, 9000, 8000,
6500, 4000, 1500, 5500 };
IEnumerable
foreach (int amount in query) { Console.WriteLine(amount); }
/* This code produces the following output:
4000 1500 5500 */
[SkipWhile](https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.skipwhile?view=net-5.0)
System.Collections.ArrayList fruits = new System.Collections.ArrayList(4);
fruits.Add("Mango");
fruits.Add("Orange");
fruits.Add("Apple");
fruits.Add(3.0);
fruits.Add("Banana");
// Apply OfType() to the ArrayList.
IEnumerable
Console.WriteLine("Elements of type 'string' are:"); foreach (string fruit in query1) { Console.WriteLine(fruit); }
// The following query shows that the standard query operators such as
// Where() can be applied to the ArrayList type after calling OfType().
IEnumerable
Console.WriteLine("\nThe following strings contain 'n':"); foreach (string fruit in query2) { Console.WriteLine(fruit); }
// This code produces the following output: // // Elements of type 'string' are: // Mango // Orange // Apple // Banana // // The following strings contain 'n': // Mango // Orange // Banana
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.Json;
namespace DesignPatterns.DynamicStrategy {
class Program {
static void Main(string[] args) {
/*
* If-else method
*/
string json = PrintOrder(Order.CreateNew(10), "Json");
string plain = PrintOrder(Order.CreateNew(10), "PlainText");
Console.WriteLine(json);
Console.WriteLine(plain);
Console.WriteLine(Environment.NewLine);
/*
* Dynamic
*/
string json2 = PrintOrder2(Order.CreateNew(10), "Json");
string plain2 = PrintOrder2(Order.CreateNew(10), "PlainText");
Console.WriteLine(json2);
Console.WriteLine(plain2);
}
/*
* If-Else Example
*/
public static string PrintOrder(Order order, string formatType) {
// Guard clauses left out for brevity
string result = string.Empty;
if (formatType == "Json") {
result = JsonSerializer.Serialize(order);
} else if (formatType == "PlainText") {
result = $"Id: {order.Id}\nSum: {order.Sum}";
} else {
result = "Unknown format";
}
return result;
}
/*
* Dynamic type discovery example
*/
private static string PrintOrder2(Order order, string formatType) {
// Dynamic type discovery process that builds a dictionary
Dictionary<string, Type> formatterTypes = Assembly
.GetExecutingAssembly()
.GetExportedTypes()
.Where(type => type.GetInterfaces().Contains(typeof(IOrderOutputStrategy)))
.ToDictionary(type => type.GetCustomAttribute<OutputFormatterName>().DisplayName);
Type chosenFormatter = formatterTypes[formatType];
// Try instantiate the formatter -- could have utilized a DI framework here instead
IOrderOutputStrategy strategy = Activator.CreateInstance(chosenFormatter) as IOrderOutputStrategy;
if (strategy is null) throw new InvalidOperationException("No valid formatter selected");
// Execute strategy method
string result = strategy.ConvertOrderToString(order);
return result;
}
}
public class Order {
private readonly string id;
private Order() {
this.id = Guid.NewGuid().ToString("D");
}
public string Id => id;
public int Sum { get; private set; }
public string GenerateOutput(IOrderOutputStrategy strategy) =>
strategy.ConvertOrderToString(this);
public static Order CreateNew(int orderSum) {
if (orderSum <= 0) throw new ArgumentException("sum must be a positive number");
var order = new Order {
Sum = orderSum,
};
return order;
}
}
[AttributeUsage(AttributeTargets.Class)]
public class OutputFormatterName : Attribute {
public OutputFormatterName(string displayName) {
DisplayName = displayName;
}
public string DisplayName { get; }
}
public interface IOrderOutputStrategy {
public string ConvertOrderToString(Order order);
}
[OutputFormatterName("Json")]
public class OrderJsonOutput : IOrderOutputStrategy {
public string ConvertOrderToString(Order order) {
string json = JsonSerializer.Serialize(order);
return json;
}
}
[OutputFormatterName("PlainText")]
public class OrderPlainTextOutput : IOrderOutputStrategy {
public string ConvertOrderToString(Order order) {
return $"Id: {order.Id}{Environment.NewLine}Sum: {order.Sum}";
}
}
}
public static T? GetProperty<T>(this ActionDescriptor actionDescriptor)
{
if (actionDescriptor == null)
{
throw new ArgumentNullException(nameof(actionDescriptor));
}
if (actionDescriptor.Properties.TryGetValue(typeof(T), out var value))
{
return (T?)value;
}
else
{
return default!;
}
}
internal unsafe sealed class BitHelper
{ // should not be serialized
private const byte MarkedBitFlag = 1;
private const byte IntSize = 32;
// m_length of underlying int array (not logical bit array)
private readonly int _length;
// ptr to stack alloc'd array of ints
private readonly int* _arrayPtr;
// array of ints
private readonly int[] _array;
// whether to operate on stack alloc'd or heap alloc'd array
private readonly bool _useStackAlloc;
/// <summary>
/// Instantiates a BitHelper with a heap alloc'd array of ints
/// </summary>
/// <param name="bitArray">int array to hold bits</param>
/// <param name="length">length of int array</param>
internal BitHelper(int* bitArrayPtr, int length)
{
_arrayPtr = bitArrayPtr;
_length = length;
_useStackAlloc = true;
}
/// <summary>
/// Instantiates a BitHelper with a heap alloc'd array of ints
/// </summary>
/// <param name="bitArray">int array to hold bits</param>
/// <param name="length">length of int array</param>
internal BitHelper(int[] bitArray, int length)
{
_array = bitArray;
_length = length;
}
/// <summary>
/// Mark bit at specified position
/// </summary>
/// <param name="bitPosition"></param>
internal void MarkBit(int bitPosition)
{
int bitArrayIndex = bitPosition / IntSize;
if (bitArrayIndex < _length && bitArrayIndex >= 0)
{
int flag = (MarkedBitFlag << (bitPosition % IntSize));
if (_useStackAlloc)
{
_arrayPtr[bitArrayIndex] |= flag;
}
else
{
_array[bitArrayIndex] |= flag;
}
}
}
/// <summary>
/// Is bit at specified position marked?
/// </summary>
/// <param name="bitPosition"></param>
/// <returns></returns>
internal bool IsMarked(int bitPosition)
{
int bitArrayIndex = bitPosition / IntSize;
if (bitArrayIndex < _length && bitArrayIndex >= 0)
{
int flag = (MarkedBitFlag << (bitPosition % IntSize));
if (_useStackAlloc)
{
return ((_arrayPtr[bitArrayIndex] & flag) != 0);
}
else
{
return ((_array[bitArrayIndex] & flag) != 0);
}
}
return false;
}
/// <summary>
/// How many ints must be allocated to represent n bits. Returns (n+31)/32, but
/// avoids overflow
/// </summary>
/// <param name="n"></param>
/// <returns></returns>
internal static int ToIntArrayLength(int n)
{
return n > 0 ? ((n - 1) / IntSize + 1) : 0;
}
}
}
Defer A defer statement defers the execution of a function until the surrounding function returns.
The deferred call's arguments are evaluated immediately, but the function call is not executed until the surrounding function returns.
package main
import "fmt"
func main() {
defer fmt.Println("world")
fmt.Println("hello")
}
hello world Program exited.
looks like finally in c sharp
Channels Channels are a typed conduit through which you can send and receive values with the channel operator, <-.
ch <- v // Send v to channel ch.
v := <-ch // Receive from ch, and
// assign value to v.
(The data flows in the direction of the arrow.)
Like maps and slices, channels must be created before use:
ch := make(chan int) By default, sends and receives block until the other side is ready. This allows goroutines to synchronize without explicit locks or condition variables.
The example code sums the numbers in a slice, distributing the work between two goroutines. Once both goroutines have completed their computation, it calculates the final result.
func sum(s []int, c chan int) {
sum := 0
for _, v := range s {
sum += v
}
c <- sum // send sum to c
}
func main() {
s := []int{7, 2, 8, -9, 4, 0}
c := make(chan int)
go sum(s[:len(s)/2], c)
go sum(s[len(s)/2:], c)
x, y := <-c, <-c // receive from c
fmt.Println(x, y, x+y)
}
namespace CoreWCF
{
public interface ICommunicationObject
{
CommunicationState State { get; }
event System.EventHandler Closed;
event System.EventHandler Closing;
event System.EventHandler Faulted;
event System.EventHandler Opened;
event System.EventHandler Opening;
void Abort();
System.Threading.Tasks.Task CloseAsync();
System.Threading.Tasks.Task CloseAsync(System.Threading.CancellationToken token);
System.Threading.Tasks.Task OpenAsync();
System.Threading.Tasks.Task OpenAsync(System.Threading.CancellationToken token);
//System.IAsyncResult BeginClose(System.AsyncCallback callback, object state); // No more APM
//System.IAsyncResult BeginClose(System.TimeSpan timeout, System.AsyncCallback callback, object state);
//System.IAsyncResult BeginOpen(System.AsyncCallback callback, object state);
//System.IAsyncResult BeginOpen(System.TimeSpan timeout, System.AsyncCallback callback, object state);
//void Close(); // No more sync
//void Close(System.TimeSpan timeout);
//void EndClose(System.IAsyncResult result); // No more APM
//void EndOpen(System.IAsyncResult result);
//void Open(); // No more sync
//void Open(System.TimeSpan timeout);
}
}
Good refactor for ICommunicationObject
Steps to build a fluent interface
Decorator is a structural pattern that allows adding new behaviors to objects dynamically by placing them inside special wrapper objects.
Extending a class is the first thing that comes to mind when you need to alter an object’s behavior. However, inheritance has several serious caveats that you need to be aware of.
Use the Decorator pattern when you need to be able to assign extra behaviors to objects at runtime without breaking the code that uses these objects.
XmlDocument document = new XmlDocument();
document.LoadXml("<People><Person Name='Nick' /><Person Name='Joe' /></People>");
[x] Loading XML From a File
XmlDocument document = new XmlDocument();
document.Load(@"C:\Path\To\xmldoc.xml");
// Or using an XmlReader/XmlTextReader
XmlReader reader = XmlReader.Create(@"C:\Path\To\xmldoc.xml");
document.Load(reader);
[x] Reading an XML Document using XPath (Using XmlDocument which allows us to edit)
XmlDocument document = new XmlDocument();
document.LoadXml("<People><Person Name='Nick' /><Person Name='Joe' /></People>");
// Select a single node XmlNode node = document.SelectSingleNode("/People/Person[@Name = 'Nick']");
// Select a list of nodes XmlNodeList nodes = document.SelectNodes("/People/Person");
- [x] Validating XML Documents against XSD Schemas
``` C#
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidateType = ValidationType.Schema;
settings.Schemas.Add("", pathToXsd); // targetNamespace, pathToXsd
XmlReader reader = XmlReader.Create(pathToXml, settings);
XmlDocument document = new XmlDocument();
try {
document.Load(reader);
} catch (XmlSchemaValidationException ex) { Trace.WriteLine(ex.Message); }
XmlWriter writer = XmlWriter.Create(pathToOutput);
writer.WriteStartDocument();
writer.WriteStartElement("People");
writer.WriteStartElement("Person"); writer.WriteAttributeString("Name", "Nick"); writer.WriteEndElement();
writer.WriteStartElement("Person"); writer.WriteStartAttribute("Name"); writer.WriteValue("Nick"); writer.WriteEndAttribute(); writer.WriteEndElement();
writer.WriteEndElement(); writer.WriteEndDocument();
writer.Flush();
- [x] XmlSerializer
```C#
using System;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
[XmlRootAttribute("PurchaseOrder", Namespace="http://www.cpandl.com",
IsNullable = false)]
public class PurchaseOrder
{
public Address ShipTo;
public string OrderDate;
/* The XmlArrayAttribute changes the XML element name
from the default of "OrderedItems" to "Items". */
[XmlArrayAttribute("Items")]
public OrderedItem[] OrderedItems;
public decimal SubTotal;
public decimal ShipCost;
public decimal TotalCost;
}
public class Address
{
[XmlAttribute]
public string Name;
public string Line1;
[XmlElementAttribute(IsNullable = false)]
public string City;
public string State;
public string Zip;
}
public class OrderedItem
{
public string ItemName;
public string Description;
public decimal UnitPrice;
public int Quantity;
public decimal LineTotal;
/* Calculate is a custom method that calculates the price per item,
and stores the value in a field. */
public void Calculate()
{
LineTotal = UnitPrice * Quantity;
}
}
public class Test
{
public static void Main()
{
// Read and write purchase orders.
Test t = new Test();
t.CreatePO("po.xml");
t.ReadPO("po.xml");
}
private void CreatePO(string filename)
{
// Create an instance of the XmlSerializer class;
// specify the type of object to serialize.
XmlSerializer serializer =
new XmlSerializer(typeof(PurchaseOrder));
TextWriter writer = new StreamWriter(filename);
PurchaseOrder po=new PurchaseOrder();
// Create an address to ship and bill to.
Address billAddress = new Address();
billAddress.Name = "Teresa Atkinson";
billAddress.Line1 = "1 Main St.";
billAddress.City = "AnyTown";
billAddress.State = "WA";
billAddress.Zip = "00000";
// Set ShipTo and BillTo to the same addressee.
po.ShipTo = billAddress;
po.OrderDate = System.DateTime.Now.ToLongDateString();
// Create an OrderedItem object.
OrderedItem i1 = new OrderedItem();
i1.ItemName = "Widget S";
i1.Description = "Small widget";
i1.UnitPrice = (decimal) 5.23;
i1.Quantity = 3;
i1.Calculate();
// Insert the item into the array.
OrderedItem [] items = {i1};
po.OrderedItems = items;
// Calculate the total cost.
decimal subTotal = new decimal();
foreach(OrderedItem oi in items)
{
subTotal += oi.LineTotal;
}
po.SubTotal = subTotal;
po.ShipCost = (decimal) 12.51;
po.TotalCost = po.SubTotal + po.ShipCost;
// Serialize the purchase order, and close the TextWriter.
serializer.Serialize(writer, po);
writer.Close();
}
protected void ReadPO(string filename)
{
XmlSerializer serializer = new XmlSerializer(typeof(PurchaseOrder));
/* If the XML document has been altered with unknown
nodes or attributes, handle them with the
UnknownNode and UnknownAttribute events.*/
serializer.UnknownNode+= new
XmlNodeEventHandler(serializer_UnknownNode);
serializer.UnknownAttribute+= new
XmlAttributeEventHandler(serializer_UnknownAttribute);
// A FileStream is needed to read the XML document.
FileStream fs = new FileStream(filename, FileMode.Open);
// Declare an object variable of the type to be deserialized.
PurchaseOrder po;
/* Use the Deserialize method to restore the object's state with
data from the XML document. */
po = (PurchaseOrder) serializer.Deserialize(fs);
// Read the order date.
Console.WriteLine ("OrderDate: " + po.OrderDate);
// Read the shipping address.
Address shipTo = po.ShipTo;
ReadAddress(shipTo, "Ship To:");
// Read the list of ordered items.
OrderedItem [] items = po.OrderedItems;
Console.WriteLine("Items to be shipped:");
foreach(OrderedItem oi in items)
{
Console.WriteLine("\t"+
oi.ItemName + "\t" +
oi.Description + "\t" +
oi.UnitPrice + "\t" +
oi.Quantity + "\t" +
oi.LineTotal);
}
// Read the subtotal, shipping cost, and total cost.
Console.WriteLine("\t\t\t\t\t Subtotal\t" + po.SubTotal);
Console.WriteLine("\t\t\t\t\t Shipping\t" + po.ShipCost);
Console.WriteLine("\t\t\t\t\t Total\t\t" + po.TotalCost);
}
protected void ReadAddress(Address a, string label)
{
// Read the fields of the Address object.
Console.WriteLine(label);
Console.WriteLine("\t"+ a.Name );
Console.WriteLine("\t" + a.Line1);
Console.WriteLine("\t" + a.City);
Console.WriteLine("\t" + a.State);
Console.WriteLine("\t" + a.Zip );
Console.WriteLine();
}
private void serializer_UnknownNode
(object sender, XmlNodeEventArgs e)
{
Console.WriteLine("Unknown Node:" + e.Name + "\t" + e.Text);
}
private void serializer_UnknownAttribute
(object sender, XmlAttributeEventArgs e)
{
System.Xml.XmlAttribute attr = e.Attr;
Console.WriteLine("Unknown attribute " +
attr.Name + "='" + attr.Value + "'");
}
}
// Load the XML file from our project directory containing the purchase orders
var filename = "PurchaseOrder.xml";
var currentDirectory = Directory.GetCurrentDirectory();
var purchaseOrderFilepath = Path.Combine(currentDirectory, filename);
XElement purchaseOrder = XElement.Load(purchaseOrderFilepath);
IEnumerable
///Create XML trees XElement contacts = new XElement("Contacts", new XElement("Contact", new XElement("Name", "Patrick Hines"), new XElement("Phone", "206-555-0144", new XAttribute("Type", "Home")), new XElement("phone", "425-555-0145", new XAttribute("Type", "Work")), new XElement("Address", new XElement("Street1", "123 Main St"), new XElement("City", "Mercer Island"), new XElement("State", "WA"), new XElement("Postal", "68042") ) ) );
XElement root = new XElement("Root",
new XElement("Child", "child content")
);
root.Save("Root.xml");
string str = File.ReadAllText("Root.xml");
Console.WriteLine(str);
<?xml version="1.0" encoding="utf-8"?>
<Root>
<Child>child content</Child>
</Root>
What I can do right now, today?
Why I need to do these stuff?
What the one thing I want to finish today?
And what I should do to finish it?
Nice interview score template from @ThaddeusJiang:
Total: 1~5 下面各项得分的平均分
Experience: 1~5 过往项目的客户群(ToB or ToC)、项目规模、项目中担当的角色、是否有突出贡献等等
Skill: 1~5 开发基础、设计能力、能否攻克中大型开发难题,能否担当 full stack 任务等等
Culture: 1~5 git 开发流程、测试开发流程、CI/CD 开发流程、云开发流程等等
Personality: 1~5 成长期还是成熟的开发者,是否有潜力,是否能胜任我们项目,是否匹配我们公司文化和style等等
Communication: 1~5 是否可以快速理解问题,是否可以清楚表达自己,是否积极交流,是否让其他人不舒服等等
Summary: 基于上面打分,给予简单的评语,让 HR 可以判断是否采用,或者以何种薪资采用
In computer science, compare-and-swap (CAS) is an atomic instruction used in multithreading to achieve synchronization. The ABA problem occurs when multiple threads (or processes) accessing shared data interleave. Below is the sequence of events that will result in the ABA problem:
博客的作用:
WPF性能优化,routine: 虚拟化技术 --> 线程模型 --> 渲染 --> 资源管理-->硬件加速 --> 多线程UI(browser)
def longestValidParentheses(s)
return 0 if s.length < 2
stack = []
max = 0
s.each_char.with_index do |c, i|
if c == '('
stack.push(i)
else
if stack.length > 0
stack.pop
max = [max, i - stack.last].max
else
stack.push(i)
end
end
end
max
end
# test
puts longestValidParentheses('(()')
puts longestValidParentheses(')()())')
puts longestValidParentheses(')()())')
output:
$ruby main.rb
2
main.rb:11:in `-': nil can't be coerced into Integer (TypeError)
from main.rb:11:in `block in longestValidParentheses'
from main.rb:5:in `each_char'
from main.rb:5:in `with_index'
from main.rb:5:in `longestValidParentheses'
from main.rb:22:in `<main>'
how about csi fsi?
git查看指定的 commit id
git log <commit id>
所谓SOLID原则最终变成的依赖会不会是一颗完美的树,隔离级别只有父节点能访问子节点
重点看一下ZoomCanvas如何使用
打乱一个数组的顺序
public static T[] GetRandomElements<T>(T[] array)
{
return array.OrderBy(x => Guid.NewGuid()).ToArray();
}
Span
Fatal Error: Memory usage limit was exceeded
using System.Threading;
public class Program
{
class Person
{
long[] personArray = new long[1000000];
~Person()
{
Thread.Sleep(1);
}
}
public static void Main(string[] args)
{
for (long i = 0; i < 100000000000; i++)
{
Person p = new Person();
}
}
}
ElementAt
string[] names =
{ "Hartono, Tommy", "Adams, Terry", "Andersen, Henriette Thaulow",
"Hedlund, Magnus", "Ito, Shu" };
Random random = new Random(DateTime.Now.Millisecond);
string name = names.ElementAt(random.Next(0, names.Length));
Console.WriteLine("The name chosen at random is '{0}'.", name);
/*
This code produces output similar to the following:
The name chosen at random is 'Ito, Shu'.
*/
python cv2 learning on youtube
namespace System
{
public readonly struct Index
{
public Index(int value, bool fromEnd);
}
}
int System.Index.GetOffset(int length);
namespace System
{
public readonly struct Range
{
public Range(System.Index start, System.Index end);
public static Range StartAt(System.Index start);
public static Range EndAt(System.Index end);
public static Range All { get; }
}
}
namespace System.Runtime.CompilerServices
{
public static class RuntimeHelpers
{
public static T[] GetSubArray<T>(T[] array, System.Range range);
}
}
System.Index operator ^(int fromEnd);
System.Range operator ..(Index start = 0, Index end = ^0);
string message = $"The usage policy for {safetyScore} is {
safetyScore switch
{
> 90 => "Unlimited usage",
> 80 => "General usage, with daily safety check",
> 70 => "Issues must be addressed within 1 week",
> 50 => "Issues must be addressed within 1 day",
_ => "Issues must be addressed before continued use",
}
}";
perfect, we don't need case: we don't need break; we don't need default, symbol is perfect.
void Method(string name!!)
{
// ...
}
nice param null check