public FastEncoder(bool doGZip) { this.usingGzip = doGZip; this.inputWindow = new FastEncoderWindow(); this.inputBuffer = new DeflateInput(); this.output = new Output(); this.currentMatch = new Match(); }
public Parameters Calculate(Parameters parameters) { var input = ParametersMapper.Map<Input>(parameters); var output = new Output(); output.Vk = input.MaxVk; var gammaN = input.Gamma / input.Fi; output.Qkr = 60 * input.F * input.Fi * input.MaxVk * gammaN; output.Kp = input.Q / output.Qkr; output.C = 1 - output.Kp; output.Vc = output.Vk * output.C; // h' и полином var x = output.C; var h = input.A2 * x * x + input.A1 * x + input.A0; output.MinH = h*10*input.F*input.Fi2/input.MinH; output.MaxH = h * 10 * input.F * input.Fi2 / input.MaxH; return ParametersMapper.Map(output); }
public Player(List<Player> players, OutputType outputType) { writer = new Output(outputType); writer.Write("Enter the name of the player: "); this.name = Console.ReadLine().Trim(); writer.Write("Enter the piece you want to use: "); this.piece = new Piece(Console.ReadLine().Trim()); while (players.Select(p => p).Where(x => string.Compare(x.Piece.Symbol, this.piece.Symbol) == 0).Count() >= 1) { writer.Write("That piece has already been taken.\nChoose a different piece: "); this.piece = new Piece(Console.ReadLine().Trim()); } writer.Write("Is this player HUMAN or AI: "); do { var playerType = Console.ReadLine().Trim(); PlayerType humanOrNot; if (Enum.TryParse<PlayerType>(playerType.ToUpper(), out humanOrNot)) { this.playerType = humanOrNot; break; } writer.Write("Enter a valid Player Type: [human] or [AI]: "); continue; } while (true); this.order = -1; }
private void ExtractDiz() { Log.Debug("ExtractDiz"); System.IO.FileInfo fileInfo = new System.IO.FileInfo(race.RaceFile); if (fileInfo.Exists) { Log.Debug("Race file exists..."); return; } bool dizFound = race.CurrentRaceData.UploadFile.ExtractFromArchive(".diz"); if (Config.ExtractNfoFromZip) { race.CurrentRaceData.UploadFile.ExtractFromArchive(".nfo"); } if (dizFound) { DataParserDiz dataParserDiz = new DataParserDiz(race); dataParserDiz.Parse(); dataParserDiz.Process(); return; } Log.Debug("DIZ file not found in ZIP"); race.IsValid = false; Output output = new Output(race); output .Client(Config.ClientHead) .Client(Config.ClientFileNameNoDiz) .Client(Config.ClientFoot); }
private IAsyncResult CallAsync() { output = GetString; return output.BeginInvoke( ControllerContext.Async.Callback, ControllerContext.Async.State); }
public Transaction(int version, Input[] inputs, Output[] outputs, uint lockTime) { Version = version; Inputs = inputs; Outputs = outputs; LockTime = lockTime; }
public ByteString GetPaymentRequest(string finalAccount, ulong amount) { PaymentDetails paymentDetails = new PaymentDetails(); paymentDetails.Network = isMainNet ? "main" : "test"; paymentDetails.Time = GetTimestamp(DateTime.UtcNow); paymentDetails.Expires = GetTimestamp(DateTime.UtcNow.AddHours(1)); paymentDetails.Memo = $"Funding Openchain account {finalAccount}"; Output paymentOutput = new Output(); paymentOutput.Amount = amount; paymentOutput.Script = Google.Protobuf.ByteString.CopyFrom(NBitcoin.Script.CreateFromDestinationAddress(destinationAddress).ToBytes()); Output dataOutput = new Output(); dataOutput.Amount = dustValue; dataOutput.Script = Google.Protobuf.ByteString.CopyFrom( new[] { (byte)OpcodeType.OP_RETURN }.Concat(Op.GetPushOp(Encoding.UTF8.GetBytes("OG" + finalAccount)).ToBytes()).ToArray()); paymentDetails.Outputs.Add(paymentOutput); paymentDetails.Outputs.Add(dataOutput); PaymentRequest request = new PaymentRequest(); request.SerializedPaymentDetails = paymentDetails.ToByteString(); request.PkiType = "none"; return new ByteString(request.ToByteArray()); }
public Link(Input input, Output output) { this.Input = input; this.Output = output; this.Weight = new Random().NextDouble(); Console.WriteLine("Weight: " + Weight); }
private void Add_RSSI() { string file = File.ReadAllText("combined_routers_C.txt"); string[] lines = file.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries); Output output = new Output(); output.router_rssis = new List<int>(8); for (int i = 0; i < 8; i++) { output.router_rssis.Add(int.MaxValue); } foreach (string line in lines) { string line2 = line.Trim(); string[] fields = line2.Split(new char[] { '\t' }); try { if (fields[1] != string.Empty) { int nnVector = int.Parse(fields[1]) - 1; int rssi_val = int.Parse(fields[2]); output.router_rssis[nnVector] = rssi_val; } else { x = double.Parse(fields[3]); y = double.Parse(fields[4]); } bool full = true; foreach (int rssi in output.router_rssis) { if (rssi.Equals(int.MaxValue)) { full = false; break; } } if (full) { output.x = x; output.y = y; outputs.Add(output); output = new Output(); output.router_rssis = new List<int>(8); for (int i = 0; i < 8; i++) { output.router_rssis.Add(int.MaxValue); } } } catch { } } }
public override void print(Output @out) { @out.println("while true do"); @out.indent(); Statement.printSequence(@out, statements); @out.dedent(); @out.print("end"); }
static void Main(string[] args) { var controller = new IndexController(); controller.IndexFile(@"data\TestData.txt"); var output = new Output(); output.Print(controller.IndexedLines); }
public WalletTransaction(Transaction transaction, Sha256Hash hash, Input[] inputs, Output[] outputs, Amount? fee, DateTimeOffset seenTime) { Hash = hash; Inputs = inputs; Outputs = outputs; Fee = fee; Transaction = transaction; SeenTime = seenTime; }
public Input(JObject i) { JObject prevOut = i["prev_out"] as JObject; if (prevOut != null) PreviousOutput = new Output(prevOut, true); Sequence = (long)i["sequence"]; ScriptSignature = (string)i["script"]; }
public override void print(Output @out) { @out.print("local "); @out.print(decls[0].name); for(int i = 1; i < decls.Count; i++) { @out.print(", "); @out.print(decls[i].name); } }
public WorkSheetOptions(Worksheet w, Output o) { // // The InitializeComponent() call is required for Windows Forms designer support. // worksheet = w; InitializeComponent(); initializeValues(); parent = o; }
public string Display(Output action) { var s = new StringBuilder(); s.Append("{weekFrom: ").Append(WeekFrom).Append(", trips: ["); var tripStrings = new List<string>(); ForEach((trip) => tripStrings.Add(action.Invoke(trip))); s.Append(String.Join(", ", tripStrings.ToArray())); return s.Append("]}").ToString(); }
public Parameters Calculate(Parameters parameters) { var input = ParametersMapper.Map<Input>(parameters); var output = new Output(); output.C = 1 / output.K0; var x = output.C; var h = input.A2 * x * x + input.A1 * x + input.A0; output.MaxH = h * 10 * input.F * input.Fi2 / (input.MaxH * input.Fi); output.MinH = h * 10 * input.F * input.Fi2 / (input.MinH * input.Fi); return ParametersMapper.Map<Output>(output); }
protected Env(Stack<Ruleset> frames, Dictionary<string, Type> functions) { Frames = frames ?? new Stack<Ruleset>(); Output = new Output(this); _plugins = new List<IPlugin>(); _functionTypes = functions ?? new Dictionary<string, Type>(); if (_functionTypes.Count == 0) AddCoreFunctions(); }
public Transaction(int version, Input[] inputs, Output[] outputs, uint lockTime) { if (inputs == null) throw new ArgumentNullException(nameof(inputs)); if (outputs == null) throw new ArgumentNullException(nameof(outputs)); Version = version; Inputs = inputs; Outputs = outputs; LockTime = lockTime; }
public StoryController(IStory story, Output output, CommandPrompt commandPrompt) { if (story == null) throw new ArgumentNullException("story"); if (output == null) throw new ArgumentNullException("output"); if (commandPrompt == null) throw new ArgumentNullException("commandPrompt"); Context.Output = output; Context.CommandPrompt = commandPrompt; Context.Story = story; Context.Parser = new Parser(); }
public override async Task<IMessage<Output>> SubtractAsync(IMessage<PairedInput> request, CancellationToken ct) { PairedInput req = request.Convert<PairedInput>().Payload.Deserialize(); var res = new Output { Result = req.First - req.Second, TraceId = req.TraceId }; await Task.Delay(DelayMilliseconds); return Message.FromPayload(res); }
public void OutputH264CreateJob() { Output output = new Output() { H264Level = H264Level.FourPointOne, H264ReferenceFrames = 5, H264Profile = H264Profile.High, Tuning = Tuning.FastDecode }; CreateJobResponse response = Zencoder.CreateJob("s3://bucket-name/file-name.avi", new Output[] { output }); Assert.IsTrue(response.Success); }
public Network(int numInputs, int numOutputs) { LearningRate = 0.1; Inputs = new Input[numInputs]; for (int i = 0; i < numInputs; i++) { Inputs[i] = new Input(); } Outputs = new Output[numOutputs]; for (int i = 0; i < numOutputs; i++) { Outputs[i] = new Output(); } }
protected Env(Stack<Ruleset> frames, Dictionary<string, Type> functions) { Frames = frames ?? new Stack<Ruleset>(); Output = new Output(this); MediaPath = new Stack<Media>(); MediaBlocks = new List<Media>(); Logger = new NullLogger(LogLevel.Info); _plugins = new List<IPlugin>(); _functionTypes = functions ?? new Dictionary<string, Type>(); if (_functionTypes.Count == 0) AddCoreFunctions(); }
public HtmlSearchManager(string startUrl, string textToSearch, int numberOfUrlsToSearch, int threadNum, Output method) { _scheduler = new LimitedConcurrencyLevelTaskScheduler(threadNum); _startUrl = startUrl; _textToSearch = textToSearch; _numberOfUrlsToSearch = numberOfUrlsToSearch; _cancelTokenSource = new CancellationTokenSource(); _cancelToken = _cancelTokenSource.Token; _taskFactory = new TaskFactory(_cancelToken, TaskCreationOptions.None, TaskContinuationOptions.None, _scheduler); _outputMethod = method; }
public override void printTail(Output @out) { @out.print("return"); if(values.Length > 0) { @out.print(" "); List<Expression> rtns = new List<Expression>(values.Length); foreach(Expression value in values) { rtns.Add(value); } Expression.printSequence(@out, rtns, false, true); } }
public override void print(Output @out) { table.print(@out); if(index.isIdentifier()) { @out.print("."); @out.print(index.asName()); } else { @out.print("["); index.print(@out); @out.print("]"); } }
public Game(int playersCount, int boardSize, OutputType outputType) { writer = new Output(outputType); if(outputType == OutputType.File) { FileWriter.ClearFile(); } players = new List<Player>(); for (int i = 0; i < playersCount; i++) { players.Add(new Player(players, outputType)); } board = new Board(boardSize); Toss(); }
private static void PrintDisplayModes(Output output, Format format) { Console.WriteLine(" Display modes for format: {0}", format); var displayModes = output.GetDisplayModeList(format, 0); if(displayModes == null) return; foreach (var displayMode in displayModes) { foreach (var descProperty in displayMode.GetType().GetProperties()) { Console.WriteLine(" {0}: {1}", ParseName(descProperty.Name), descProperty.GetValue(displayMode, null)); } Console.WriteLine(); } }
public Output ProcessInput(Input input) { if (String.IsNullOrEmpty(input.AssertPresence)) throw new ArgumentException("input.AssertPresence might not be null or Empty."); if (input.DontBeNull == null) throw new ArgumentException("input.DontBeNull has to be set."); var result = new Output { Sum = _additionService.Add(input.Operands), Product = _multiplicationService.Multiply(input.Operands) }; return result; }
public Form1() { InitializeComponent(); Output.SetGenericOutput(MSGFormat); Interface.SetOutputEventHandler(Output.GenerateOutput); }
/// <summary> /// Main running method for the application. /// </summary> /// <param name="args">Commandline arguments to the application.</param> /// <returns>Returns the application error code.</returns> private int Run(string[] args) { try { XmlSchemaCollection objectSchema = new XmlSchemaCollection(); FileInfo currentFile = null; ArrayList intermediates = new ArrayList(); Linker linker = null; Microsoft.Tools.WindowsInstallerXml.Binder binder = null; Localizer localizer = null; try { // parse the command line this.ParseCommandLine(args); // exit if there was an error parsing the command line (otherwise the logo appears after error messages) if (this.messageHandler.FoundError) { return(this.messageHandler.PostProcess()); } if (0 == this.objectFiles.Count) { this.showHelp = true; } else if (null == this.outputFile) { if (1 < this.objectFiles.Count) { throw new ArgumentException("must specify output file when using more than one input file", "-out"); } FileInfo fi = (FileInfo)this.objectFiles[0]; this.outputFile = new FileInfo(Path.ChangeExtension(fi.Name, ".wix")); // we'll let the linker change the extension later } if (this.showLogo) { Assembly lightAssembly = Assembly.GetExecutingAssembly(); Console.WriteLine("Microsoft (R) Windows Installer Xml Linker version {0}", lightAssembly.GetName().Version.ToString()); Console.WriteLine("Copyright (C) Microsoft Corporation 2003. All rights reserved."); Console.WriteLine(); } if (this.showHelp) { Console.WriteLine(" usage: light.exe [-?] [-b basePath] [-nologo] [-out outputFile] objectFile [objectFile ...]"); Console.WriteLine(); Console.WriteLine(" -ai allow identical rows, identical rows will be treated as a warning"); Console.WriteLine(" -au (experimental) allow unresolved references, will not create a valid output"); Console.WriteLine(" -b base path to locate all files (default: current directory)"); Console.WriteLine(" -cc path to cache built cabinets (will not be deleted after linking)"); Console.WriteLine(" -ext extension (class, assembly), should extend SchemaExtension or BinderExtension"); Console.WriteLine(" -fv add a 'fileVersion' entry to the MsiAssemblyName table (rarely needed)"); Console.WriteLine(" -i specify the base output path for uncompressed images (default: -out parameter)"); Console.WriteLine(" -loc read localization string sfrom .wxl file"); Console.WriteLine(" -nologo skip printing light logo information"); Console.WriteLine(" -notidy do not delete temporary files (useful for debugging)"); Console.WriteLine(" -reusecab reuse cabinets from cabinet cache"); Console.WriteLine(" -out specify output file (default: write to current directory)"); Console.WriteLine(" -xo output xml instead of MSI format"); Console.WriteLine(" -pedantic:<level> pedantic checks (levels: easy, heroic, legendary)"); Console.WriteLine(" -reusecab reuse cabinets from cabinet cache"); Console.WriteLine(" -sa suppress assemblies: do not get assembly name information for assemblies"); Console.WriteLine(" -sacl suppress resetting ACLs (useful when laying out image to a network share)"); Console.WriteLine(" -sadmin suppress default admin sequence actions"); Console.WriteLine(" -sadv suppress default adv sequence actions"); Console.WriteLine(" -sa suppress assemblys: do not get assembly name information for assemblies"); Console.WriteLine(" -sf suppress files: do not get any file information (equivalent to -sa and -sh)"); Console.WriteLine(" -sh suppress file info: do not get hash, version, language, etc"); Console.WriteLine(" -sl suppress layout"); Console.WriteLine(" -ss suppress schema validation of documents (performance boost)"); Console.WriteLine(" -sui suppress default UI sequence actions"); Console.WriteLine(" -sv suppress intermediate file version mismatch checking"); Console.WriteLine(" -ts tag sectionId attribute on tuples (ignored if not used with -xo)"); Console.WriteLine(" -ust use small table definitions (for backwards compatiblity)"); Console.WriteLine(" -wx treat warnings as errors"); Console.WriteLine(" -w<N> set the warning level (0: show all, 3: show none)"); Console.WriteLine(" -sw suppress all warnings (same as -w3)"); Console.WriteLine(" -sw<N> suppress warning with specific message ID"); Console.WriteLine(" -v verbose output (same as -v2)"); Console.WriteLine(" -v<N> sets the level of verbose output (0: most output, 3: none)"); Console.WriteLine(" -? this help information"); Console.WriteLine(); Console.WriteLine("Environment variables:"); Console.WriteLine(" WIX_TEMP overrides the temporary directory used for cab creation, msm exploding, ..."); Console.WriteLine(); Console.WriteLine("Common extensions:"); Console.WriteLine(" .wxs - Windows installer Xml Source file"); Console.WriteLine(" .wxi - Windows installer Xml Include file"); Console.WriteLine(" .wxl - Windows installer Xml Localization file"); Console.WriteLine(" .wixobj - Windows installer Xml Object file (in XML format)"); Console.WriteLine(" .wixlib - Windows installer Xml Library file (in XML format)"); Console.WriteLine(" .wixout - Windows installer Xml Output file (in XML format)"); Console.WriteLine(); Console.WriteLine(" .msm - Windows installer Merge Module"); Console.WriteLine(" .msi - Windows installer Product Database"); Console.WriteLine(" .mst - Windows installer Transform"); Console.WriteLine(" .pcp - Windows installer Patch Creation Package"); Console.WriteLine(); Console.WriteLine("For more information see: http://wix.sourceforge.net"); return(this.messageHandler.PostProcess()); } // create the linker and the binder linker = new Linker(this.useSmallTables); binder = new Microsoft.Tools.WindowsInstallerXml.Binder(this.useSmallTables); linker.AllowIdenticalRows = this.allowIdenticalRows; linker.AllowUnresolvedReferences = this.allowUnresolvedReferences; linker.PedanticLevel = this.pedanticLevel; // set the sequence suppression options linker.SuppressAdminSequence = this.suppressAdminSequence; linker.SuppressAdvertiseSequence = this.suppressAdvertiseSequence; linker.SuppressUISequence = this.suppressUISequence; linker.SectionIdOnTuples = this.sectionIdOnTuples; binder.SuppressAclReset = this.suppressAclReset; binder.SetMsiAssemblyNameFileVersion = this.setMsiAssemblyNameFileVersion; binder.SuppressAssemblies = this.suppressAssemblies; binder.SuppressFileHashAndInfo = this.suppressFileHashAndInfo; if (this.suppressFiles) { binder.SuppressAssemblies = true; binder.SuppressFileHashAndInfo = true; } binder.SuppressLayout = this.suppressLayout; binder.TempFilesLocation = Environment.GetEnvironmentVariable("WIX_TEMP"); if (null != this.cabCachePath || this.reuseCabinets) { // ensure the cabinet cache path exists if we are going to use it if (null != this.cabCachePath && !Directory.Exists(this.cabCachePath)) { Directory.CreateDirectory(this.cabCachePath); } } if (null != this.basePaths) { foreach (string basePath in this.basePaths) { this.sourcePaths.Add(basePath); } } // load any extensions bool binderExtensionLoaded = false; foreach (string extension in this.extensionList) { Type extensionType = Type.GetType(extension); if (null == extensionType) { throw new WixInvalidExtensionException(extension); } if (extensionType.IsSubclassOf(typeof(BinderExtension))) { object[] extensionArgs = new object[] { this.basePaths, this.cabCachePath, this.reuseCabinets, this.sourcePaths }; BinderExtension binderExtension = Activator.CreateInstance(extensionType, extensionArgs) as BinderExtension; Debug.Assert(null != binderExtension); if (binderExtensionLoaded) { throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, "cannot load binder extension: {0}. light can only load one binder extension and has already loaded binder extension: {1}.", binderExtension.ToString(), binder.Extension.ToString()), "ext"); } binder.Extension = binderExtension; binderExtensionLoaded = true; } else if (extensionType.IsSubclassOf(typeof(SchemaExtension))) { linker.AddExtension((SchemaExtension)Activator.CreateInstance(extensionType)); } else { throw new WixInvalidExtensionException(extension, extensionType, typeof(BinderExtension), typeof(SchemaExtension)); } } // if the binder extension has not been loaded yet use the built-in binder extension if (!binderExtensionLoaded) { binder.Extension = new LightBinderExtension(this.basePaths, this.cabCachePath, this.reuseCabinets, this.sourcePaths); } if (null != this.imagebaseOutputPath) { binder.ImageBaseOutputPath = this.imagebaseOutputPath; } // set the message handlers linker.Message += new MessageEventHandler(this.messageHandler.Display); binder.Message += new MessageEventHandler(this.messageHandler.Display); // load the object schema if (!this.suppressSchema) { Assembly wixAssembly = Assembly.Load("wix"); using (Stream objectsSchemaStream = wixAssembly.GetManifestResourceStream("Microsoft.Tools.WindowsInstallerXml.Xsd.objects.xsd")) { XmlReader reader = new XmlTextReader(objectsSchemaStream); objectSchema.Add("http://schemas.microsoft.com/wix/2003/04/objects", reader); } } Output output = null; // loop through all the believed object files foreach (FileInfo objectFile in this.objectFiles) { currentFile = objectFile; string dirName = Path.GetDirectoryName(currentFile.FullName); if (!StringArrayContains(this.sourcePaths, dirName)) { this.sourcePaths.Add(dirName); } // load the object file into an intermediate object and add it to the list to be linked using (Stream fileStream = new FileStream(currentFile.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { XmlReader fileReader = new XmlTextReader(fileStream); try { XmlReader intermediateReader = fileReader; if (!this.suppressSchema) { intermediateReader = new XmlValidatingReader(fileReader); ((XmlValidatingReader)intermediateReader).Schemas.Add(objectSchema); } Intermediate intermediate = Intermediate.Load(intermediateReader, currentFile.FullName, linker.TableDefinitions, this.suppressVersionCheck); intermediates.Add(intermediate); continue; // next file } catch (WixNotIntermediateException) { // try another format } try { Library library = Library.Load(currentFile.FullName, linker.TableDefinitions, this.suppressVersionCheck); intermediates.AddRange(library.Intermediates); continue; // next file } catch (WixNotLibraryException) { // try another format } output = Output.Load(currentFile.FullName, this.suppressVersionCheck); } } // instantiate the localizer and load any wixloc files if (0 < this.localizationFiles.Count || !this.outputXml) { localizer = new Localizer(); localizer.Message += new MessageEventHandler(this.messageHandler.Display); // load each wixloc file foreach (string localizationFile in this.localizationFiles) { localizer.LoadFromFile(localizationFile); } // immediately stop processing if any errors were found if (this.messageHandler.FoundError) { return(this.messageHandler.PostProcess()); } } // and now for the fun part currentFile = this.outputFile; if (null == output) { // tell the linker about the localizer linker.Localizer = localizer; localizer = null; output = linker.Link((Intermediate[])intermediates.ToArray(typeof(Intermediate))); // if an error occurred during linking, stop processing if (null == output) { return(this.messageHandler.PostProcess()); } } else if (0 != intermediates.Count) { throw new InvalidOperationException("Cannot link object files (.wixobj) files with an output file (.wixout)"); } output.Path = this.outputFile.FullName; // only output the xml if (this.outputXml) { string outputExtension = Path.GetExtension(this.outputFile.FullName); if (null == outputExtension || 0 == outputExtension.Length || ".wix" == outputExtension) { output.Path = Path.ChangeExtension(this.outputFile.FullName, ".wixout"); } output.Save(); } else // finish creating the MSI/MSM { string outputExtension = Path.GetExtension(this.outputFile.FullName); if (null == outputExtension || 0 == outputExtension.Length || ".wix" == outputExtension) { if (OutputType.Module == output.Type) { output.Path = Path.ChangeExtension(this.outputFile.FullName, ".msm"); } else if (OutputType.PatchCreation == output.Type) { output.Path = Path.ChangeExtension(this.outputFile.FullName, ".pcp"); } else { output.Path = Path.ChangeExtension(this.outputFile.FullName, ".msi"); } } // tell the binder about the localizer binder.Localizer = localizer; binder.Bind(output); } currentFile = null; } catch (WixInvalidIdtException) { this.tidy = false; // make sure the IDT files stay around throw; } catch (WixMergeFailureException) { this.tidy = false; // make sure the merge.log stays around throw; } finally { if (null != binder) { if (this.tidy) { if (!binder.DeleteTempFiles()) { Console.WriteLine("Warning, failed to delete temporary directory: {0}", binder.TempFilesLocation); } } else { Console.WriteLine("Temporary directory located at '{0}'.", binder.TempFilesLocation); } } } } catch (WixException we) { // TODO: once all WixExceptions are converted to errors, this clause // should be a no-op that just catches WixFatalErrorException's this.messageHandler.Display("light.exe", "LGHT", we); return(1); } catch (Exception e) { this.OnMessage(WixErrors.UnexpectedException(e.Message, e.GetType().ToString(), e.StackTrace)); if (e is NullReferenceException || e is SEHException) { throw; } } return(this.messageHandler.PostProcess()); }
public MyStack() { var cluster = new Pulumi.Aws.Ecs.Cluster("app-cluster"); // Read back the default VPC and public subnets, which we will use. var vpc = Output.Create(Pulumi.Aws.Ec2.GetVpc.InvokeAsync(new Pulumi.Aws.Ec2.GetVpcArgs { Default = true })); var vpcId = vpc.Apply(vpc => vpc.Id); var subnet = vpcId.Apply(id => Pulumi.Aws.Ec2.GetSubnetIds.InvokeAsync(new Pulumi.Aws.Ec2.GetSubnetIdsArgs { VpcId = id })); var subnetIds = subnet.Apply(s => s.Ids); // Create a SecurityGroup that permits HTTP ingress and unrestricted egress. var webSg = new Pulumi.Aws.Ec2.SecurityGroup("web-sg", new Pulumi.Aws.Ec2.SecurityGroupArgs { VpcId = vpcId, Egress = { new Pulumi.Aws.Ec2.Inputs.SecurityGroupEgressArgs { Protocol = "-1", FromPort = 0, ToPort = 0, CidrBlocks ={ "0.0.0.0/0" } } }, Ingress = { new Pulumi.Aws.Ec2.Inputs.SecurityGroupIngressArgs { Protocol = "tcp", FromPort = 80, ToPort = 80, CidrBlocks ={ "0.0.0.0/0" } } } }); // Create a load balancer to listen for HTTP traffic on port 80. var webLb = new Pulumi.Aws.LB.LoadBalancer("web-lb", new Pulumi.Aws.LB.LoadBalancerArgs { Subnets = subnetIds, SecurityGroups = { webSg.Id } }); var webTg = new Pulumi.Aws.LB.TargetGroup("web-tg", new Pulumi.Aws.LB.TargetGroupArgs { Port = 80, Protocol = "HTTP", TargetType = "ip", VpcId = vpcId }); var webListener = new Pulumi.Aws.LB.Listener("web-listener", new Pulumi.Aws.LB.ListenerArgs { LoadBalancerArn = webLb.Arn, Port = 80, DefaultActions = { new Pulumi.Aws.LB.Inputs.ListenerDefaultActionsArgs { Type = "forward", TargetGroupArn = webTg.Arn, } } }); // Create an IAM role that can be used by our service's task. var taskExecRole = new Pulumi.Aws.Iam.Role("task-exec-role", new Pulumi.Aws.Iam.RoleArgs { AssumeRolePolicy = @"{ ""Version"": ""2008-10-17"", ""Statement"": [{ ""Sid"": """", ""Effect"": ""Allow"", ""Principal"": { ""Service"": ""ecs-tasks.amazonaws.com"" }, ""Action"": ""sts:AssumeRole"" }] }" }); var taskExecAttach = new Pulumi.Aws.Iam.RolePolicyAttachment("task-exec-policy", new Pulumi.Aws.Iam.RolePolicyAttachmentArgs { Role = taskExecRole.Name, PolicyArn = "arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy" }); // Spin up a load balanced service running our container image. var appTask = new Pulumi.Aws.Ecs.TaskDefinition("app-task", new Pulumi.Aws.Ecs.TaskDefinitionArgs { Family = "fargate-task-definition", Cpu = "256", Memory = "512", NetworkMode = "awsvpc", RequiresCompatibilities = { "FARGATE" }, ExecutionRoleArn = taskExecRole.Arn, ContainerDefinitions = @"[{ ""name"": ""my-app"", ""image"": ""nginx"", ""portMappings"": [{ ""containerPort"": 80, ""hostPort"": 80, ""protocol"": ""tcp"" }] }]", }); var appSvc = new Pulumi.Aws.Ecs.Service("app-svc", new Pulumi.Aws.Ecs.ServiceArgs { Cluster = cluster.Arn, DesiredCount = 1, LaunchType = "FARGATE", TaskDefinition = appTask.Arn, NetworkConfiguration = new Pulumi.Aws.Ecs.Inputs.ServiceNetworkConfigurationArgs { AssignPublicIp = true, Subnets = subnetIds, SecurityGroups = { webSg.Id } }, LoadBalancers = { new Pulumi.Aws.Ecs.Inputs.ServiceLoadBalancersArgs { TargetGroupArn = webTg.Arn, ContainerName = "my-app", ContainerPort = 80 } } }, new CustomResourceOptions { DependsOn = { webListener } }); // Export the resulting web address. this.Url = Output.Format($"http://{webLb.DnsName}"); }
protected async Task <(IStreamStore, Action)> GetStore(CancellationToken cancellationToken) { IStreamStore streamStore = null; IDisposable disposable = null; Output.WriteLine(ConsoleColor.Yellow, "Store type:"); await new Menu() .AddSync("InMem", () => streamStore = new InMemoryStreamStore()) .Add("MS SQL V2 (Docker)", async _ => { var fixture = new MsSqlStreamStoreDb("dbo"); Console.WriteLine(fixture.ConnectionString); streamStore = await fixture.GetStreamStore(); disposable = fixture; }) .Add("MS SQL V3 (Docker)", async _ => { var fixture = new MsSqlStreamStoreDbV3("dbo"); Console.WriteLine(fixture.ConnectionString); streamStore = await fixture.GetStreamStore(); disposable = fixture; }) .AddSync("MS SQL V3 (LocalDB)", () => { var sqlLocalDb = new SqlLocalDb(); Console.WriteLine(sqlLocalDb.ConnectionString); streamStore = sqlLocalDb.StreamStore; disposable = sqlLocalDb; }) .Add("Postgres (Docker)", async ct => { var fixture = new PostgresStreamStoreDb("dbo"); Console.WriteLine(fixture.ConnectionString); streamStore = await fixture.GetPostgresStreamStore(true); disposable = fixture; }) .Add("Postgres (Server)", async ct => { Console.Write("Enter the connection string: "); var connectionString = Console.ReadLine(); var fixture = new PostgresStreamStoreDb("dbo", connectionString); Console.WriteLine(fixture.ConnectionString); streamStore = await fixture.GetPostgresStreamStore(true); disposable = fixture; }) .Add("MySql (Docker)", async ct => { var fixture = new MySqlStreamStoreDb(); Console.WriteLine(fixture.ConnectionString); streamStore = await fixture.GetMySqlStreamStore(true); disposable = fixture; }) .Add("MySql (Server)", async ct => { Console.Write("Enter the connection string: "); var connectionString = Console.ReadLine(); var fixture = new MySqlStreamStoreDb(connectionString); Console.WriteLine(fixture.ConnectionString); streamStore = await fixture.GetMySqlStreamStore(true); disposable = fixture; }) .Display(cancellationToken); return( streamStore, () => { streamStore.Dispose(); disposable?.Dispose(); }); }
public static void Sucess() { Stop(); Output.Success("Terminé"); }
public void Generate() { // header Output.WriteLine( "<p>This page contains the API documentation for this MPExtended service, as automatically generated on {0} for version {1} (build {2}). " + "Please do not edit, as your changes will be overwritten.</p>", DateTime.Now.ToString("dd MMM yyy HH:mm", System.Globalization.CultureInfo.InvariantCulture), VersionUtil.GetVersion(Assembly), VersionUtil.GetBuildVersion(Assembly)); UserStream.WriteLine("Generating documentation for assembly {0}", Assembly.GetName().Name); // get all items IEnumerable <DocGenItem> typesToDocument = new List <DocGenItem>(); if (JsonAPI != null) { typesToDocument = JsonAPI.GetMethods().Select(x => new DocGenItem() { URLPrefix = "/json", Reflected = x, Name = x.Name, Order = GenerateSortOrder(x.Name) }); } if (StreamAPI != null) { typesToDocument = typesToDocument.Union(StreamAPI.GetMethods().Select(x => new DocGenItem() { URLPrefix = "/stream", Reflected = x, Name = x.Name, Order = GenerateSortOrder(x.Name) })); } if (Enumerations != null) { typesToDocument = typesToDocument.Union(Enumerations.Select(x => new DocGenItem() { URLPrefix = "", Reflected = x, Name = x.Name, Order = GenerateSortOrder(x.Name), })); } // sort all types typesToDocument = typesToDocument .OrderBy(x => x.Order) .ThenBy(x => x.Name); // print navigation int lastOrder = -1; UserStream.WriteLine("=> Generating documentation header"); Output.WriteLine("<h3>Navigation</h3>"); foreach (var item in typesToDocument) { if (lastOrder != item.Order) { if (lastOrder != -1) { Output.WriteLine("</ul>"); } Output.WriteLine("<h4>{0}</h4><ul>", GetHeadings()[item.Order]); lastOrder = item.Order; } Output.WriteLine("<li><a href=\"#{0}\">{0}</a></li>", item.Name); } Output.WriteLine("</ul>"); // generate all documentation lastOrder = -1; foreach (var item in typesToDocument) { if (lastOrder != item.Order) { Output.WriteLine(String.Format("<h3>{0}</h3>", GetHeadings()[item.Order])); lastOrder = item.Order; } if (item.Reflected is MethodInfo) { GenerateMethodDocumentation(item.Reflected as MethodInfo, item.URLPrefix); } else if (item.Reflected is Type) { GenerateEnumDocumentation(item.Reflected as Type); } } UserStream.WriteLine("=> Done"); Output.Flush(); Output.Close(); }
public void OnError(Exception error) => Output.OnError(error);
/// <summary> /// Logs the given text with the runtime. /// </summary> /// <param name="s">String</param> /// <param name="args">Arguments</param> void IDispatcher.Log(string s, params object[] args) { Output.Log(s, args); }
public void PartOne() => Output .WriteLine($"Adapter checksum: {CalculateJoltageChecksum(Input)}");
public void Resume() { Diagnostics = new List <string>(); Halted = false; while (Pointer < Memory.Length) { var op = Memory[Pointer] % 100; var modes = (Memory[Pointer] - Memory[Pointer] % 100).ToString().Reverse().Skip(2).Concat(new[] { '0', '0', '0' }).Select(c => c - '0').ToArray(); long Arg(long offset) { switch (modes[offset - 1]) { case 1: return(_memory[Pointer + offset]); case 2: return(_memory[BaseAddress + _memory[Pointer + offset]]); default: return(_memory[_memory[Pointer + offset]]); } } long Val(long offset) => modes[offset - 1] == 2 ? _memory[Pointer + offset] + BaseAddress : _memory[Pointer + offset]; var start = Pointer; var action = string.Empty; switch (op) { case 01: { var arg1 = Arg(1); var arg2 = Arg(2); var dest = Val(3); _memory[dest] = arg1 + arg2; action = $"{dest:0000} <- {arg1 + arg2}"; Pointer += 4; break; } case 02: { var arg1 = Arg(1); var arg2 = Arg(2); var dest = Val(3); _memory[dest] = arg1 * arg2; action = $"{dest:0000} <- {arg1 * arg2}"; Pointer += 4; break; } case 03: { if (HaltOnIO && !Input.Any()) { return; } var input = Input.First(); var dest = Val(1); _memory[dest] = input; Input = Input.Skip(1).ToList(); action = $"{dest:0000} <- {input}"; Pointer += 2; break; } case 04: { var src = Val(1); var value = Arg(1); Output.Add(value); action = $"{src:0000} -> {value}"; Pointer += 2; break; } case 05: { var arg1 = Arg(1); var dest = Arg(2); if (arg1 != 0) { action = $"! {dest:0000}"; Pointer = dest; } else { Pointer += 3; } break; } case 06: { var arg1 = Arg(1); var dest = Arg(2); if (arg1 == 0) { action = $"! {dest:0000}"; Pointer = dest; } else { Pointer += 3; } break; } case 07: { var arg1 = Arg(1); var arg2 = Arg(2); var dest = Val(3); if (arg1 < arg2) { action = $"{dest:0000} <- 1"; _memory[dest] = 1; } else { action = $"{dest:0000} <- 0"; _memory[dest] = 0; } Pointer += 4; break; } case 08: { var arg1 = Arg(1); var arg2 = Arg(2); var dest = Val(3); if (arg1 == arg2) { action = $"{dest:0000} <- 1"; _memory[dest] = 1; } else { action = $"{dest:0000} <- 0"; _memory[dest] = 0; } Pointer += 4; break; } case 09: { var arg1 = Arg(1); BaseAddress += arg1; action = $"B <- {arg1}"; Pointer += 2; break; } case 99: { Pointer = Memory.Length; action = "break"; Halted = true; break; } } Diagnostics.Add($"{start:0000}:{op:00}:{string.Join("", modes.Take(3))} {action}"); } }
/// <summary> /// Main running method for the application. /// </summary> /// <param name="args">Commandline arguments to the application.</param> /// <returns>Returns the application error code.</returns> private int Run(string[] args) { Microsoft.Tools.WindowsInstallerXml.Binder binder = new Microsoft.Tools.WindowsInstallerXml.Binder(); try { // parse the command line this.ParseCommandLine(args); // exit if there was an error parsing the command line (otherwise the logo appears after error messages) if (this.messageHandler.EncounteredError) { return(this.messageHandler.LastErrorNumber); } if (null == this.inputFile || null == this.outputFile) { this.showHelp = true; } if (this.showLogo) { Assembly pyroAssembly = Assembly.GetExecutingAssembly(); Console.WriteLine("Microsoft (R) Windows Installer Xml Patch Builder Version {0}", pyroAssembly.GetName().Version.ToString()); Console.WriteLine("Copyright (C) Microsoft Corporation 2003. All rights reserved.\n"); Console.WriteLine(); } if (this.showHelp) { Console.WriteLine(" usage: pyro.exe [-?] [-nologo] inputFile -out outputFile [-t baseline wixTransform]"); Console.WriteLine(); Console.WriteLine(" -cc path to cache built cabinets"); Console.WriteLine(" -ext extension assembly or \"class, assembly\""); Console.WriteLine(" -nologo skip printing logo information"); Console.WriteLine(" -notidy do not delete temporary files (useful for debugging)"); Console.WriteLine(" -out specify output file"); Console.WriteLine(" -reusecab reuse cabinets from cabinet cache"); Console.WriteLine(" -sa suppress assemblies: do not get assembly name information for assemblies"); Console.WriteLine(" -sf suppress files: do not get any file information (equivalent to -sa and -sh)"); Console.WriteLine(" -sh suppress file info: do not get hash, version, language, etc"); Console.WriteLine(" -sw<N> suppress warning with specific message ID"); Console.WriteLine(" -t baseline transform one or more wix transforms and its baseline"); Console.WriteLine(" -v verbose output"); Console.WriteLine(" -wx treat warnings as errors"); Console.WriteLine(" -? this help information"); Console.WriteLine(); Console.WriteLine("Environment variables:"); Console.WriteLine(" WIX_TEMP overrides the temporary directory used for cab extraction, binary extraction, ..."); Console.WriteLine(); Console.WriteLine("Common extensions:"); Console.WriteLine(" .wxi - Windows installer Xml Include file"); Console.WriteLine(" .wxl - Windows installer Xml Localization file"); Console.WriteLine(" .wxs - Windows installer Xml Source file"); Console.WriteLine(" .wixlib - Windows installer Xml Library file (in XML format)"); Console.WriteLine(" .wixobj - Windows installer Xml Object file (in XML format)"); Console.WriteLine(" .wixout - Windows installer Xml Output file (in XML format)"); Console.WriteLine(); Console.WriteLine(" .msi - Windows installer Product Database"); Console.WriteLine(" .msm - Windows installer Merge Module"); Console.WriteLine(" .msp - Windows installer Patch"); Console.WriteLine(" .mst - Windows installer Transform"); Console.WriteLine(" .pcp - Windows installer Patch Creation Package"); Console.WriteLine(); Console.WriteLine("For more information see: http://wix.sourceforge.net"); return(this.messageHandler.LastErrorNumber); } // Load the extension if one was passed on the command line. WixExtension wixExtension = null; if (null != this.extension) { wixExtension = WixExtension.Load(extension); } // Load in transforms ArrayList transforms = new ArrayList(); foreach (DictionaryEntry inputTransform in inputTransforms) { Output transformOutput = Output.Load(inputTransform.Key.ToString(), false, false); PatchTransform patchTransform = new PatchTransform(transformOutput, (string)inputTransform.Value); transforms.Add(patchTransform); } // Load the patch Patch patch = new Patch(); patch.Load(this.inputFile); // Copy transforms into output if (0 < transforms.Count) { patch.AttachTransforms(transforms); } // Create and configure the binder binder = new Microsoft.Tools.WindowsInstallerXml.Binder(); binder.TempFilesLocation = Environment.GetEnvironmentVariable("WIX_TEMP"); binder.WixVariableResolver = this.wixVariableResolver; binder.Message += new MessageEventHandler(this.messageHandler.Display); binder.SuppressAssemblies = this.suppressAssemblies; binder.SuppressFileHashAndInfo = this.suppressFileHashAndInfo; if (this.suppressFiles) { binder.SuppressAssemblies = true; binder.SuppressFileHashAndInfo = true; } // Load the extension if provided and set all its properties if (null != wixExtension) { binder.Extension = wixExtension.BinderExtension; } if (null != this.cabCachePath || this.reuseCabinets) { // ensure the cabinet cache path exists if we are going to use it if (null != this.cabCachePath && !Directory.Exists(this.cabCachePath)) { Directory.CreateDirectory(this.cabCachePath); } } binder.Extension.ReuseCabinets = this.reuseCabinets; binder.Extension.CabCachePath = this.cabCachePath; binder.Extension.Output = patch.PatchOutput; // Bind the patch to an msp. binder.Bind(patch.PatchOutput, this.outputFile); } catch (WixException we) { this.OnMessage(we.Error); } catch (Exception e) { this.OnMessage(WixErrors.UnexpectedException(e.Message, e.GetType().ToString(), e.StackTrace)); if (e is NullReferenceException || e is SEHException) { throw; } } finally { if (null != binder) { if (this.tidy) { if (!binder.DeleteTempFiles()) { Console.WriteLine("Warning, failed to delete temporary directory: {0}", binder.TempFilesLocation); } } else { Console.WriteLine("Temporary directory located at '{0}'.", binder.TempFilesLocation); } } } return(this.messageHandler.LastErrorNumber); }
public void Execute() { var languages = new[] { "csharp", "visualbasic", "java", "python", "ruby", "php", "c++" }; // // First拡張メソッドは、シーケンスの最初の要素を返すメソッド。 // // predicateを指定した場合は、その条件に合致する最初の要素が返る。 // Output.WriteLine("============ First ============"); Output.WriteLine(languages.First()); Output.WriteLine(languages.First(item => item.StartsWith("v"))); // // Last拡張メソッドは、シーケンスの最後の要素を返すメソッド。 // // predicateを指定した場合は、その条件に合致する最後の要素が返る。 // Output.WriteLine("============ Last ============"); Output.WriteLine(languages.Last()); Output.WriteLine(languages.Last(item => item.StartsWith("p"))); // // Single拡張メソッドは、シーケンスの唯一の要素を返すメソッド。 // // Singleを利用する場合、対象となるシーケンスには要素が一つだけ // でないといけない。複数の要素が存在する場合例外が発生する。 // // また、空のシーケンスに対してSingleを呼ぶと例外が発生する。 // // predicateを指定した場合は、その条件に合致するシーケンスの唯一の // 要素が返される。この場合も、結果のシーケンスには要素が一つだけの // 状態である必要がある。条件に合致する要素が複数であると例外が発生する、 // Output.WriteLine("============ Single ============"); var onlyOne = new[] { "csharp" }; Output.WriteLine(onlyOne.Single()); try { // ReSharper disable once UnusedVariable var val = languages.Single(); } catch { Output.WriteLine("複数の要素が存在する状態でSingleを呼ぶと例外が発生する。"); } Output.WriteLine(languages.Single(item => item.EndsWith("y"))); try { // ReSharper disable once UnusedVariable var val = languages.Single(item => item.StartsWith("p")); } catch { Output.WriteLine("条件に合致する要素が複数存在する場合例外が発生する。"); } }
/// <summary> /// Writes the a new line to the current <see cref="Output"/> /// </summary> public TemplateContext WriteLine() { Output.Write(NewLine); return(this); }
public override Output PrintReport(Output task) { return(_impl.PrintReport(task)); }
public void OnCompleted() => Output.OnCompleted();
public static int Main(string[] args) { // Creates an SBMLNamespaces object with the given SBML level, version // package name, package version. SBMLNamespaces sbmlns = new SBMLNamespaces(3, 1, "qual", 1); // create the document SBMLDocument document = new SBMLDocument(sbmlns); // mark qual as required document.setPackageRequired("qual", true); // create the Model Model model = document.createModel(); // create the Compartment Compartment compartment = model.createCompartment(); compartment.setId("c"); compartment.setConstant(true); // Get a QualModelPlugin object plugged in the model object. QualModelPlugin mplugin = (QualModelPlugin)(model.getPlugin("qual")); // create the QualitativeSpecies QualitativeSpecies qs = mplugin.createQualitativeSpecies(); qs.setId("s1"); qs.setCompartment("c"); qs.setConstant(false); qs.setInitialLevel(1); qs.setMaxLevel(4); qs.setName("sss"); // create the Transition Transition t = mplugin.createTransition(); t.setId("d"); t.setSBOTerm(1); Input i = t.createInput(); i.setId("RD"); i.setQualitativeSpecies("s1"); i.setTransitionEffect(libsbml.INPUT_TRANSITION_EFFECT_NONE); i.setSign(libsbml.INPUT_SIGN_NEGATIVE); i.setThresholdLevel(2); i.setName("aa"); Output o = t.createOutput(); o.setId("wd"); o.setQualitativeSpecies("s1"); o.setTransitionEffect(libsbml.OUTPUT_TRANSITION_EFFECT_PRODUCTION); o.setOutputLevel(2); o.setName("aa"); FunctionTerm ft = t.createFunctionTerm(); ASTNode math = libsbml.parseL3Formula("geq(s1, 2)"); ft.setResultLevel(1); ft.setMath(math); DefaultTerm dt = t.createDefaultTerm(); dt.setResultLevel(2); int result = libsbml.writeSBML(document, "qual_example1.xml"); if (result == 1) { Console.WriteLine("Wrote file"); return(0); } else { Console.WriteLine("Failed to write"); return(1); } }
public Output Calculate(Input input) { Output result = new Output() { Input = input }; result.Keping = (int)Math.Ceiling((double)input.Lebar / 12) * input.Set; result.HargaRainbow = input.RainbowQuantity * 5 * input.Set; result.UpahKainA = result.Keping * 3; result.UpahHook = input.Lebar / 4 * input.HargaHook * input.Set; double kainMeterA = (input.Lebar + 15) / 39.0 * input.Set; result.HargaKainA = Math.Round(kainMeterA * input.HargaKainA, 2); result.DetailedBreakdown += GetHargaBreakdown(nameof(Output.HargaKainA), kainMeterA, input.HargaKainA, result.HargaKainA); double kainMeterB = 0.00; double kainMeterC = 0.00; if (input.Tinggi > 24) { kainMeterB = (input.Lebar * 3.5) / 39.0 / 2 * input.Set; kainMeterC = (input.Lebar * 3.5) / 39.0 / 2 * input.Set; } else { kainMeterB = (input.Lebar * 3.5) / 39.0 / 3 * input.Set; kainMeterC = (input.Lebar * 3.5) / 39.0 / 3 * input.Set; } result.HargaKainB = Math.Round(kainMeterB * input.HargaKainA, 2); result.DetailedBreakdown += GetHargaBreakdown(nameof(Output.HargaKainB), kainMeterB, input.HargaKainA, result.HargaKainB); result.HargaKainC = Math.Round(kainMeterC * input.HargaKainA, 2); result.DetailedBreakdown += GetHargaBreakdown(nameof(Output.HargaKainC), kainMeterC, input.HargaKainA, result.HargaKainC); double rendaMeter1 = input.Lebar * 1.5 / 39.0 * input.RendaQuantity * input.Set; result.HargaRenda = Math.Round(rendaMeter1 * input.HargaRenda, 2); result.DetailedBreakdown += GetHargaBreakdown(nameof(Output.HargaRenda), rendaMeter1, input.HargaRenda, result.HargaRenda); double rendaMeter2 = input.Lebar * 3.5 / 39.0 * input.RendaQuantity * input.Set; result.HargaRenda2 = Math.Round(rendaMeter2 * input.HargaRenda, 2); result.DetailedBreakdown += GetHargaBreakdown(nameof(Output.HargaRenda2), rendaMeter2, input.HargaRenda, result.HargaRenda2); double rendaMeter3 = input.Lebar * 3.5 / 39.0 * input.RendaQuantity * input.Set; result.HargaRenda3 = Math.Round(rendaMeter3 * input.HargaRenda, 2); result.DetailedBreakdown += GetHargaBreakdown(nameof(Output.HargaRenda3), rendaMeter3, input.HargaRenda, result.HargaRenda3); result.HargaTaliLangsir = Math.Round(10.0 * input.TaliLangsirQuantity, 2); result.Jumlah = Math.Round(result.HargaRainbow + result.UpahKainA + result.UpahHook + result.HargaKainA + result.HargaKainB + result.HargaKainC + result.HargaRenda + +result.HargaRenda2 + result.HargaRenda3 + result.HargaTaliLangsir, 2); AddOptionalItemsToJumlah(input, result); result.DetailedBreakdown += GetDetailBreakdown(result, result.HargaRainbow, result.UpahKainA, result.UpahHook, result.HargaKainA, result.HargaKainB, result.HargaKainC, result.HargaRenda, +result.HargaRenda2, result.HargaRenda3, result.HargaTaliLangsir); result.TailorInchLabel = "110''"; result.TailorMeterA = 9999; result.TailorMeterB = 9999; result.TailorMeterC = 9999; result.TailorRenda1 = Math.Round((input.Lebar + 10) / 39.0, 2); result.TailorRenda2 = Math.Round((input.Lebar * 3) / 39.0, 2); result.TailorRenda3 = Math.Round((input.Lebar * 3) / 39.0, 2); result.TailorTotalKeping = result.Keping; return(result); }
public FilterOutput(Output opout) { output = opout; }
public static void Error() { Stop(); Output.Error("Erreur"); }
public void TestBasicPubSub(bool preserveOrder, string channelPrefix, bool wildCard) { using (var muxer = Create(channelPrefix: channelPrefix)) { muxer.PreserveAsyncOrder = preserveOrder; var pub = GetAnyMaster(muxer); var sub = muxer.GetSubscriber(); Ping(muxer, pub, sub); HashSet <string> received = new HashSet <string>(); int secondHandler = 0; string subChannel = wildCard ? "a*c" : "abc"; const string pubChannel = "abc"; Action <RedisChannel, RedisValue> handler1 = (channel, payload) => { lock (received) { if (channel == pubChannel) { received.Add(payload); } else { Output.WriteLine((string)channel); } } } , handler2 = (channel, payload) => Interlocked.Increment(ref secondHandler); sub.Subscribe(subChannel, handler1); sub.Subscribe(subChannel, handler2); lock (received) { Assert.Empty(received); } Assert.Equal(0, VolatileWrapper.Read(ref secondHandler)); var count = sub.Publish(pubChannel, "def"); Ping(muxer, pub, sub, 3); lock (received) { Assert.Single(received); } Assert.Equal(1, VolatileWrapper.Read(ref secondHandler)); // unsubscribe from first; should still see second sub.Unsubscribe(subChannel, handler1); count = sub.Publish(pubChannel, "ghi"); Ping(muxer, pub, sub); lock (received) { Assert.Single(received); } Assert.Equal(2, VolatileWrapper.Read(ref secondHandler)); Assert.Equal(1, count); // unsubscribe from second; should see nothing this time sub.Unsubscribe(subChannel, handler2); count = sub.Publish(pubChannel, "ghi"); Ping(muxer, pub, sub); lock (received) { Assert.Single(received); } Assert.Equal(2, VolatileWrapper.Read(ref secondHandler)); Assert.Equal(0, count); } }
public void PartTwo() => Output .WriteLine($"Adapter Combinations: {CountCombinations(Input)}");
protected override void OnTreeBeginFunc(ClusterTree tree, IClusterNode root) { base.OnTreeBeginFunc(tree, root); Output.WriteLine("subgraph[peripheries=0]"); }
public MyStack() { // TODO: Remove after autonaming support is added. var randomSuffix = new RandomString("randomSuffix", new RandomStringArgs { Length = 10, Special = false, Upper = false, }); var config = new Config(); var storageAccountName = config.Get("storageAccountName") != null?Output.Create(config.Get("storageAccountName") !) : randomSuffix.Result.Apply(result => $"site{result}"); var cdnEndpointName = config.Get("cdnEndpointName") != null?Output.Create(config.Get("cdnEndpointName") !) : storageAccountName.Apply(result => $"cdn-endpnt-{result}"); var cdnProfileName = config.Get("cdnProfileName") != null?Output.Create(config.Get("cdnProfileName") !) : storageAccountName.Apply(result => $"cdn-profile-{result}"); var resourceGroup = new Resources.ResourceGroup("resourceGroup", new Resources.ResourceGroupArgs { ResourceGroupName = randomSuffix.Result.Apply(result => $"rg{result}"), }); var profile = new Cdn.Profile("profile", new Cdn.ProfileArgs { ProfileName = cdnProfileName, ResourceGroupName = resourceGroup.Name, Sku = new Cdn.Inputs.SkuArgs { Name = Cdn.SkuName.Standard_Microsoft, }, }); var storageAccount = new Storage.StorageAccount("storageAccount", new Storage.StorageAccountArgs { AccessTier = Storage.AccessTier.Hot, AccountName = storageAccountName, EnableHttpsTrafficOnly = true, Encryption = new Storage.Inputs.EncryptionArgs { KeySource = Storage.KeySource.Microsoft_Storage, Services = new Storage.Inputs.EncryptionServicesArgs { Blob = new Storage.Inputs.EncryptionServiceArgs { Enabled = true, }, File = new Storage.Inputs.EncryptionServiceArgs { Enabled = true, }, }, }, Kind = Storage.Kind.StorageV2, NetworkRuleSet = new Storage.Inputs.NetworkRuleSetArgs { Bypass = Storage.Bypass.AzureServices, DefaultAction = Storage.DefaultAction.Allow, }, ResourceGroupName = resourceGroup.Name, Sku = new Storage.Inputs.SkuArgs { Name = Storage.SkuName.Standard_LRS, }, }); var endpointOrigin = storageAccount.PrimaryEndpoints.Apply(pe => pe.Web.Replace("https://", "").Replace("/", "")); var endpoint = new Cdn.Endpoint("endpoint", new Cdn.EndpointArgs { ContentTypesToCompress = { }, EndpointName = cdnEndpointName, IsCompressionEnabled = false, IsHttpAllowed = false, IsHttpsAllowed = true, OriginHostHeader = endpointOrigin, Origins = { new Cdn.Inputs.DeepCreatedOriginArgs { HostName = endpointOrigin, HttpsPort = 443, Name = Output.Tuple(randomSuffix.Result, cdnEndpointName).Apply(t => $"{t.Item2}-origin-{t.Item1}"), }, }, ProfileName = profile.Name, QueryStringCachingBehavior = Cdn.QueryStringCachingBehavior.NotSet, ResourceGroupName = resourceGroup.Name, }); // Enable static website support var staticWebsite = new Storage.StorageAccountStaticWebsite("staticWebsite", new Storage.StorageAccountStaticWebsiteArgs { AccountName = storageAccount.Name, ResourceGroupName = resourceGroup.Name, IndexDocument = "index.html", Error404Document = "404.html", }); var index_html = new Storage.Blob("index_html", new Storage.BlobArgs { BlobName = "index.html", ResourceGroupName = resourceGroup.Name, AccountName = storageAccount.Name, ContainerName = staticWebsite.ContainerName, Type = Storage.BlobType.Block, Source = new FileAsset("./wwwroot/index.html"), ContentType = "text/html", }); var notfound_html = new Storage.Blob("notfound_html", new Storage.BlobArgs { BlobName = "404.html", ResourceGroupName = resourceGroup.Name, AccountName = storageAccount.Name, ContainerName = staticWebsite.ContainerName, Type = Storage.BlobType.Block, Source = new FileAsset("./wwwroot/404.html"), ContentType = "text/html", }); // Web endpoint to the website this.StaticEndpoint = storageAccount.PrimaryEndpoints.Apply(primaryEndpoints => primaryEndpoints.Web); // CDN endpoint to the website. // Allow it some time after the deployment to get ready. this.CdnEndpoint = endpoint.HostName.Apply(hostName => $"https://{hostName}"); }
internal DirectionDistanceCalculator(Enterprise enterprise, Output output, Input input) : base("Direction/distance calculator", output) { _enterprise = enterprise; _input = input; }
public override Stream GetReportPreview(Output task) { return(_impl.GetReportPreview(task)); }
/// <summary> /// Переопределение метода ToString которые повзращает строку с выходным значением синапса нейрона /// </summary> /// <returns>Выходное значением синапса нейрона</returns> public override string ToString() { return(Output.ToString()); }
public static Transaction Deserialize(byte[] rawTransaction) { if (rawTransaction == null) { throw new ArgumentNullException(nameof(rawTransaction)); } int version; Input[] inputs; Output[] outputs; uint lockTime; uint expiry; var cursor = new ByteCursor(rawTransaction); try { version = cursor.ReadInt32(); if (version != SupportedVersion) { var reason = $"Unsupported transaction version `{version}`"; throw new EncodingException(typeof(Transaction), cursor, reason); } // Prefix deserialization var prefixInputCount = cursor.ReadCompact(); if (prefixInputCount > TransactionRules.MaxInputs) { var reason = $"Input count {prefixInputCount} exceeds maximum value {TransactionRules.MaxInputs}"; throw new EncodingException(typeof(Transaction), cursor, reason); } inputs = new Input[prefixInputCount]; for (int i = 0; i < (int)prefixInputCount; i++) { var previousHash = new Blake256Hash(cursor.ReadBytes(Blake256Hash.Length)); var previousIndex = cursor.ReadUInt32(); var previousTree = cursor.ReadByte(); var previousOutPoint = new OutPoint(previousHash, previousIndex, previousTree); var sequence = cursor.ReadUInt32(); inputs[i] = Input.CreateFromPrefix(previousOutPoint, sequence); } var outputCount = cursor.ReadCompact(); if (outputCount > TransactionRules.MaxOutputs) { var reason = $"Output count {outputCount} exceeds maximum value {TransactionRules.MaxOutputs}"; throw new EncodingException(typeof(Transaction), cursor, reason); } outputs = new Output[outputCount]; for (int i = 0; i < (int)outputCount; i++) { var amount = (Amount)cursor.ReadInt64(); var outputVersion = cursor.ReadUInt16(); var pkScript = cursor.ReadVarBytes(TransactionRules.MaxPayload); outputs[i] = new Output(amount, outputVersion, pkScript); } lockTime = cursor.ReadUInt32(); expiry = cursor.ReadUInt32(); // Witness deserialization var witnessInputCount = cursor.ReadCompact(); if (witnessInputCount != prefixInputCount) { var reason = $"Input counts in prefix and witness do not match ({prefixInputCount} != {witnessInputCount})"; throw new EncodingException(typeof(Transaction), cursor, reason); } for (int i = 0; i < (int)witnessInputCount; i++) { var inputAmount = (Amount)cursor.ReadInt64(); var blockHeight = cursor.ReadUInt32(); var blockIndex = cursor.ReadUInt32(); var signatureScript = cursor.ReadVarBytes(TransactionRules.MaxPayload); inputs[i] = Input.AddWitness(inputs[i], inputAmount, blockHeight, blockIndex, signatureScript); } } catch (Exception ex) when(!(ex is EncodingException)) { throw new EncodingException(typeof(Transaction), cursor, ex); } return(new Transaction(version, inputs, outputs, lockTime, expiry)); }
internal async Task <ProcessResult> RunDotNetNewAsync( string templateName, string auth = null, string language = null, bool useLocalDB = false, bool noHttps = false, string[] args = null, // Used to set special options in MSBuild IDictionary <string, string> environmentVariables = null) { var hiveArg = $"--debug:custom-hive \"{TemplatePackageInstaller.CustomHivePath}\""; var argString = $"new {templateName} {hiveArg}"; environmentVariables ??= new Dictionary <string, string>(); if (!string.IsNullOrEmpty(auth)) { argString += $" --auth {auth}"; } if (!string.IsNullOrEmpty(language)) { argString += $" -lang {language}"; } if (useLocalDB) { argString += $" --use-local-db"; } if (noHttps) { argString += $" --no-https"; } if (args != null) { foreach (var arg in args) { argString += " " + arg; } } // Save a copy of the arguments used for better diagnostic error messages later. // We omit the hive argument and the template output dir as they are not relevant and add noise. ProjectArguments = argString.Replace(hiveArg, ""); argString += $" -o {TemplateOutputDir}"; // Only run one instance of 'dotnet new' at once, as a workaround for // https://github.com/aspnet/templating/issues/63 await DotNetNewLock.WaitAsync(); try { Output.WriteLine("Acquired DotNetNewLock"); using var execution = ProcessEx.Run(Output, AppContext.BaseDirectory, DotNetMuxer.MuxerPathOrDefault(), argString, environmentVariables); await execution.Exited; return(new ProcessResult(execution)); } finally { DotNetNewLock.Release(); Output.WriteLine("Released DotNetNewLock"); } }
public Job CreateJobWithSetNumberImagesSpritesheet( string projectId, string location, string inputUri, string outputUri) { // Create the client. TranscoderServiceClient client = TranscoderServiceClient.Create(); // Build the parent location name. LocationName parent = new LocationName(projectId, location); // Build the job config. VideoStream videoStream0 = new VideoStream { H264 = new VideoStream.Types.H264CodecSettings { BitrateBps = 550000, FrameRate = 60, HeightPixels = 360, WidthPixels = 640 } }; AudioStream audioStream0 = new AudioStream { Codec = "aac", BitrateBps = 64000 }; // Generates a 10x10 spritesheet of small images from the input video. // To preserve the source aspect ratio, you should set the // SpriteWidthPixels field or the SpriteHeightPixels field, but not // both (the API will automatically calculate the missing field). For // this sample, we don't care about the aspect ratio so we set both // fields. SpriteSheet smallSpriteSheet = new SpriteSheet { FilePrefix = SmallSpritesheetFilePrefix, SpriteHeightPixels = 32, SpriteWidthPixels = 64, ColumnCount = 10, RowCount = 10, TotalCount = 100 }; // Generates a 10x10 spritesheet of larger images from the input video. // input video. To preserve the source aspect ratio, you should set the // SpriteWidthPixels field or the SpriteHeightPixels field, but not // both (the API will automatically calculate the missing field). For // this sample, we don't care about the aspect ratio so we set both // fields. SpriteSheet largeSpriteSheet = new SpriteSheet { FilePrefix = LargeSpritesheetFilePrefix, SpriteHeightPixels = 72, SpriteWidthPixels = 128, ColumnCount = 10, RowCount = 10, TotalCount = 100 }; ElementaryStream elementaryStream0 = new ElementaryStream { Key = "video_stream0", VideoStream = videoStream0 }; ElementaryStream elementaryStream1 = new ElementaryStream { Key = "audio_stream0", AudioStream = audioStream0 }; MuxStream muxStream0 = new MuxStream { Key = "sd", Container = "mp4", ElementaryStreams = { "video_stream0", "audio_stream0" } }; Input input = new Input { Key = "input0", Uri = inputUri }; Output output = new Output { Uri = outputUri }; JobConfig jobConfig = new JobConfig { Inputs = { input }, Output = output, ElementaryStreams = { elementaryStream0, elementaryStream1 }, MuxStreams = { muxStream0 }, SpriteSheets = { smallSpriteSheet, largeSpriteSheet } }; // Build the job. Job newJob = new Job(); newJob.InputUri = inputUri; newJob.OutputUri = outputUri; newJob.Config = jobConfig; // Call the API. Job job = client.CreateJob(parent, newJob); // Return the result. return job; }
public bool Initialize(out string errorMsg) { try { errorMsg = null; List <ModeDescription> adapterModes = new List <ModeDescription>(); _dx11factory = new Factory1(); using (Adapter1 adapter = _dx11factory.GetAdapter1(0)) { using (Output output = adapter.Outputs[0]) { IsB8G8R8A8_UNormSupport = false; foreach (var mode in output.GetDisplayModeList(Format.B8G8R8A8_UNorm, DisplayModeEnumerationFlags.Interlaced)) { IsB8G8R8A8_UNormSupport = true; adapterModes.Add(mode); } MainAdapter = adapter.Description.Description; logger.Info("GPU found : {0}", MainAdapter); //GetResource Level FeatureLevel maxSupportLevel = Device.GetSupportedFeatureLevel(adapter); logger.Info("Maximum supported DirectX11 level = {0}", maxSupportLevel.ToString()); if (maxSupportLevel == FeatureLevel.Level_9_1 || maxSupportLevel == FeatureLevel.Level_9_2 || maxSupportLevel == FeatureLevel.Level_9_3) { errorMsg = "Your graphical card doesn't support at minimum DirectX 10 feature, current feature : " + maxSupportLevel.ToString(); return(false); } int DedicatedGPU = adapter.Description.DedicatedVideoMemory / (1024 * 1024); if (DedicatedGPU < 0) { DedicatedGPU = 0; } int DedicatedSystem = adapter.Description.DedicatedSystemMemory / (1024 * 1024); if (DedicatedSystem < 0) { DedicatedSystem = 0; } int SharedSystem = adapter.Description.SharedSystemMemory / (1024 * 1024); if (SharedSystem < 0) { SharedSystem = 0; } logger.Info("GPU Memory : Dedicated from GPU : {0}MB, Shared : {1}MB, Dedicated from System : {2}MB. Total : {3}MB", DedicatedGPU, DedicatedSystem, SharedSystem, DedicatedGPU + DedicatedSystem + SharedSystem); logger.Info("B8G8R8A8_UNormSupport compatibility = {0}", IsB8G8R8A8_UNormSupport); #if DEBUG foreach (var mode in adapterModes) { logger.Trace("[{1}:{2}], format : {0}, RefreshRate : {3}hz, Scaling : {4}, ScanlineMode : {5}", mode.Format, mode.Width, mode.Height, (float)mode.RefreshRate.Numerator / mode.RefreshRate.Denominator, mode.Scaling, mode.ScanlineOrdering); } #endif } } RefreshResources(); GetMSAAQualities(Format.B8G8R8A8_UNorm); //Remove the some built-in fonctionnality of DXGI _dx11factory.MakeWindowAssociation(_renderForm.Handle, WindowAssociationFlags.IgnoreAll | WindowAssociationFlags.IgnoreAltEnter); _renderForm.ResizeBegin += _renderForm_ResizeBegin; _renderForm.ResizeEnd += _renderForm_ResizeEnd; _renderForm.Resize += _renderForm_Resize; _renderForm.LostFocus += GameWindow_LostFocus; _renderForm.GotFocus += GameWindow_GotFocus; _renderForm.Show(); _renderForm.Focus(); _renderForm.TopMost = true; HasFocus = true; _renderForm.TopMost = false; return(true); } catch (Exception e) { errorMsg = e.Message; return(false); } }