public Image3D(string workingDirectory, IList<Image2D> images) { this.WorkingDirectory = workingDirectory; this.OriginalSlices = images.ToArray(); this.Slices = images.ToArray(); }
public DataTable GetQueryResult(string Connection, IList<string> lstPdLine, IList<string> Model, bool IsWithoutShift, string ModelCategory) { string methodName = MethodBase.GetCurrentMethod().Name; BaseLog.LoggingBegin(logger, methodName); try { string SQLText = ""; StringBuilder sb = new StringBuilder(); sb.AppendLine("SELECT DISTINCT a.ProductID,a.CUSTSN,b.InfoValue as 'IMGCL',c.Line "); sb.AppendLine("FROM Product a (NOLOCK) "); sb.AppendLine("INNER JOIN ProductInfo b (NOLOCK) ON b.ProductID = a.ProductID "); sb.AppendLine("INNER JOIN ProductStatus c (NOLOCK) ON c.ProductID = a.ProductID "); sb.AppendLine("WHERE b.InfoType='IMGCL' "); if (lstPdLine.Count > 0) { if (IsWithoutShift) { sb.AppendFormat("AND SUBSTRING(c.Line,1,1) in ('{0}') ", string.Join("','", lstPdLine.ToArray())); } else { sb.AppendFormat("AND c.Line in ('{0}') ", string.Join("','", lstPdLine.ToArray())); } } if (Model.Count > 0) { sb.AppendFormat("AND a.ProductID in ('{0}') ", string.Join("','", Model.ToArray())); } if (ModelCategory != "") { sb.AppendFormat(" AND dbo.CheckModelCategory(a.Model,'" + ModelCategory + "')='Y' "); } SQLText = sb.ToString(); return SQLHelper.ExecuteDataFill(Connection, System.Data.CommandType.Text, SQLText ); } catch (Exception e) { BaseLog.LoggingError(logger, MethodBase.GetCurrentMethod(), e); throw; } finally { BaseLog.LoggingEnd(logger, methodName); } }
public void Serialize(IList<Employee> employees) { using (var stream = new FileStream(FilePath, FileMode.Truncate)) { serializer.Serialize(stream, employees.ToArray()); } }
public static void ExtractConfigfileFromJar(string reefJar, IList<string> configFiles, string dropFolder) { var configFileNames = string.Join(" ", configFiles.ToArray()); var startInfo = new ProcessStartInfo { FileName = GetJarBinary(), Arguments = @"xf " + reefJar + " " + configFileNames, RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true }; LOGGER.Log(Level.Info, "extracting files from jar file with \r\n" + startInfo.FileName + "\r\n" + startInfo.Arguments); using (var process = Process.Start(startInfo)) { var outReader = process.StandardOutput; var errorReader = process.StandardError; var output = outReader.ReadToEnd(); var error = errorReader.ReadToEnd(); process.WaitForExit(); if (process.ExitCode != 0) { throw new InvalidOperationException("Failed to extract files from jar file with stdout :" + output + "and stderr:" + error); } } LOGGER.Log(Level.Info, "files are extracted."); }
public bool SignalExternalCommandLineArgs(IList<string> args) { // handle command line arguments of second instance HandleArguments(args.ToArray()); return true; }
public ImportStatement(Token importToken, IList<Token> importChain, IList<Token> fromChain, Token asValue) : base(importToken) { this.ImportChain = importChain.ToArray(); this.FromChain = fromChain == null ? null : fromChain.ToArray(); this.AsValue = asValue; }
public DataTable GetPdLine(string customer, IList<string> lstProcess, string DBConnection) { string methodName = MethodBase.GetCurrentMethod().Name; BaseLog.LoggingBegin(logger, methodName); try { string SQLText = @" SELECT Line,Descr FROM Line (NOLOCK) WHERE CustomerID=@customer "; // AND Stage IN (@process) ORDER BY 1"; SQLText += string.Format(" AND Stage IN ('{0}')", string.Join("','", lstProcess.ToArray())); SQLText += " ORDER BY 1"; return SQLHelper.ExecuteDataFill(DBConnection, System.Data.CommandType.Text, SQLText, SQLHelper.CreateSqlParameter("@customer", 32, customer, ParameterDirection.Input)); //SQLHelper.CreateSqlParameter("@process", 32, process, ParameterDirection.Input)); } catch (Exception e) { BaseLog.LoggingError(logger, MethodBase.GetCurrentMethod(), e); throw; } finally { BaseLog.LoggingEnd(logger, methodName); } }
public FunctionCall(Expression root, Token parenToken, IList<Expression> args, Executable owner) : base(root.FirstToken, owner) { this.Root = root; this.ParenToken = parenToken; this.Args = args.ToArray(); }
public MultilayerPerceptron(int numInputs, int numOutputs, IList<int> hiddenLayerSizes) { if (numInputs <= 0) throw new NeuralNetworkException($"Argument {nameof(numInputs)} must be positive; was {numInputs}."); if (numOutputs <= 0) throw new NeuralNetworkException($"Argument {nameof(numOutputs)} must be positive; was {numOutputs}."); if (hiddenLayerSizes == null || !hiddenLayerSizes.Any()) throw new NeuralNetworkException($"Argument {nameof(hiddenLayerSizes)} cannot be null or empty."); if (hiddenLayerSizes.Any(h => h <= 0)) { var badSize = hiddenLayerSizes.First(h => h <= 0); var index = hiddenLayerSizes.IndexOf(badSize); throw new NeuralNetworkException($"Argument {nameof(hiddenLayerSizes)} must contain only positive " + $"values; was {badSize} at index {index}."); } NumInputs = numInputs; NumOutputs = numOutputs; HiddenLayerSizes = hiddenLayerSizes.ToArray(); Weights = new double[hiddenLayerSizes.Count + 1][]; for (var i = 0; i < hiddenLayerSizes.Count + 1; i++) { if (i == 0) Weights[i] = new double[(numInputs + 1) * hiddenLayerSizes[0]]; else if (i < hiddenLayerSizes.Count) Weights[i] = new double[(hiddenLayerSizes[i-1] + 1) * hiddenLayerSizes[i]]; else Weights[i] = new double[(hiddenLayerSizes[hiddenLayerSizes.Count - 1] + 1) * numOutputs]; } }
public PathRecord(IVertex target, double weight, IList<IEdge> edgeTracks) { Target = target; Weight = weight; EdgeTracks = edgeTracks.ToArray(); ParseVertexTracks(edgeTracks); }
public ForEachLoop(Token forToken, Token iterationVariable, Expression iterationExpression, IList<Executable> code, Executable owner) : base(forToken, owner) { this.IterationVariable = iterationVariable; this.IterationExpression = iterationExpression; this.Code = code.ToArray(); }
/// <summary> /// Converts the given object to the type of this converter, using the specified context and culture /// information. /// </summary> /// <returns> /// An <see cref="T:System.Object"/> that represents the converted value. /// </returns> /// <param name="culture"> /// The <see cref="T:System.Globalization.CultureInfo"/> to use as the current culture. /// </param> /// <param name="value">The <see cref="T:System.Object"/> to convert. </param> /// <param name="propertyType">The property type that the converter will convert to.</param> /// <exception cref="T:System.NotSupportedException">The conversion cannot be performed.</exception> public override object ConvertFrom(CultureInfo culture, object value, Type propertyType) { object result = base.ConvertFrom(culture, value, propertyType); IList <T> list = result as IList <T>; return(list?.ToArray() ?? result); }
/// <summary> /// Decompresses a file. /// </summary> public static byte[] Decompress( IList<byte> bytes ) { List<byte> result = new List<byte>( 1024 * 1024 ); using( GZipStream stream = new GZipStream( new MemoryStream( bytes.ToArray() ), CompressionMode.Decompress, false ) ) { byte[] buffer = new byte[2048]; int b = 0; while( true ) { b = stream.Read( buffer, 0, 2048 ); if( b < 2048 ) break; else result.AddRange( buffer ); } if( b > 0 ) { result.AddRange( buffer.Sub( 0, b - 1 ) ); } } return result.ToArray(); }
public static Tuple<int, int> FindTwoSum(IList<int> list, int sum) { var newList = list.ToArray(); var pairs = (from number in list where newList.Contains(sum - number) select Tuple.Create(Array.IndexOf(newList, number), Array.LastIndexOf(newList, sum - number))).ToList(); return pairs.Count > 0 ? pairs[0] : null; }
public Annotation(Token firstToken, Token typeToken, IList<Expression> args) { this.FirstToken = firstToken; this.TypeToken = typeToken; this.Type = typeToken.Value; this.Args = args.ToArray(); }
internal string GetDeleteSyntax(IInfluxRetentionPolicy rp = null, IList <string> whereClause = null) { if (!String.IsNullOrWhiteSpace(Name) && !String.IsNullOrWhiteSpace(Name)) { string whereClauseText = ""; if (whereClause != null) { whereClauseText = $" where { String.Join(" and ", whereClause?.ToArray())}"; } if (rp != null) { return($"DELETE from \"{rp.Name}\".\"{Name}\" {whereClauseText}"); } else { return($"DELETE from \"{Name}\" {whereClauseText}"); } } else if (String.IsNullOrWhiteSpace(Name)) { throw new ArgumentException("Measurement name is not set"); } return(null); }
/// <summary> /// Initializes a new instance of the <see cref="SemanticVersion"/> class. /// </summary> /// <param name="major">Major.</param> /// <param name="minor">Minor.</param> /// <param name="patch">Patch.</param> /// <param name="prereleaseIdentifiers">Prerelease identifiers.</param> /// <param name="metadata">Metadata.</param> /// <param name="isPresumed">If set to <c>true</c> then this instance will represent a presumed version number.</param> public SemanticVersion(int major, int minor, int patch, IList <string> prereleaseIdentifiers = null, IList <string> metadata = null, bool isPresumed = false) : base(isPresumed) { if (major < 0) { throw new ArgumentOutOfRangeException(nameof(major), "No version number component may be negative"); } if (minor < 0) { throw new ArgumentOutOfRangeException(nameof(minor), "No version number component may be negative"); } if (patch < 0) { throw new ArgumentOutOfRangeException(nameof(patch), "No version number component may be negative"); } this.major = major; this.minor = minor; this.patch = patch; this.prereleaseIdentifiers = prereleaseIdentifiers?.ToArray() ?? new string[0]; this.metadata = metadata?.ToArray() ?? new string[0]; }
public DataTable GetDefectInfo(string DBConnection, DateTime StartTime, DateTime EndTime, IList<string> Family, IList<string> PdLine, IList<string> Model, IList<string> Station) { string strSQL = @"SELECT TOP 1000 a.ID,a.Line,a.Station,a.ActionName,a.PCBNo,c.Descr,a.Editor,a.Cdt FROM PCBTestLog a LEFT JOIN PCBTestLog_DefectInfo b on a.ID=b.PCBTestLogID LEFT JOIN DefectCode c on c.Defect = b.DefectCodeID WHERE a.Status = 0 AND a.PCBNo IN ( SELECT a.PCBNo FROM PCB a RIGHT JOIN ModelBOM b ON b.Component = a.PCBModelID AND b.Material_group = 'MB' RIGHT JOIN Model c ON c.Model = b.Material AND c.Family IN ('{0}') RIGHT JOIN dbo.PartInfo d ON InfoType='MB' AND d.PartNo = a.PCBModelID AND InfoValue in ('{1}') ) AND a.Cdt BETWEEN @StartTime AND @EndTime AND a.Station IN ('{2}') AND a.Line IN ('{3}'); "; strSQL = string.Format(strSQL, string.Join("','", Family.ToArray()), string.Join("','", Model.ToArray()), string.Join("','", Station.ToArray()), string.Join("','", PdLine.ToArray())); DataTable dt = SQLHelper.ExecuteDataFill(DBConnection, System.Data.CommandType.Text, strSQL, new SqlParameter("@StartTime", StartTime), new SqlParameter("@EndTime", EndTime)); return dt; }
public bool CheckGoodsIssueFIFO(string locationCode, string itemCode, DateTime baseManufatureDate, IList<string> huIdList) { DetachedCriteria criteria = DetachedCriteria.For<LocationLotDetail>(); criteria.SetProjection(Projections.Count("Id")); criteria.CreateAlias("Hu", "hu"); criteria.CreateAlias("Location", "loc"); criteria.CreateAlias("Item", "item"); criteria.Add(Expression.IsNotNull("Hu")); criteria.Add(Expression.Gt("Qty", new Decimal(0))); criteria.Add(Expression.Eq("item.Code", itemCode)); criteria.Add(Expression.Eq("loc.Code", locationCode)); criteria.Add(Expression.Lt("hu.ManufactureDate", baseManufatureDate)); criteria.Add(Expression.Not(Expression.In("hu.HuId", huIdList.ToArray<string>()))); IList<int> list = this.criteriaMgr.FindAll<int>(criteria); if (list[0] > 0) { return false; } else { return true; } }
public DataTable GetModel(string DBConnection, IList<String> PdLine, DateTime From, DateTime To) { DataTable Result = null; string selectSQL = ""; string groupbySQL = ""; groupbySQL += "GROUP by b.Descr"; string orderbySQL = "ORDER BY b.Descr"; StringBuilder sb = new StringBuilder(); //sb.AppendLine("WITH [TEMP] AS ("); sb.AppendLine(" select distinct b.Descr as Family from PCBLog a inner join Part b on a.PCBModel=b.PartNo "); //sb.AppendLine("INNER JOIN PCB b ON a.PCBNo = b.PCBNo AND e.PartNo = b.PCBModelID "); sb.AppendLine("WHERE a.Cdt Between @StartTime AND @EndTime and b.BomNodeType='MB' "); if (PdLine.Count > 0) { sb.AppendFormat("AND a.Line in ('{0}') ", string.Join("','", PdLine.ToArray())); } sb.AppendFormat("{0} ", groupbySQL); sb.AppendFormat("{0} ", orderbySQL); Result = SQLHelper.ExecuteDataFill(DBConnection, System.Data.CommandType.Text, sb.ToString(), new SqlParameter("@StartTime", From), new SqlParameter("@EndTime", To)); return Result; }
public IList<Interval> Merge(IList<Interval> intervals) { Interval[] intervalArr = intervals.ToArray(); Array.Sort(intervalArr, new Comparison<Interval>(comparerInterval)); if (intervalArr.Length < 1) return intervalArr; IList<Interval> result = new List<Interval>(); Interval current = intervalArr[0]; for (int i = 1; i < intervalArr.Length; i++) { Interval next = intervalArr[i]; if (next.start > current.end) { result.Add(current); current = next; } else { current.end = Math.Max(current.end, next.end); } } result.Add(current); return result; }
public OpcDaVQTE[] Read(IList<string> itemIds, IList<TimeSpan> maxAge) { if (maxAge == null) maxAge = new TimeSpan[itemIds.Count]; if (itemIds.Count != maxAge.Count) throw new ArgumentException("Invalid size of maxAge", "maxAge"); int[] intMaxAge = ArrayHelpers.CreateMaxAgeArray(maxAge, itemIds.Count); string[] pszItemIDs = itemIds.ToArray(); var ppvValues = new object[pszItemIDs.Length]; var ppwQualities = new short[pszItemIDs.Length]; var ppftTimeStamps = new FILETIME[pszItemIDs.Length]; var ppErrors = new HRESULT[pszItemIDs.Length]; DoComCall(ComObject, "IOPCItemIO::Read", () => ComObject.Read(pszItemIDs.Length, pszItemIDs, intMaxAge, out ppvValues, out ppwQualities, out ppftTimeStamps, out ppErrors), pszItemIDs.Length, pszItemIDs, maxAge); var result = new OpcDaVQTE[itemIds.Count]; for (int i = 0; i < ppvValues.Length; i++) { var vqte = new OpcDaVQTE { Value = ppvValues[i], Quality = ppwQualities[i], Timestamp = FileTimeConverter.FromFileTime(ppftTimeStamps[i]), Error = ppErrors[i] }; result[i] = vqte; } return result; }
public HRESULT[] WriteVQT(IList<string> itemIds, IList<OpcDaVQT> values) { if (itemIds.Count != values.Count) throw new ArgumentException("Invalid size of values", "values"); var vqts = new OPCITEMVQT[values.Count]; for (int i = 0; i < values.Count; i++) { OpcDaVQT opcItemValue = values[i]; vqts[i].bQualitySpecified = false; if (opcItemValue.Quality != short.MinValue) { vqts[i].bQualitySpecified = true; vqts[i].wQuality = opcItemValue.Quality; } vqts[i].bTimeStampSpecified = false; if (opcItemValue.Timestamp != DateTimeOffset.MinValue) { vqts[i].bTimeStampSpecified = true; vqts[i].ftTimeStamp = FileTimeConverter.ToFileTime(opcItemValue.Timestamp); } vqts[i].vDataValue = opcItemValue.Value; } string[] pszItemIDs = itemIds.ToArray(); var ppErrors = new HRESULT[pszItemIDs.Length]; DoComCall(ComObject, "IOPCItemIO::WriteVQT", () => ComObject.WriteVQT(pszItemIDs.Length, pszItemIDs, vqts, out ppErrors), pszItemIDs.Length, pszItemIDs); return ppErrors; }
/// <summary> /// Initializes a new cellular automaton with the specified states that has the specified rule. /// </summary> /// <param name="rule">A rule number</param> /// <param name="length">A length of cells</param> /// <param name="initialState">An initial state</param> public LinearCellularAutomaton(byte rule, int length, IList<bool> initialState) : this(rule, length) { _density = (double)initialState.Count(b => b) / length; state = initialState.ToArray(); _initialState = new System.Collections.ObjectModel.ReadOnlyCollection<bool>(initialState); }
public SliceExpression(Expression root, Token bracketToken, IList<Expression> components) : base(root.FirstToken) { this.Root = root; this.BracketToken = bracketToken; this.Components = components.ToArray(); }
void IMemcachedNodeLocator.Initialize(IList<IMemcachedNode> nodes) { // we do not care about dead nodes if (this.nodes != null) return; this.nodes = nodes.ToArray(); }
public static DataTable Select(string sql, IList<SQLiteParameter> cmdparams = null) { SQLiteConnection cnn = Connect; if (cnn == null) return null; DataTable dt = new DataTable(); SQLiteCommand Comm = null; SQLiteDataReader Reader = null; try { Comm = new SQLiteCommand(cnn); Comm.CommandText = sql; if (cmdparams != null) Comm.Parameters.AddRange(cmdparams.ToArray()); Comm.CommandTimeout = TIMEOUT; Reader = Comm.ExecuteReader(); dt.Load(Reader); } catch (Exception e) { _Err = e.Message; return null; } finally { if (Reader != null) Reader.Close(); if (Comm != null) Comm.Dispose(); } return dt; }
public Instantiate(Token firstToken, Token firstClassNameToken, string name, IList<Expression> args, Executable owner) : base(firstToken, owner) { this.NameToken = firstClassNameToken; this.Name = name; this.Args = args.ToArray(); }
private void PromptMacros() { var builderSingle = new Android.App.AlertDialog.Builder(this); builderSingle.SetTitle("Select Macro"); var negative = new EventHandler <DialogClickEventArgs>( (s, args) => { }); var positive = new EventHandler <DialogClickEventArgs>( async(s, args) => { if (_macrosValues != null && _macrosValues.Count > args.Which) { var value = _macrosValues[args.Which]; var currentHtml = await _richEditorWebView.GetHtmlAsync(); _richEditorWebView.SetHTML(currentHtml + value + "<br/>"); } }); builderSingle.SetItems(_macros?.ToArray(), positive); builderSingle.SetNegativeButton("Cancel", negative); var adialog = builderSingle.Create(); adialog.Show(); }
/// <summary> /// Disassembles the given code /// </summary> /// <param name="generatedCode">The generated code</param> public static string Disassemble(IList<byte> generatedCode) { var strBuffer = new StringBuilder(); var buffer = new UnmanagedBuffer(generatedCode.ToArray()); var disasm = new Disasm(); disasm.Archi = 64; int offset = 0; while (offset < generatedCode.Count) { disasm.EIP = new IntPtr(buffer.Ptr.ToInt64() + offset); int result = BeaEngine64.Disasm(disasm); if (result == (int)BeaConstants.SpecialInfo.UNKNOWN_OPCODE) { break; } //strBuffer.AppendLine("0x" + offset.ToString("X") + " " + disasm.CompleteInstr); strBuffer.AppendLine(disasm.CompleteInstr); offset += result; } return strBuffer.ToString(); }
public ForEachLoop(Token forToken, Token iteratorVariable, Expression iterableExpression, IList<Executable> body) : base(forToken) { this.IteratorVariable = iteratorVariable; this.IterableExpression = iterableExpression; this.Body = body.ToArray(); }
private void BindAccountInfo(int accountType) { //账户 var accounts = new List <AccountEntity>(); var infos = _accountService.GetAccountDetails(accountIds: _tradingAccountIds?.ToArray(), typeCode: accountType, onlyNeedAccounting: true, showDisabled: true).ToList(); accounts.AddRange(infos); if (accounts.Count > 0) { //æ·»åŠ å…¨é€‰ var all = new AccountEntity { Id = 0, Name = " 全部 ", AttributeName = " 全部 ", SecurityCompanyName = " 全部 ", TypeName = this.cbAccountType.Text, DisplayMember = " 全部 ", }; accounts.Add(all); } accounts = accounts.OrderBy(x => x.Name).ThenBy(x => x.SecurityCompanyName).ToList(); luAccount.Initialize(accounts, "Id", "DisplayMember", showHeader: true, enableSearch: true); luAccount.EditValue = 0; }
public PegPattern(Palette palette, IList <int> pegs) : base(palette, pegs?.ToArray()) { if (Size <= 0) { throw new ArgumentException("Pattern size must be greater than 0."); } }
public IfStatement(Token ifToken, Expression condition, IList<Executable> trueCode, IList<Executable> falseCode, Executable owner) : base(ifToken, owner) { this.Condition = condition; this.TrueCode = trueCode.ToArray(); this.FalseCode = falseCode.ToArray(); }
public SystemFunctionInvocation(Token prefix, Token root, IList<Expression> args) : base(prefix) { this.Root = root; this.Name = root.Value; this.Args = args.ToArray(); }
// The reason why I still run this function with actuallyDoThis = false is so that other platforms can still be exported to // and potentially crash if the implementation was somehow broken on Python (or some other future platform that doesn't have traditional switch statements). internal static Executable[] RemoveBreaksForElifedSwitch(bool actuallyDoThis, IList<Executable> executables) { List<Executable> newCode = new List<Executable>(executables); if (newCode.Count == 0) throw new Exception("A switch statement contained a case that had no code and a fallthrough."); if (newCode[newCode.Count - 1] is BreakStatement) { newCode.RemoveAt(newCode.Count - 1); } else if (newCode[newCode.Count - 1] is ReturnStatement) { // that's okay. } else { throw new Exception("A switch statement contained a case with a fall through."); } foreach (Executable executable in newCode) { if (executable is BreakStatement) { throw new Exception("Can't break out of case other than at the end."); } } return actuallyDoThis ? newCode.ToArray() : executables.ToArray(); }
public Choice(IList <IConsideration <T> > considerations, IList <IRequirement <T> > requirements = null) { this.considerations = considerations?.ToArray() ?? new IConsideration <T> [0]; this.requirements = requirements?.ToArray() ?? new IRequirement <T> [0]; requirementCount = this.requirements.Length; considerationCount = this.considerations.Length; }
public virtual void SetAttributeFilters(Store store, IList <AttributeFilter> filters) { if (store != null) { var browsing = GetFilteredBrowsing(store) ?? new FilteredBrowsing(); browsing.Attributes = filters?.ToArray(); SetFilteredBrowsing(store, browsing); } }
public WebDriverWait Wait(int wait = 30, IList <Type> ignoreExceptionTypes = null) { var webDriverWait = new WebDriverWait(_driver, TimeSpan.FromSeconds(wait)); webDriverWait.IgnoreExceptionTypes(ignoreExceptionTypes?.ToArray() ?? new [] { typeof(StaleElementReferenceException) }); return(webDriverWait); }
public void TestMethod(int[] arr, int k, int x, int[] expected) { // Arrange FindKClosestElements question = new FindKClosestElements(); // Act IList <int> actual = question.FindClosestElements(arr, k, x); // Assert CollectionAssert.AreEqual(expected, actual?.ToArray()); }
public async Task <FavoriteRepositoryVM[]> GetFavoriteRepositories() { var pathFile = _repositoryFavoritePath + "favorites.json"; var fileExists = await Task.FromResult(File.Exists(pathFile)).ConfigureAwait(false); IList <FavoriteRepositoryVM> favorites = fileExists ? await Task.FromResult(JsonSerializer.Deserialize <FavoriteRepositoryVM[]>(File.ReadAllText(pathFile))).ConfigureAwait(false) : null; return(favorites?.ToArray()); }
public void TestMethod3(string[] words, int maxWidth, string[] expected) { // Arrange TextJustification question = new TextJustification(); // Act IList <string> actual = question.FullJustify(words, maxWidth); // Assert CollectionAssert.AreEqual(expected, actual?.ToArray()); }
/// <summary> /// Creates a new <see cref="IDataItem"/> instance using the specified parameters. /// </summary> /// <param name="etpAdapter">The ETP adapter.</param> /// <param name="channelId">The channel identifier.</param> /// <param name="value">The channel data value.</param> /// <param name="indexes">The channel index values.</param> /// <param name="attributes">The data attributes.</param> /// <returns>A new <see cref="IDataItem"/> instance.</returns> public static IDataItem CreateDataItem(this IEtpAdapter etpAdapter, long channelId = 0, object value = null, IList <long> indexes = null, IList <object> attributes = null) { if (etpAdapter is Energistics.Etp.v11.Etp11Adapter) { return(new Energistics.Etp.v11.Datatypes.ChannelData.DataItem { ChannelId = channelId, Indexes = indexes?.ToArray() ?? new long[0], Value = new Energistics.Etp.v11.Datatypes.DataValue { Item = value }, ValueAttributes = attributes? .Select((x, i) => new Energistics.Etp.v11.Datatypes.DataAttribute { AttributeId = i, AttributeValue = new Energistics.Etp.v11.Datatypes.DataValue { Item = x } }) .ToArray() ?? new Energistics.Etp.v11.Datatypes.DataAttribute[0] }); } return(new Energistics.Etp.v12.Datatypes.ChannelData.DataItem { ChannelId = channelId, Indexes = indexes?.ToArray() ?? new long[0], Value = new Energistics.Etp.v12.Datatypes.DataValue { Item = value }, ValueAttributes = attributes? .Select((x, i) => new Energistics.Etp.v12.Datatypes.DataAttribute { AttributeId = i, AttributeValue = new Energistics.Etp.v12.Datatypes.DataValue { Item = x } }) .ToArray() ?? new Energistics.Etp.v12.Datatypes.DataAttribute[0] }); }
/// <summary> /// Creates a new <see cref="StructuredTransformer"/> instance. /// </summary> internal StructuredTransformer(bool?copyRequestHeaders, bool?copyResponseHeaders, bool?copyResponseTrailers, IList <RequestTransform> requestTransforms, IList <ResponseTransform> responseTransforms, IList <ResponseTrailersTransform> responseTrailerTransforms) { ShouldCopyRequestHeaders = copyRequestHeaders; ShouldCopyResponseHeaders = copyResponseHeaders; ShouldCopyResponseTrailers = copyResponseTrailers; RequestTransforms = requestTransforms?.ToArray() ?? throw new ArgumentNullException(nameof(requestTransforms)); ResponseTransforms = responseTransforms?.ToArray() ?? throw new ArgumentNullException(nameof(responseTransforms)); ResponseTrailerTransforms = responseTrailerTransforms?.ToArray() ?? throw new ArgumentNullException(nameof(responseTrailerTransforms)); }
public GraphQLError(string message, IList <object> path = null, SourceLocation location = null, string type = null) { Message = message; Path = path?.ToArray() ?? _emptyPath; if (location != null) { Locations.Add(location); } if (!string.IsNullOrEmpty(type)) { Extensions[ErrorCodeKey] = type; } }
public void Execute(string guid, string controllerName, string methodName, IList <object> data = null) { var controllerType = GetControllerType(controllerName); var controller = GetController(controllerType); var method = controllerType.GetMethod(methodName); Task.Factory .StartNew(() => method.Invoke(controller, data?.ToArray())) .ContinueWith((e) => { CefForm.Instance.ExecuteJsFunction("ajax.resolve", guid, e.Result?.ToString()); }); }
public MappedCommand <T> CompileInsertWithOutput <T>(string tableName, IList <FieldSettings <T> > settings, IList <string> ignoreFields, params string[] outputFields) { var ignFields = ignoreFields?.ToArray() ?? new string[0]; if (outputFields.Length == 0) { return(CompileInsert(tableName, settings, ignFields)); } var fields = settings.Select(x => x.Name).Except(ignFields.Select(x => x)).ToArray(); string query = contextProvider.CommandTextGenerator.InsertWithOutput(tableName, fields, outputFields); return(new MappedCommand <T>(contextProvider, query, fields, settings, true)); }
public void TestMethod2() { // Arrange BinaryTreePostorderTraversal question = new BinaryTreePostorderTraversal(); TreeNode root = new TreeNode(1); root.right = new TreeNode(2); root.right.left = new TreeNode(3); int[] expected = new int[] { 3, 2, 1 }; // Act IList <int> actual = question.PostorderTraversal2(root); // Assert CollectionAssert.AreEqual(expected, actual?.ToArray()); }
public Task <FileBrowserResult> BrowseToOpen(string defaultDirectory, IList <string> extensions) { var openPanel = NSOpenPanel.OpenPanel; var result = new FileBrowserResult(); openPanel.CanChooseDirectories = false; openPanel.CanChooseFiles = true; openPanel.CanCreateDirectories = false; if (openPanel.RunModal(defaultDirectory, null, extensions?.ToArray()) == 1) { result.Confirmed = true; result.FileName = openPanel.Filename; } return(Task.FromResult(result)); }
public static Task <IStorageFile> PickSingleFileAsync(IList <string> fileTypes) { tcs = new TaskCompletionSource <IStorageFile>(); pvc = new UIDocumentPickerViewController(fileTypes?.ToArray() ?? new string[] { UTType.Content, UTType.Item, "public.data" }, UIDocumentPickerMode.Open) { AllowsMultipleSelection = false }; pvc.DidPickDocument += Pvc_DidPickDocument; pvc.WasCancelled += Pvc_WasCancelled; pvc.DidPickDocumentAtUrls += Pvc_DidPickDocumentAtUrls; UIViewController viewController = GetActiveViewController(); viewController.PresentViewController(pvc, true, null); return(tcs.Task); //Task.FromResult<IStorageFile>(new StorageFile(_uri)); }
private async Task LoadAssets(LoadAssets payload, Action onCompleteCallback) { LoaderFunction loader; switch (payload.Source.ContainerType) { case AssetContainerType.GLTF: loader = LoadAssetsFromGLTF; break; default: throw new Exception( $"Cannot load assets from unknown container type {payload.Source.ContainerType.ToString()}"); } IList <Asset> assets = null; string failureMessage = null; // attempt to get cached assets instead of loading try { assets = await loader(payload.Source, payload.ContainerId, payload.ColliderType); ActiveContainers.Add(payload.ContainerId); } catch (Exception e) { failureMessage = UtilMethods.FormatException( $"An unexpected error occurred while loading the asset [{payload.Source.Uri}].", e); } _app.Protocol.Send(new Message() { ReplyToId = payload.MessageId, Payload = new AssetsLoaded() { FailureMessage = failureMessage, Assets = assets?.ToArray() } }); onCompleteCallback?.Invoke(); }
public static Task <IStorageFile> PickSingleFileAsync(IList <string> fileTypes) { var panel = new NSOpenPanel { CanChooseDirectories = false, CanChooseFiles = true, FloatingPanel = true, AllowsMultipleSelection = false, ResolvesAliases = true, }; panel.RunModal(fileTypes?.ToArray() ?? new string[] { UTType.Content, UTType.Item, "public.data" }); if (panel.Url is null) { return(Task.FromResult <IStorageFile>(null)); } System.Diagnostics.Debug.WriteLine("panel.Url.Path: " + panel.Url.Path); return(Task.FromResult <IStorageFile>(new StorageFile(panel.Url, true))); }
public NDArray(IList <mx_float> data, Shape shape) : this(data?.ToArray(), shape) { }
public NotificationUserCategory[] GetUserNotificationCategories() { return(usernNotificationCategories?.ToArray()); }
static IVTableSlot ResolveSlot(TypeDef openType, VTableSlot slot, IList <TypeSig> genArgs) { var newSig = GenericArgumentResolver.Resolve(slot.Signature.MethodSig, genArgs); var newDecl = slot.MethodDefDeclType; if (new SigComparer().Equals(newDecl, openType)) { newDecl = new GenericInstSig((ClassOrValueTypeSig)openType.ToTypeSig(), genArgs.ToArray()); } else { newDecl = GenericArgumentResolver.Resolve(newDecl, genArgs); } return(new VTableSlot(newDecl, slot.MethodDef, slot.DeclaringType, new VTableSignature(newSig, slot.Signature.Name), (VTableSlot)slot.Parent)); }
public NDArray(IList <mx_float> data, Shape shape, Context context) : this(data?.ToArray(), shape, context) { }
private static SupportBean[] AllEvents(IList <SupportBean> list) { return(list?.ToArray()); }
public async Task CreateMemberDetailAssociation(DetailReadModel detail, IList <Guid> memberIds) { await this.CreateDetailAssociation(detail, EntityTypeEnum.Member, memberIds?.ToArray()) .ConfigureAwait(false); }
public static RpcParameters FromList(IList <object> parameters) { return(new RpcParameters(parameters?.ToArray())); }
/// <summary> /// Creats a new <see cref="FlagEnum{T}"/> from a list of specified flag values. /// </summary> /// <typeparam name="T">The type of enum values to encapsulate.</typeparam> /// <param name="value">The values to encapsulate.</param> /// <returns>A <see cref="FlagEnum{T}"/> that encapsulates the specified values.</returns> public static FlagEnum <T> Create <T>(IList <T> value) where T : struct { return(new FlagEnum <T>(value?.ToArray())); }