GraphMindStudio工作流标准函数
【代码】GraphMindStudio运行函数。
·
public static class Arithmetics
{
public static Func<Dictionary<string, object>> getfunc = () => { return GetValueFrame<Dictionary<string, object>>(globalvariableset.dataStorage, "ComGenerate_functionMap"); };
public static Func<object, object> Int = (obj) => Convert.ToInt32(obj);
public static Func<object, object> Float = (obj) => Convert.ToSingle(obj);
public static Func<object, object> Double = (obj) => Convert.ToDouble(obj);
public static Func<object, object> String = (obj) => obj.ToString();
public static Func<object, object> QuaternionConvert = (obj) =>
{
if (obj is Quaternion q) return q;
var arr = ParseToFloatArray(obj, 4);
return new Quaternion(arr[0], arr[1], arr[2], arr[3]);
};
public static Func<object, object> Vector3Convert = (obj) =>
{
if (obj is Vector3 v) return v;
var arr = ParseToFloatArray(obj, 3);
return new Vector3(arr[0], arr[1], arr[2]);
};
public static Func<object, object> Vector2Convert = (obj) =>
{
if (obj is Vector2 v) return v;
var arr = ParseToFloatArray(obj, 2);
return new Vector2(arr[0], arr[1]);
};
public static Func<object, object> StringToDictionary = (obj) =>
{
if (obj is Dictionary<string, object> dic) return dic;
var input = obj?.ToString() ?? "";
var kvs = ParseKeyValuePairs(input);
DebugPrint(kvs, false, "kvs");
return kvs;
};
public static readonly Func<List<object>, List<string>> ConvertToStringList = (objects) =>
{
return objects.Select(obj => obj?.ToString() ?? string.Empty).ToList();
};
public static readonly Func<string, bool> StringToBool = str =>
!string.IsNullOrWhiteSpace(str) &&
new[] { "true", "1", "yes", "on", "y", "t" }
.Contains(str.Trim().ToLowerInvariant());
public static Func<object, object> Plus = (obj) =>
{
List<object> list = (List<object>)obj;
// 直接获取两个值(可能是数字或字符串)
object value1 = list[0];
object value2 = list[1];
// 转换为字符串
string str1 = Convert.ToString(value1);
string str2 = Convert.ToString(value2);
// 尝试解析为数字并相加
if (double.TryParse(str1, out double d1) &&
double.TryParse(str2, out double d2))
{
return (d1 + d2);
}
// 返回错误信息(移除了对 list[2] 的引用)
return $"Invalid input\n" +
$"value1: {list[0]} ({list[0].GetType()})\n" +
$"value2: {list[1]} ({list[1].GetType()})";
};
public static Func<object, object> RandomIntFunc = obj => RandomInRange<int>(obj);
public static Func<object, object> RandomFloatFunc = obj => RandomInRange<float>(obj);
public static Func<object, object> RandomDoubleFunc = obj => RandomInRange<double>(obj);
public static T RandomInRange<T>(object obj)
{
if (obj is List<object> list && list.Count >= 2)
{
double min = Convert.ToDouble(list[0]);
double max = Convert.ToDouble(list[1]);
var rand = new System.Random();
if (typeof(T) == typeof(int))
{
return (T)(object)rand.Next((int)min, (int)max);
}
else if (typeof(T) == typeof(float))
{
return (T)(object)((float)(rand.NextDouble() * (max - min) + min));
}
else if (typeof(T) == typeof(double))
{
return (T)(object)(rand.NextDouble() * (max - min) + min);
}
}
if (typeof(T) == typeof(int)) return (T)(object)0;
if (typeof(T) == typeof(float)) return (T)(object)0f;
if (typeof(T) == typeof(double)) return (T)(object)0.0;
return default;
}
public static Func<object, object> SortTimestampsFunc = obj =>
{
var list = Converter.ConvertValue<List<object>>(obj);
bool reverse = false;
if (list[^1] is string s && s.Equals("desc", StringComparison.OrdinalIgnoreCase))
{
reverse = true;
list = list.Take(list.Count - 1).ToList();
}
else if (list[^1] is bool b && b == false)
{
reverse = true;
list = list.Take(list.Count - 1).ToList();
}
var liststr = Converter.ConvertValue<List<string>>(list);
var indexed = liststr
.Select((ts, idx) => new { Index = idx, Date = DateTime.ParseExact(ts, "yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture) })
.ToList();
var sorted = indexed.OrderBy(x => x.Date).ToList();
if (reverse)
sorted.Reverse();
var orderMap = sorted.Select(x => x.Index).ToList();
return orderMap;
};
public static Func<Dictionary<string, object>, string, string> getstr = (dic, key) =>
{
var p = GetPathGetValue(dic, key);
if (p is string s)
return s;
if (p is IEnumerable ie && !(p is string))
return $"Show:{PrintCollection(ie.Cast<object>())}";
return p?.ToString() ?? string.Empty;
};
public static Func<int, string, List<string>> BuildRepeatedStringListFunc = (count, input) =>
{
if (string.IsNullOrEmpty(input) || count <= 0)
return new List<string>();
return Enumerable.Repeat(input, count).ToList();
};
/// <summary>
/// 通用 LINQ 二维表格提取方法
/// </summary>
/// <typeparam name="TCell">单元格类型</typeparam>
/// <typeparam name="TResult">返回结果类型</typeparam>
/// <param name="rows">行数</param>
/// <param name="columns">列数</param>
/// <param name="getCell">获取单元格的方法 (row, col) => cell</param>
/// <param name="selector">处理单元格的方法 (cell, row, col) => TResult</param>
/// <returns>二维 TResult 数组</returns>
public static TResult[,] ExtractTableByLinq<TCell, TResult>(
int rows,
int columns,
Func<int, int, TCell> getCell,
Func<TCell, int, int, TResult> selector)
{
return Enumerable.Range(0, rows)
.Select(row => Enumerable.Range(0, columns)
.Select(col => selector(getCell(row, col), row, col))
.ToArray())
.ToArray()
.To2DArray();
}
/// <summary>
/// 通用方法:将二维表格数据转换为参数字典集合,并可自定义过滤条件
/// </summary>
/// <typeparam name="TCell">单元格类型</typeparam>
/// <param name="rows">行数</param>
/// <param name="columns">列数</param>
/// <param name="getCell">获取单元格内容的委托</param>
/// <param name="columnNames">列名集合</param>
/// <param name="rowFilter">行过滤条件(可选)</param>
/// <returns>每行的参数字典集合</returns>
public static List<Dictionary<string, object>> TableRowsToParamList<TCell>(
int rows,
int columns,
Func<int, int, TCell> getCell,
List<string> columnNames,
Func<Dictionary<string, object>, bool> rowFilter = null)
{
var paramList = Enumerable.Range(0, rows)
.Select(r =>
{
var param = columnNames
.Select((col, c) => new { col, cellText = getCell(r, c)?.ToString() ?? string.Empty })
.ToDictionary(x => x.col, x => (object)x.cellText);
return param;
})
.Where(param => rowFilter == null || rowFilter(param))
.ToList();
return paramList;
}
public static Func<int, object, List<object>> CreateObjectList = (int count, object obj) =>
{
return Enumerable.Repeat(obj, count).ToList();
};
public static Func<object, object> DirectstrOut_ = (obj) => { if (obj is string str) return str; else return null; };
public static Func<object, object> StandliseCode_ = (obj) => { if (obj is string str) return StandliseCode(str); else return null; };
public static Func<object, object> MergePrefix_ = (obj) =>
{
List<object> list = ParameterCheck(obj, "MergePrefix_", 1); // 最小参数数量改为1
if (list.Count < 2)
throw new ArgumentException($"MergePrefix_ 需要至少2个参数(前缀和至少一个字符串),实际收到: {list.Count}");
string prefix = StringCheck(list[0], "MergePrefix_第一个参数");
// 收集所有字符串参数
List<string> allStrings = new List<string>();
for (int i = 1; i < list.Count; i++)
{
switch (list[i])
{
case List<string> stringList:
allStrings.AddRange(stringList);
break;
case string singleString:
allStrings.Add(singleString);
break;
case IEnumerable<string> stringEnumerable:
allStrings.AddRange(stringEnumerable);
break;
default:
throw new ArgumentException($"MergePrefix_ 第{i + 1}个参数类型不匹配。期望: List<string>、IEnumerable<string> 或 string,实际: {list[i]?.GetType().Name ?? "null"}");
}
}
return MergeStrings(prefix, allStrings);
};
public static Func<object, object> CompileCheck_ = (obj) =>
{
var result = new List<object>();
List<object> list = TCheckWithDescription<List<object>>(obj, "DynamicExcute_代码");
foreach (var item in list)
{
string code = TCheckWithDescription<string>(item, "DynamicExcute_代码");
CompilationHelper.ValidateCodeBeforeCompilation(code);
}
return $"预编译没有语法错误,{string.Join("", list)}";
};
public static Func<object, Task<object>> DynamicExcute_ = async (obj) =>
{
var result = new List<object>();
List<object> list = TCheckWithDescription<List<object>>(obj, "DynamicExcute_代码");
foreach (var item in list)
{
string code = TCheckWithDescription<string>(item, "DynamicExcute_代码");
code = RemoveComments(code);
//code = RewritingMethod(code);
DebugPrint(code, false, "RewritingMethod");
code = await Task.Run(() => SortStatement(code));
DebugPrint(code, false, "SortStatementED");
result.Add(code);
}
if (result == null)
throw new InvalidOperationException("动态构建操作失败");
DebugPrint(result);
return result;
};
public static Func<object, Task<object>> CmopileFunction_ = async (obj) =>
{
List<object> list = TCheckWithDescription<List<object>>(obj, "DynamicExcute_输入");
//Dictionary<string, (string code, string dictionaryName)> result = new();
//foreach (var code in list)
//{
// string code_ = TCheckWithDescription<string>(code, "CombineFunction_代码");
//string standardizedCode = StandliseCode(code_);
//var funcs = await RewriteFunctionClasses(standardizedCode, dic);
// DebugPrint(funcs, false, "CombineFunction_funcs");
// result.AddRange(funcs);
// if (funcs == null)
// throw new InvalidOperationException("重写函数类返回null");
// if (funcs.Count == 0)
// throw new InvalidOperationException("重写函数类返回空字典");
// DictionaryMerger.BatchMergeDictionaries(funcs, dic).GetAwaiter().GetResult();
//}
List<Assembly> assemblys = new();
foreach (var code in list)
{
string code_ = TCheckWithDescription<string>(code, "CombineFunction_代码");
DebugPrint(code_, false, "CombineFunction_代码");
var assembly = await CompileAssembly(code_);
assemblys.Add(assembly);
DebugPrint(assembly);
var analysis = Analyzer.AssemblyAnalyzer.AnalyzeMethods(assembly);
DebugPrint(analysis, true, "analysisassembly");
var internalSignatures = MethodSignatureExtractor.ExtractMethodSignatures(assembly: assembly);
DebugPrint(internalSignatures);
var fields = FieldSignatureExtractor.ExtractFieldSignatures(
assembly: assembly,
filter: field => field.FieldType == typeof(Func<object, object>));
DebugPrint(fields);
FieldSignatureToFuncConverter.PopulateDictionaryWithDetails(fields, dic);
//var funcs = MethodSignatureToFuncConverter.ConvertToFuncList(internalSignatures);
MethodSignatureToFuncConverter.PopulateDictionary(internalSignatures, dic);
//string detailedOutput = MethodSignaturePrinter.GenerateMethodSignaturesString(internalSignatures);
//DebugPrint(detailedOutput);
}
UnityEngine.Debug.Log("CombineFunction_ResultRun");
return assemblys;
};
public static Func<object, Task<object>> PipelineRun_ = async (obj) =>
{
List<object> list = ParameterCheck(obj, "PipelineRun_", 1);
string InvokeJson = TCheckWithDescription<string>(list[0], "PipelineRun_调用");
FuncPipelineParameters funcPipelineParameters = JsonConvert.DeserializeObject<FuncPipelineParameters>(InvokeJson);
funcPipelineParameters.FunctionMap = dic;
await PipelineRunAsync(funcPipelineParameters);
return null;
};
public static Func<object, Task<object>> WebInvoke_ = async (obj) =>
{
if (localswitchbool) return $"WebInvoke_运行\n参数:(({PrintCollection(obj)}))";
List<object> list = ParameterCheck(obj, "WebInvoke_", 2);
string target = StringCheck(list[0], "WebInvoke_target参数");
string prompt = StringCheck(list[1], "WebInvoke_prompt参数");
string extramodel = "text";
bool skip = false;
DebugPrint("WebInvoke_RUN");
if (list.Count > 2)
extramodel = StringCheck(list[2], "WebInvoke_extramodel参数");
if (list.Count > 3)
skip = StringToBool(StringCheck(list[3], "WebInvoke_extramodel参数"));
return await WebHtmlCoze.ExtractFirstHtmlContentAsync(target, extramodel, RemoveNewLines(ExtractString(prompt)), skip);
};
public static Func<object, Task<object>> DonloadPhoto_ = async (obj) =>
{
DebugPrint("DonloadPhoto_Run");
if (localswitchbool) return $"DonloadPhoto_运行\n参数:{PrintCollection(obj)}";
List<object> list = ParameterCheck(obj, "DonloadPhoto_", 3);
string imgurl = StringCheck(list[0], "WebInvoke_第一个参数");
string savedirectory = StringCheck(list[1], "WebInvoke_第二个参数");
string filename = StringCheck(list[2], "WebInvoke_第二个参数");
//savedirectory = CreateTodayFolder(savedirectory);
var donloadpath = await DownLoader.QuickImageDownloader.QuickDownloadWithNameAsync(imgurl, savedirectory, filename);
DebugPrint("DonloadPhoto_Run2");
return $"图像下载成功:{donloadpath}";
};
public static Func<object, Task<object>> Dispatch_ = async (obj) =>
{
if (localswitchbool) return $"FileProcessDispatcher运行\n参数:{PrintCollection(obj)}";
List<object> list = ParameterCheck(obj, "FileProcessDispatcher", 2);
string methodName = TCheckWithDescription<string>(list[0], "FileProcessDispatcher方法名");
object parameters = list[1];
return methodName.ToLower() switch
{
"savetofileasync" => await SaveToFileAsyncWrapper(parameters),
"fileread" => FileReadWrapper(parameters),
"renamefolder" => RenameFolderWrapper(parameters),
_ => throw new ArgumentException($"未知的FileProcess方法: {methodName}")
};
};
public static Func<object, object> DataValueUpdate_ = (obj) =>
{
List<object> list = ParameterCheck(obj, "DataBaseUpdate_", 3);
var tableName = TCheckWithDescription<string>(list[0], "tableName");
var primaryKey = TCheckWithDescription<string>(list[1], "primaryKey");
var paramList = TCheckWithDescription<Dictionary<string, object>>(list[2], "paramList");
if (string.IsNullOrEmpty(tableName))
throw new ArgumentException("表名不能为空", nameof(tableName));
if (string.IsNullOrEmpty(primaryKey))
throw new ArgumentException("主键名不能为空", nameof(primaryKey));
if (paramList == null || paramList.Count == 0)
return "数据库储存失败";
SqlProcess.SaveToDataBase(tableName, primaryKey, new() { paramList });
return "数据储存成功";
};
public static Func<object, object> DataValueRead_ = (obj) =>
{
List<object> list = ParameterCheck(obj, "DataBaseUpdate_", 3);
var tableName = TCheckWithDescription<string>(list[0], "tableName");
var primaryKey = TCheckWithDescription<string>(list[1], "primaryKey");
var primaryKeyValue = TCheckWithDescription<string>(list[2], "primaryKeyValue");
if (string.IsNullOrEmpty(tableName))
throw new ArgumentException("表名不能为空", nameof(tableName));
if (string.IsNullOrEmpty(primaryKey))
throw new ArgumentException("主键名不能为空", nameof(primaryKey));
var result = SqlProcess.ReadFromDataBase(tableName, primaryKey, primaryKeyValue);
DebugPrint(result, false, "DataValueRead_");
return result;
};
public static Func<object, object> ToListDictionary_ = (obj) =>
{
// 参数检查
List<object> list = ParameterCheck(obj, "ToListDictionary", 2); // 至少需要2个元素(一对键值)
// 检查元素数量是否为偶数
if (list.Count % 2 != 0)
throw new ArgumentException("参数列表必须包含偶数个元素(键值对)");
var dic = new Dictionary<string, object>();
// 每次处理两个元素(键和值)
for (int i = 0; i < list.Count; i += 2)
{
var key = TCheckWithDescription<string>(list[i], "key");
var value = list[i + 1]; // 值可以是任意object类型
// 检查键是否重复
if (dic.ContainsKey(key))
throw new ArgumentException($"字典中已存在相同的键: {key}");
dic.Add(key, value);
}
DebugPrint(dic, true, "TestDIC");
return dic;
};
/// <summary>
/// 将二维 jagged 数组转换为真正的二维数组
/// </summary>
public static TResult[,] To2DArray<TResult>(this TResult[][] source)
{
int rows = source.Length;
int cols = rows > 0 ? source[0].Length : 0;
var result = new TResult[rows, cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
result[i, j] = source[i][j];
return result;
}
public static Func<Dictionary<TKey, TValue>, Dictionary<TKey, TValue>, Dictionary<TKey, TValue>> MergeDictionaries<TKey, TValue>(
Func<TValue, TValue, TValue> conflictResolver)
{
if (conflictResolver == null) throw new ArgumentNullException(nameof(conflictResolver));
return (dictionary1, dictionary2) =>
{
if (dictionary1 == null) throw new ArgumentNullException(nameof(dictionary1));
if (dictionary2 == null) throw new ArgumentNullException(nameof(dictionary2));
var mergedDictionary = new Dictionary<TKey, TValue>(dictionary1);
foreach (var kvp in dictionary2)
{
if (mergedDictionary.ContainsKey(kvp.Key))
{
// 处理键冲突
mergedDictionary[kvp.Key] = conflictResolver(mergedDictionary[kvp.Key], kvp.Value);
}
else
{
// 添加新键值对
mergedDictionary[kvp.Key] = kvp.Value;
}
}
return mergedDictionary;
};
}
public static Func<object, object, object> conflictResolver = (value1, value2) =>
{
UnityEngine.Debug.Log($"键冲突: 保留第一个字典的值。冲突键值对: {value1} (保留) vs {value2} (丢弃)");
return value1; // 保留第一个字典的值
};
// 通用的路径组合方法
public static Func<string, string> CreatePathCombiner(Func<string> basePathGetter)
{
return relativePath => Path.Combine(basePathGetter(), relativePath);
}
// 预定义的常用路径组合器
public static readonly Func<string, string> StreamingAssetsPath =
CreatePathCombiner(() => Application.streamingAssetsPath);
public static readonly Func<string, string> PersistentDataPath =
CreatePathCombiner(() => Application.persistentDataPath);
public static readonly Func<string, string> DataPath =
CreatePathCombiner(() => Application.dataPath);
public static readonly Func<string, string> TemporaryCachePath =
CreatePathCombiner(() => Application.temporaryCachePath);
}
鲲鹏昇腾开发者社区是面向全社会开放的“联接全球计算开发者,聚合华为+生态”的社区,内容涵盖鲲鹏、昇腾资源,帮助开发者快速获取所需的知识、经验、软件、工具、算力,支撑开发者易学、好用、成功,成为核心开发者。
更多推荐



所有评论(0)