/// <exception cref="ArgumentNullException"> /// Thrown when a null reference is passed to a method that does not accept it as a /// valid argument. /// </exception> internal HttpRequestMessage CreateAlbumRequest(string url, string title = null, string description = null, AlbumPrivacy? privacy = null, AlbumLayout? layout = null, string coverId = null, IEnumerable<string> imageIds = null) { if (string.IsNullOrWhiteSpace(url)) throw new ArgumentNullException(nameof(url)); var parameters = new Dictionary<string, string>(); if (privacy != null) parameters.Add(nameof(privacy), $"{privacy}".ToLower()); if (layout != null) parameters.Add(nameof(layout), $"{layout}".ToLower()); if (coverId != null) parameters.Add("cover", coverId); if (title != null) parameters.Add(nameof(title), title); if (description != null) parameters.Add(nameof(description), description); if (imageIds != null) parameters.Add("ids", string.Join(",", imageIds)); var request = new HttpRequestMessage(HttpMethod.Post, url) { Content = new FormUrlEncodedContent(parameters.ToArray()) }; return request; }
/// <exception cref="ArgumentNullException"></exception> internal HttpRequestMessage CreateCommentRequest(string url, string comment, string imageId, string parentId) { if (string.IsNullOrEmpty(url)) throw new ArgumentNullException(nameof(url)); if (string.IsNullOrEmpty(comment)) throw new ArgumentNullException(nameof(comment)); if (string.IsNullOrEmpty(imageId)) throw new ArgumentNullException(nameof(imageId)); var parameters = new Dictionary<string, string> { {"image_id", imageId}, {"comment", comment} }; if (!string.IsNullOrWhiteSpace(parentId)) parameters.Add("parent_id", parentId); var request = new HttpRequestMessage(HttpMethod.Post, url) { Content = new FormUrlEncodedContent(parameters.ToArray()) }; return request; }
/// <exception cref="ArgumentNullException"> /// Thrown when a null reference is passed to a method that does not accept it as a /// valid argument. /// </exception> internal HttpRequestMessage GetTokenByPinRequest(string url, string pin, string clientId, string clientSecret) { if (string.IsNullOrWhiteSpace(url)) throw new ArgumentNullException(nameof(url)); if (string.IsNullOrWhiteSpace(pin)) throw new ArgumentNullException(nameof(pin)); if (string.IsNullOrWhiteSpace(clientId)) throw new ArgumentNullException(nameof(clientId)); if (string.IsNullOrWhiteSpace(clientSecret)) throw new ArgumentNullException(nameof(clientSecret)); var parameters = new Dictionary<string, string> { {"client_id", clientId}, {"client_secret", clientSecret}, {"grant_type", "pin"}, {"pin", pin} }; var request = new HttpRequestMessage(HttpMethod.Post, url) { Content = new FormUrlEncodedContent(parameters.ToArray()) }; return request; }
/// <exception cref="ArgumentNullException"> /// Thrown when a null reference is passed to a method that does not accept it as a /// valid argument. /// </exception> internal HttpRequestMessage PublishToGalleryRequest(string url, string title, string topicId = null, bool? bypassTerms = null, bool? mature = null) { if (string.IsNullOrWhiteSpace(url)) throw new ArgumentNullException(nameof(url)); if (string.IsNullOrWhiteSpace(title)) throw new ArgumentNullException(nameof(title)); var parameters = new Dictionary<string, string> {{nameof(title), title}}; if (topicId != null) parameters.Add("topic", topicId); if (bypassTerms != null) parameters.Add("terms", $"{bypassTerms}".ToLower()); if (mature != null) parameters.Add(nameof(mature), $"{mature}".ToLower()); var request = new HttpRequestMessage(HttpMethod.Post, url) { Content = new FormUrlEncodedContent(parameters.ToArray()) }; return request; }
static int GetGems(string[] stones) { var elements = new Dictionary<char, bool>(); for (var j = 0; j < stones[0].Length; j++) { var c = stones[0][j]; if (!elements.ContainsKey(stones[0][j])) { elements.Add(c, true); } } for (var i = 1; i < stones.Length; i++) { var arr = elements.ToArray(); for (var j = 0; j < arr.Length; j++) { var c = arr[j].Key; if (stones[i].IndexOf(c) == -1) { elements.Remove(c); } } } return elements.Keys.Count(); }
internal HttpRequestMessage PublishRequest(string url, string title, string topic, bool? acceptTerms, bool? nsfw) { if (string.IsNullOrEmpty(url)) throw new ArgumentNullException(nameof(url)); if (string.IsNullOrEmpty(title)) throw new ArgumentNullException(nameof(title)); var parameters = new Dictionary<string, string>() { { "title", title } }; if (!string.IsNullOrEmpty(topic)) parameters.Add("topic", topic); if (acceptTerms != null) parameters.Add("terms", (bool)acceptTerms ? "1" : "0"); if (nsfw != null) parameters.Add("mature", (bool)nsfw ? "1" : "0"); var request = new HttpRequestMessage(HttpMethod.Post, url) { Content = new FormUrlEncodedContent(parameters.ToArray()) }; return request; }
public RecognizedGesture(Dictionary<string, SimpleGesture[]> gestures) { if (gestures == null || gestures.Count < 1) throw new ArgumentNullException("gestures"); Gesture = gestures.ToArray(); Machines = (from g in Gesture select new KeyValuePair<string, RecognitionSequenceMachine>(g.Key, new RecognitionSequenceMachine(g.Value))).ToArray(); }
public static Script ParseScript(string s) { MemoryStream result = new MemoryStream(); if(mapOpNames.Count == 0) { mapOpNames = new Dictionary<string, OpcodeType>(Op._OpcodeByName); foreach(var kv in mapOpNames.ToArray()) { if(kv.Key.StartsWith("OP_", StringComparison.Ordinal)) { var name = kv.Key.Substring(3, kv.Key.Length - 3); mapOpNames.AddOrReplace(name, kv.Value); } } } var words = s.Split(' ', '\t', '\n'); foreach(string w in words) { if(w == "") continue; if(w.All(l => l.IsDigit()) || (w.StartsWith("-") && w.Substring(1).All(l => l.IsDigit()))) { // Number long n = long.Parse(w); Op.GetPushOp(new BigInteger(n)).WriteTo(result); } else if(w.StartsWith("0x") && HexEncoder.IsWellFormed(w.Substring(2))) { // Raw hex data, inserted NOT pushed onto stack: var raw = Encoders.Hex.DecodeData(w.Substring(2)); result.Write(raw, 0, raw.Length); } else if(w.Length >= 2 && w.StartsWith("'") && w.EndsWith("'")) { // Single-quoted string, pushed as data. NOTE: this is poor-man's // parsing, spaces/tabs/newlines in single-quoted strings won't work. var b = TestUtils.ToBytes(w.Substring(1, w.Length - 2)); Op.GetPushOp(b).WriteTo(result); } else if(mapOpNames.ContainsKey(w)) { // opcode, e.g. OP_ADD or ADD: result.WriteByte((byte)mapOpNames[w]); } else { Assert.True(false, "Invalid test"); return null; } } return new Script(result.ToArray()); }
public MainMenuSource (Dictionary<string,Action> buttonDictionary) { TableCells = new List<UITableViewCell> (); ButtonArray = buttonDictionary.ToArray (); foreach (var buttonProperty in ButtonArray) { var cell = new UITableViewCell (); cell.TextLabel.Text = buttonProperty.Key; TableCells.Add (cell); } }
public void DictionaryExtensions_Unit_AsReadOnly_Optimal() { IDictionary<String, DateTime> dictionary = new Dictionary<String, DateTime>() { { "One", DateTime.Today.AddDays(-1) }, { "Two", DateTime.Today }, { "Three", DateTime.Today.AddDays(1) } }; ReadOnlyDictionary<String, DateTime> actual = DictionaryExtensions.AsReadOnly(dictionary); CollectionAssert.AreEquivalent(dictionary.ToArray(pair => pair), actual.ToArray(pair => pair)); }
internal HttpRequestMessage ReportCommentRequest(string url, ReportReason reason) { var parameters = new Dictionary<string, string> { {"reason", ((int) reason).ToString()} }; var request = new HttpRequestMessage(HttpMethod.Post, url) { Content = new FormUrlEncodedContent(parameters.ToArray()) }; return request; }
static void Main(string[] args) { Dictionary<string, string> dictionary = new Dictionary<string, string>(); dictionary.Add("contacts[0].Name", "张三"); dictionary.Add("contacts[0].PhoneNo", "123456789"); dictionary.Add("contacts[0].EmailAddress", "*****@*****.**"); dictionary.Add("contacts[1].Name", "李四"); dictionary.Add("contacts[1].PhoneNo", "987654321"); dictionary.Add("contacts[1].EmailAddress", "*****@*****.**"); NameValuePairsValueProvider valueProvider = new NameValuePairsValueProvider(dictionary.ToArray(), null); //Prefix="" Console.WriteLine("Prefix: <Empty>"); Console.WriteLine("{0,-14}{1}", "Key", "Value"); IDictionary<string, string> keys = valueProvider.GetKeysFromPrefix(string.Empty); foreach (var item in keys) { Console.WriteLine("{0,-14}{1}", item.Key, item.Value); } //Prefix="contact" Console.WriteLine("\nPrefix: contact"); Console.WriteLine("{0,-14}{1}", "Key", "Value"); keys = valueProvider.GetKeysFromPrefix("contact"); foreach (var item in keys) { Console.WriteLine("{0,-14}{1}", item.Key, item.Value); } //Prefix="contacts[0]" Console.WriteLine("\nPrefix: contacts[0]"); Console.WriteLine("{0,-14}{1}", "Key", "Value"); keys = valueProvider.GetKeysFromPrefix("contacts[0]"); foreach (var item in keys) { Console.WriteLine("{0,-14}{1}", item.Key, item.Value); } //Prefix="contacts[1]" Console.WriteLine("\nPrefix: contacts[1]"); Console.WriteLine("{0,-14}{1}", "Key", "Value"); keys = valueProvider.GetKeysFromPrefix("contacts[1]"); foreach (var item in keys) { Console.WriteLine("{0,-14}{1}", item.Key, item.Value); } }
/// <exception cref="ArgumentNullException"></exception> /// <exception cref="ArgumentException"></exception> internal HttpRequestMessage UpdateAccountSettingsRequest( string url, string bio = null, bool? publicImages = null, bool? messagingEnabled = null, AlbumPrivacy? albumPrivacy = null, bool? acceptedGalleryTerms = null, string username = null, bool? showMature = null, bool? newsletterSubscribed = null) { if (string.IsNullOrEmpty(url)) throw new ArgumentNullException(nameof(url)); var parameters = new Dictionary<string, string>(); if (publicImages != null) parameters.Add("public_images", $"{publicImages}".ToLower()); if (messagingEnabled != null) parameters.Add("messaging_enabled", $"{messagingEnabled}".ToLower()); if (albumPrivacy != null) parameters.Add("album_privacy", $"{albumPrivacy}".ToLower()); if (acceptedGalleryTerms != null) parameters.Add("accepted_gallery_terms", $"{acceptedGalleryTerms}".ToLower()); if (showMature != null) parameters.Add("show_mature", $"{showMature}".ToLower()); if (newsletterSubscribed != null) parameters.Add("newsletter_subscribed", $"{newsletterSubscribed}".ToLower()); if (!string.IsNullOrWhiteSpace(username)) parameters.Add(nameof(username), username); if (!string.IsNullOrWhiteSpace(bio)) parameters.Add(nameof(bio), bio); var request = new HttpRequestMessage(HttpMethod.Post, url) { Content = new FormUrlEncodedContent(parameters.ToArray()) }; return request; }
internal HttpRequestMessage CommentRequest(string url, string comment) { if (string.IsNullOrEmpty(url)) throw new ArgumentNullException(nameof(url)); var parameters = new Dictionary<string, string>() { { "comment", comment } }; var request = new HttpRequestMessage(HttpMethod.Post, url) { Content = new FormUrlEncodedContent(parameters.ToArray()) }; return request; }
public async Task HttpClient_PostAsync_ResponseContentAreEqual() { var fakeHttpMessageHandler = new FakeHttpMessageHandler(); var fakeResponse = new HttpResponseMessage(HttpStatusCode.OK) {Content = new StringContent("post response")}; fakeHttpMessageHandler.AddFakeResponse(new Uri("http://example.org/test"), fakeResponse); var httpClient = new HttpClient(fakeHttpMessageHandler); var parameters = new Dictionary<string, string> {{"Name", "bob"}}; var content = new FormUrlEncodedContent(parameters.ToArray()); var response = await httpClient.PostAsync("http://example.org/test", content); var stringResponse = await response.Content.ReadAsStringAsync(); Assert.AreEqual("post response", stringResponse); }
internal HttpRequestMessage PostReportRequest(string url, Reporting reason) { if (string.IsNullOrEmpty(url)) throw new ArgumentNullException(nameof(url)); var parameters = new Dictionary<string, string>() { { "reason", ((int)reason).ToString() } }; var request = new HttpRequestMessage(HttpMethod.Post, url) { Content = new FormUrlEncodedContent(parameters.ToArray()) }; return request; }
public Highscores() { InitializeComponent(); dataGridView1.Columns.Add("Место", "Место"); dataGridView1.Columns.Add("Ник", "Ник"); dataGridView1.Columns.Add("Очки", "Очки"); dataGridView1.Dock=DockStyle.Fill; dataGridView1.AllowUserToAddRows = false; Dictionary<string,object> dict = new Dictionary<string, object>(); JavaScriptSerializer js = new JavaScriptSerializer(); FileStream fs = new FileStream("highscores.txt",FileMode.OpenOrCreate); byte[] bytes = new byte[fs.Length]; fs.Read(bytes,0,(int)fs.Length); string ttemp = Encoding.UTF8.GetString(bytes); fs.Close(); dict = js.Deserialize<Dictionary<string, object>>(ttemp); List<KeyValuePair<string,object>> list =new List<KeyValuePair<string,object>>(); list.AddRange(dict.ToArray()); list.Sort((x, y) => ((int)x.Value > (int)y.Value)?-1:1); for (int i = 0; i < 10; i++) { DataGridViewRow row = new DataGridViewRow(); row.Cells.Add(new DataGridViewTextBoxCell() { Value = (i+1).ToString() }); row.Cells.Add(new DataGridViewTextBoxCell() { Value = list[i].Key }); row.Cells.Add(new DataGridViewTextBoxCell() { Value = list[i].Value }); this.dataGridView1.Rows.Add(row); } dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells); dataGridView1.AutoResizeRows(DataGridViewAutoSizeRowsMode.AllCells); }
private void T( string text, Dictionary<int, int> syntactic, Dictionary<int, int> semantic, Dictionary<int, int> expectedOutput) { Paths.SolutionDestinationFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); var expectedArray = expectedOutput.ToArray(); var result = TypeScriptSupport.PrepareRanges( syntactic.Select(p => new ClassifiedRange(text, p.Key, p.Value)).ToArray(), semantic.Select(p => new ClassifiedRange(text, p.Key, p.Value)).ToArray(), text); Assert.AreEqual(expectedOutput.Count, result.Length, "Lengths aren't same"); for (int i = 0; i < expectedOutput.Count; i++) { Assert.AreEqual(expectedArray[i].Key, result[i].start); Assert.AreEqual(expectedArray[i].Value, result[i].length); } }
internal HttpRequestMessage MarkAsReadRequest(string url, int[] ids) { if (string.IsNullOrEmpty(url)) throw new ArgumentNullException(nameof(url)); if (ids == null) throw new ArgumentNullException(nameof(ids)); var parameters = new Dictionary<string, string>() { {"ids", string.Format(",", ids)} }; var request = new HttpRequestMessage(HttpMethod.Post, url) { Content = new FormUrlEncodedContent(parameters.ToArray()) }; return request; }
/// <exception cref="ArgumentNullException"> /// Thrown when a null reference is passed to a method that does not accept it as a /// valid argument. /// </exception> internal HttpRequestMessage AddFilteredOutGalleryTagRequest(string url, string tag) { if (string.IsNullOrWhiteSpace(url)) throw new ArgumentNullException(nameof(url)); if (string.IsNullOrWhiteSpace(tag)) throw new ArgumentNullException(nameof(tag)); var parameters = new Dictionary<string, string> { {nameof(tag), tag} }; var request = new HttpRequestMessage(HttpMethod.Post, url) { Content = new FormUrlEncodedContent(parameters.ToArray()) }; return request; }
/// <exception cref="ArgumentNullException"></exception> internal HttpRequestMessage UpdateImageRequest(string url, string title = null, string description = null) { if (string.IsNullOrEmpty(url)) throw new ArgumentNullException(nameof(url)); var parameters = new Dictionary<string, string>(); if (title != null) parameters.Add(nameof(title), title); if (description != null) parameters.Add(nameof(description), description); var request = new HttpRequestMessage(HttpMethod.Post, url) { Content = new FormUrlEncodedContent(parameters.ToArray()) }; return request; }
internal HttpRequestMessage PostConversationMessageRequest(string url, string body) { if (string.IsNullOrEmpty(url)) throw new ArgumentNullException(nameof(url)); if (string.IsNullOrEmpty(body)) throw new ArgumentNullException(nameof(body)); var parameters = new Dictionary<string, string>() { { "body", body } }; var request = new HttpRequestMessage(HttpMethod.Post, url) { Content = new FormUrlEncodedContent(parameters.ToArray()) }; return request; }
/// <exception cref="ArgumentNullException"> /// Thrown when a null reference is passed to a method that does not accept it as a /// valid argument. /// </exception> internal HttpRequestMessage MarkNotificationsViewedRequest(string url, IEnumerable<string> notificationIds) { if (string.IsNullOrWhiteSpace(url)) throw new ArgumentNullException(nameof(url)); if (notificationIds == null) throw new ArgumentNullException(nameof(notificationIds)); var parameters = new Dictionary<string, string> { {"ids", string.Join(",", notificationIds)} }; var request = new HttpRequestMessage(HttpMethod.Post, url) { Content = new FormUrlEncodedContent(parameters.ToArray()) }; return request; }
/// <exception cref="ArgumentNullException"> /// Thrown when a null reference is passed to a method that does not accept it as a /// valid argument. /// </exception> internal HttpRequestMessage CreateMessageRequest(string url, string body) { if (string.IsNullOrWhiteSpace(url)) throw new ArgumentNullException(nameof(url)); if (string.IsNullOrWhiteSpace(body)) throw new ArgumentNullException(nameof(body)); var parameters = new Dictionary<string, string> { {nameof(body), body} }; var request = new HttpRequestMessage(HttpMethod.Post, url) { Content = new FormUrlEncodedContent(parameters.ToArray()) }; return request; }
/// <exception cref="ArgumentNullException"> /// Thrown when a null reference is passed to a method that does not accept it as a /// valid argument. /// </exception> internal HttpRequestMessage AddAlbumImagesRequest(string url, IEnumerable<string> imageIds) { if (string.IsNullOrWhiteSpace(url)) throw new ArgumentNullException(nameof(url)); if (imageIds == null) throw new ArgumentNullException(nameof(imageIds)); var parameters = new Dictionary<string, string> { {"ids", string.Join(",", imageIds)} }; var request = new HttpRequestMessage(HttpMethod.Put, url) { Content = new FormUrlEncodedContent(parameters.ToArray()) }; return request; }
/// <exception cref="ArgumentNullException"> /// Thrown when a null reference is passed to a method that does not accept it as a /// valid argument. /// </exception> internal HttpRequestMessage AddCustomGalleryTagsRequest(string url, IEnumerable<string> tags) { if (string.IsNullOrWhiteSpace(url)) throw new ArgumentNullException(nameof(url)); if (tags == null) throw new ArgumentNullException(nameof(tags)); var parameters = new Dictionary<string, string> { {nameof(tags), string.Join(",", tags)} }; var request = new HttpRequestMessage(HttpMethod.Put, url) { Content = new FormUrlEncodedContent(parameters.ToArray()) }; return request; }
public static Animation CreateAnimation() { var rng = new Random(12); var bigArraySize = 62; var ops = new List<Operation>(); ops.Add(new Operation {Key = -1, Interval = new Interval(1, bigArraySize)}); var remainingNumbers = Enumerable.Range(1, bigArraySize).ToList(); var activeIntervals = new Dictionary<int, Interval>(); activeIntervals[-1] = new Interval(1, bigArraySize); for (var i = 0; i < 50; i++) { if (activeIntervals.Count == 0) break; var rr = activeIntervals.ToArray(); if (i < 4) { //} || rng.Next(5) == 0) { var parent = activeIntervals[-1]; //rng.Next(activeIntervals.Count)].Value; var rep = 0; while (true) { var v1 = rng.Next(parent.Length); var v2 = rng.Next(parent.Length); if (v1 == v2) continue; rep += 1; if (rep < 10 && (!remainingNumbers.Contains(v1) || !remainingNumbers.Contains(v2))) continue; var offset = Math.Min(v2, v1); var len = Math.Max(v2, v1) - offset + 1; var x = new Interval(parent.Offset + offset, len/2); ops.Add(new Operation {Key = i, Interval = x}); activeIntervals[i] = x; break; } } else { var x = rng.Next(activeIntervals.Count); var k = i == 4 ? -1 : rr[x].Key; ops.Add(new Operation() {Key=k}); activeIntervals.Remove(k); } } return CreateAnimationOfOperations(new Interval(1 - 5, bigArraySize + 10), new Interval(1, bigArraySize), ops.ToArray()); }
ISemantic E(NewExpression nex) { // http://www.d-programming-language.org/expression.html#NewExpression ISemantic[] possibleTypes = null; if (nex.Type is IdentifierDeclaration) possibleTypes = TypeDeclarationResolver.Resolve((IdentifierDeclaration)nex.Type, ctxt, filterForTemplateArgs: false); else possibleTypes = TypeDeclarationResolver.Resolve(nex.Type, ctxt); var ctors = new Dictionary<DMethod, TemplateIntermediateType>(); if (possibleTypes == null) return null; foreach (var t in possibleTypes) { var ct = DResolver.StripAliasSymbol(t as AbstractType) as TemplateIntermediateType; if (ct!=null && !ct.Definition.ContainsAttribute(DTokens.Abstract)) foreach (var ctor in GetConstructors(ct)) ctors.Add(ctor, ct); } MemberSymbol finalCtor = null; var kvArray = ctors.ToArray(); /* * TODO: Determine argument types and filter out ctor overloads. */ if (kvArray.Length != 0) finalCtor = new MemberSymbol(kvArray[0].Key, kvArray[0].Value, nex); else if (possibleTypes.Length != 0) return AbstractType.Get(possibleTypes[0]); return finalCtor; }
public void Write(GitHubFlowArguments gitHubFlowConfiguration, Dictionary<string, string> variables, SemanticVersion nextBuildNumber) { if (string.IsNullOrEmpty(gitHubFlowConfiguration.ToFile)) return; var stringBuilder = new StringBuilder(); stringBuilder.AppendLine("{"); var variableList = variables.ToArray(); for (var index = 0; index < variableList.Length; index++) { var variable = variableList[index]; stringBuilder.AppendFormat(" \"{0}\": \"{1}\"{2}", variable.Key, variable.Value, index < variableList.Length - 1 ? "," : string.Empty); stringBuilder.AppendLine(); } stringBuilder.AppendLine("}"); var directoryName = Path.GetDirectoryName(gitHubFlowConfiguration.ToFile); if (!Directory.Exists(directoryName)) Directory.CreateDirectory(directoryName); File.WriteAllText(gitHubFlowConfiguration.ToFile, stringBuilder.ToString()); }
static void Main(string[] args) { Dictionary<string, string> dictionary = new Dictionary<string, string>(); dictionary.Add("contact.Name", "张三"); dictionary.Add("contact.PhoneNo", "123456789"); dictionary.Add("contact.EmailAddress", "*****@*****.**"); dictionary.Add("contact.Address.Province", "江苏"); dictionary.Add("contact.Address.City", "苏州"); dictionary.Add("contact.Address.District", "工业园区"); dictionary.Add("contact.Address.Street", "星湖街328号"); NameValuePairsValueProvider valueProvider = new NameValuePairsValueProvider(dictionary.ToArray(), null); //Prefix="" Console.WriteLine("Prefix: <Empty>"); Console.WriteLine("{0,-14}{1}", "Key", "Value"); IDictionary<string, string> keys = valueProvider.GetKeysFromPrefix(string.Empty); foreach (var item in keys) { Console.WriteLine("{0,-14}{1}", item.Key, item.Value); } //Prefix="contact" Console.WriteLine("\nPrefix: contact"); Console.WriteLine("{0,-14}{1}", "Key", "Value"); keys = valueProvider.GetKeysFromPrefix("contact"); foreach (var item in keys) { Console.WriteLine("{0,-14}{1}", item.Key, item.Value); } //Prefix="contact.Address" Console.WriteLine("\nPrefix: contact.Address"); Console.WriteLine("{0,-14}{1}", "Key", "Value"); keys = valueProvider.GetKeysFromPrefix("contact.Address"); foreach (var item in keys) { Console.WriteLine("{0,-14}{1}", item.Key, item.Value); } }
public static void ApplyTranslation(string originalPath, string outputPath) { var index = 0; var subtitleLocation = originalPath.Remove(originalPath.LastIndexOf('.')); var set = LoadSubtitle(index, subtitleLocation); var buffer = new Dictionary <long, byte[]>(); using (var output = File.Create(outputPath)) using (var input = File.OpenRead(originalPath)) { while (input.Position < input.Length) { var section = StreamSection.FromStream(input); switch (section.Type) { case SectionType.Raw: var rawSection = section as RawSection; using (var ms = new MemoryStream()) { RawSection.ToStream(ms, rawSection); AppendToBuffer(buffer, rawSection.First, ms.ToArray()); } break; case SectionType.EndOfStream: if (buffer.Count > 0) { var source = buffer.ToArray().OrderBy(x => x.Key); foreach (var item in source) { output.Write(item.Value); } buffer.Clear(); } EndOfStreamSection.ToStream(output, section as EndOfStreamSection); index++; set = LoadSubtitle(index, subtitleLocation); break; case SectionType.Subtitle: var subtitleSection = section as SubtitleSection; SubtitleSection loaded; using (var ms = new MemoryStream()) { if (set != null && set.TryGetValue(GetKey(subtitleSection), out loaded)) { if (loaded.Texts.Where(x => x.TranslatedText != null).Count() > 0) { var copy = loaded.Texts.ToArray(); for (int i = 0; i < copy.Length; i++) { loaded.Texts.Clear(); loaded.Texts.Add(copy[i]); loaded.BaseTime = copy[i].Start; SubtitleSection.ToStreamTranslated(ms, loaded); AppendToBuffer(buffer, loaded.BaseTime, ms.ToArray()); } } else { SubtitleSection.ToStream(ms, subtitleSection); AppendToBuffer(buffer, subtitleSection.BaseTime, ms.ToArray()); } } else { SubtitleSection.ToStream(ms, subtitleSection); AppendToBuffer(buffer, subtitleSection.BaseTime, ms.ToArray()); } } break; } } } }
// Public method for sending changes to the monitoring status public async Task <Scrobble> SendMonitoringStatusChanged(MediaItem mediaItem, MonitoringStatus newMonitoringStatus) { string updateMethod = string.Empty; // Create an empty list of parameters var baseParameters = new Dictionary <string, string>(); PlayStatusResponse response = null; // If monitoring has started if (newMonitoringStatus == MonitoringStatus.StartedMonitoring) { // Use the updateNowPlaying API method updateMethod = "track.updateNowPlaying"; // Add details of the track to the parameter list baseParameters.Add("track", mediaItem.TrackName); baseParameters.Add("artist", mediaItem.ArtistName); if (!string.IsNullOrEmpty(mediaItem.AlbumName)) { baseParameters.Add("album", mediaItem.AlbumName); } if (mediaItem.TrackLength > 0) { baseParameters.Add("duration", mediaItem.TrackLength.ToString()); } } // Or the monitoring status is stopped else if (newMonitoringStatus == MonitoringStatus.StoppedMonitoring) { // Use the removeNowPlaying API method updateMethod = "track.removeNowPlaying"; } // If a method has been specified (ie. someone hasn't tried to send a monitoring state > 1 if (!string.IsNullOrEmpty(updateMethod)) { // Add the required parameters (including the session token etc) AddRequiredRequestParams(baseParameters, updateMethod, _sessionToken.Key); // Convert the paremeters into body content FormUrlEncodedContent postContent = new FormUrlEncodedContent(baseParameters); // Send the request and get the response response = await Post <PlayStatusResponse>(updateMethod, postContent, baseParameters.ToArray()).ConfigureAwait(false); #if DebugAPICalls Console.WriteLine($"Sent Playing Status request ({updateMethod}), response:\r\n {response}"); #endif } return(response?.NowPlaying); }
private void Init() { // New permissions permission.RegisterPermission(permBalance, this); permission.RegisterPermission(permDeposit, this); permission.RegisterPermission(permSetMoney, this); permission.RegisterPermission(permTransfer, this); permission.RegisterPermission(permWithdraw, this); permission.RegisterPermission(permWipe, this); // Deprecated permissions permission.RegisterPermission(permAdmin, this); AddLocalizedCommand("CommandBalance", "BalanceCommand"); AddLocalizedCommand("CommandDeposit", "DepositCommand"); AddLocalizedCommand("CommandSetMoney", "SetMoneyCommand"); AddLocalizedCommand("CommandTransfer", "TransferCommand"); AddLocalizedCommand("CommandWithdraw", "WithdrawCommand"); AddLocalizedCommand("CommandWipe", "WipeCommand"); data = Interface.Oxide.DataFileSystem.GetFile(Name); try { Dictionary <ulong, double> temp = data.ReadObject <Dictionary <ulong, double> >(); try { storedData = new StoredData(); foreach (KeyValuePair <ulong, double> old in temp.ToArray()) { if (!storedData.Balances.ContainsKey(old.Key.ToString())) { storedData.Balances.Add(old.Key.ToString(), old.Value); } } changed = true; } catch { // Ignored } } catch { storedData = data.ReadObject <StoredData>(); changed = true; } string[] playerData = storedData.Balances.Keys.ToArray(); if (config.MaximumBalance > 0) { foreach (string p in playerData.Where(p => storedData.Balances[p] > config.MaximumBalance)) { storedData.Balances[p] = config.MaximumBalance; changed = true; } } if (config.RemoveUnused) { foreach (string p in playerData.Where(p => storedData.Balances[p].Equals(config.StartAmount))) { storedData.Balances.Remove(p); changed = true; } } SaveData(); }
private void handleImageGrabbed(object sender, EventArgs args) { PreTick(); try { Mat = new Mat(); if (Capture.Retrieve(Mat)) { if (Mat.IsEmpty) { return; } using (var vector = new VectorOfByte()) { CvInvoke.Imencode(getStringfromEncodingFormat(format), Mat, vector, encodingParams?.ToArray()); data = vector.ToArray(); } } OnTick?.Invoke(); } catch (CvException e) { logger.Add($@"{e.Status} {e.Message}", osu.Framework.Logging.LogLevel.Verbose, e); } }
/// <summary> /// Gets the menu. /// </summary> /// <param name="assemblyname"> /// The assembly name. /// </param> /// <param name="menuname"> /// The menu name. /// </param> /// <returns> /// The <see cref="Menu" />. /// </returns> public static Menu GetMenu(string assemblyname, string menuname) { return(RootMenus.ToArray().FirstOrDefault(x => x.Key == assemblyname + "." + menuname).Value); }
/// <exception cref="T:System.ArgumentNullException"> /// Thrown when a null reference is passed to a method that does not accept it as a /// valid argument. /// </exception> internal HttpRequestMessage UpdateAlbumRequest( string url, string title = null, string description = null, AlbumPrivacy?privacy = null, AlbumLayout?layout = null, string coverId = null, IEnumerable <string> imageIds = null) { if (string.IsNullOrWhiteSpace(url)) { throw new ArgumentNullException(nameof(url)); } Dictionary <string, string> source = new Dictionary <string, string>(); if (privacy.HasValue) { source.Add(nameof(privacy), string.Format("{0}", (object)privacy).ToLower()); } if (layout.HasValue) { source.Add(nameof(layout), string.Format("{0}", (object)layout).ToLower()); } if (coverId != null) { source.Add("cover", coverId); } if (title != null) { source.Add(nameof(title), title); } if (description != null) { source.Add(nameof(description), description); } if (imageIds != null) { source.Add("ids", string.Join(",", imageIds)); } return(new HttpRequestMessage(HttpMethod.Post, url) { Content = (HttpContent) new FormUrlEncodedContent((IEnumerable <KeyValuePair <string, string> >)source.ToArray <KeyValuePair <string, string> >()) }); }
private string GetRunningPipsMessage(string standardStatus, string perfInfo) { lock (m_runningPipsLock) { if (m_buildViewModel == null) { return(null); } var context = m_buildViewModel.Context; Contract.Assert(context != null); if (m_runningPips == null) { m_runningPips = new Dictionary <PipId, PipInfo>(); } DateTime thisCollection = DateTime.UtcNow; // Use the viewer's interface to fetch the info about which pips are currently running. foreach (var pip in m_buildViewModel.RetrieveExecutingProcessPips()) { PipInfo runningInfo; if (!m_runningPips.TryGetValue(pip.PipId, out runningInfo)) { // This is a new pip that wasn't running the last time the currently running pips were queried Pip p = pip.HydratePip(); runningInfo = new PipInfo() { PipDescription = p.GetShortDescription(context), FirstSeen = DateTime.UtcNow, }; m_runningPips.Add(pip.PipId, runningInfo); } runningInfo.LastSeen = DateTime.UtcNow; } // Build up a string based on the snapshot of what pips are being running using (var pooledWrapper = Pools.StringBuilderPool.GetInstance()) { StringBuilder sb = pooledWrapper.Instance; sb.Append(TimeSpanToString(TimeDisplay.Seconds, DateTime.UtcNow - BaseTime)); sb.Append(' '); sb.Append(standardStatus); if (!string.IsNullOrWhiteSpace(perfInfo)) { sb.Append(". " + perfInfo); } // Display the log file location if there have been errors logged. This allows the user to open the // log files while the build is running to see errors that have scrolled off the console var errors = Interlocked.Read(ref m_errorsLogged); if (errors > 0 && m_logsDirectory != null) { sb.AppendLine(); sb.AppendFormat(Strings.App_Errors_LogsDirectory, errors, m_logsDirectory); } int pipCount = 0; foreach (var item in m_runningPips.ToArray().OrderBy(kvp => kvp.Value.FirstSeen)) { if (item.Value.LastSeen < thisCollection) { // If the pip was last seen before this collection it is no longer running and should be removed m_runningPips.Remove(item.Key); } else { pipCount++; if (pipCount <= m_maxStatusPips) { // Otherwise include it in the string string info = string.Format(CultureInfo.InvariantCulture, " {0} {1}", TimeSpanToString(TimeDisplay.Seconds, item.Value.LastSeen - item.Value.FirstSeen), item.Value.PipDescription); // Don't have a trailing newline for the last message; if (sb.Length > 0) { sb.AppendLine(); } sb.Append(info); } } } if (pipCount > m_maxStatusPips) { sb.AppendLine(); sb.AppendFormat(Strings.ConsoleListener_AdditionalPips, pipCount - m_maxStatusPips); } return(sb.ToString()); } } }
private void CheckForExpiredIP() { List <string> ipAddressesToForget = new List <string>(); bool fileChanged = false; KeyValuePair <string, DateTime>[] blockList; KeyValuePair <string, IPBlockCount>[] ipBlockCountList; // brief lock, we make copies of everything and work on the copies so we don't hold a lock too long lock (ipBlocker) { blockList = ipBlockerDate.ToArray(); ipBlockCountList = ipBlocker.ToArray(); } DateTime now = DateTime.UtcNow; // Check the block list for expired IPs. foreach (KeyValuePair <string, DateTime> keyValue in blockList) { // never un-ban a blacklisted entry if (config.IsBlackListed(keyValue.Key)) { continue; } TimeSpan elapsed = now - keyValue.Value; if (elapsed > config.BanTime) { Log.Write(LogLevel.Error, "Un-banning ip address {0}", keyValue.Key); lock (ipBlocker) { // take the ip out of the lists and mark the file as changed so that the ban script re-runs without this ip ipBlockerDate.Remove(keyValue.Key); ipBlocker.Remove(keyValue.Key); fileChanged = true; } } } // if we are allowing ip addresses failed login attempts to expire and get reset back to 0 if (config.ExpireTime.TotalSeconds > 0) { // Check the list of failed login attempts, that are not yet blocked, for expired IPs. foreach (KeyValuePair <string, IPBlockCount> keyValue in ipBlockCountList) { if (config.IsBlackListed(keyValue.Key)) { continue; } // Find this IP address in the block list. var block = from b in blockList where b.Key == keyValue.Key select b; // If this IP is not yet blocked, and an invalid login attempt has not been made in the past timespan, see if we should forget it. if (block.Count() == 0) { TimeSpan elapsed = (now - keyValue.Value.LastFailedLogin); if (elapsed > config.ExpireTime) { Log.Write(LogLevel.Info, "Forgetting ip address {0}", keyValue.Key); ipAddressesToForget.Add(keyValue.Key); } } } // Remove the IPs that have expired. lock (ipBlocker) { foreach (string ip in ipAddressesToForget) { // no need to mark the file as changed because this ip was not banned, it only had some number of failed login attempts ipBlocker.Remove(ip); } } } // if the file changed, re-run the ban script with the updated list of ip addresses if (fileChanged) { ExecuteBanScript(); } }
private void InteractiveHistorySearchLoop(int direction) { var searchFromPoint = _currentHistoryIndex; var searchPositions = new Stack <int>(); searchPositions.Push(_currentHistoryIndex); if (Options.HistoryNoDuplicates) { _hashedHistory = new Dictionary <string, int>(); } var toMatch = new StringBuilder(64); while (true) { var key = ReadKey(); _dispatchTable.TryGetValue(key, out var handler); var function = handler?.Action; if (function == ReverseSearchHistory) { UpdateHistoryDuringInteractiveSearch(toMatch.ToString(), -1, ref searchFromPoint); } else if (function == ForwardSearchHistory) { UpdateHistoryDuringInteractiveSearch(toMatch.ToString(), +1, ref searchFromPoint); } else if (function == BackwardDeleteChar || key == Keys.Backspace || key == Keys.CtrlH) { if (toMatch.Length > 0) { toMatch.Remove(toMatch.Length - 1, 1); _statusBuffer.Remove(_statusBuffer.Length - 2, 1); searchPositions.Pop(); searchFromPoint = _currentHistoryIndex = searchPositions.Peek(); var moveCursor = Options.HistorySearchCursorMovesToEnd ? HistoryMoveCursor.ToEnd : HistoryMoveCursor.DontMove; UpdateFromHistory(moveCursor); if (_hashedHistory != null) { // Remove any entries with index < searchFromPoint because // we are starting the search from this new index - we always // want to find the latest entry that matches the search string foreach (var pair in _hashedHistory.ToArray()) { if (pair.Value < searchFromPoint) { _hashedHistory.Remove(pair.Key); } } } // Prompt may need to have 'failed-' removed. var toMatchStr = toMatch.ToString(); var startIndex = _buffer.ToString().IndexOf(toMatchStr, Options.HistoryStringComparison); if (startIndex >= 0) { _statusLinePrompt = direction > 0 ? _forwardISearchPrompt : _backwardISearchPrompt; _current = startIndex; _emphasisStart = startIndex; _emphasisLength = toMatch.Length; Render(); } } else { Ding(); } } else if (key == Keys.Escape) { // End search break; } else if (function == Abort) { // Abort search EndOfHistory(); break; } else { char toAppend = key.KeyChar; if (char.IsControl(toAppend)) { PrependQueuedKeys(key); break; } toMatch.Append(toAppend); _statusBuffer.Insert(_statusBuffer.Length - 1, toAppend); var toMatchStr = toMatch.ToString(); var startIndex = _buffer.ToString().IndexOf(toMatchStr, Options.HistoryStringComparison); if (startIndex < 0) { UpdateHistoryDuringInteractiveSearch(toMatchStr, direction, ref searchFromPoint); } else { _current = startIndex; _emphasisStart = startIndex; _emphasisLength = toMatch.Length; Render(); } searchPositions.Push(_currentHistoryIndex); } } }
/// <summary> /// AresTcpSocket can also act as a miniature WebServer and can handle HEAD/GET/POST requests /// </summary> private void ClientHttpRequestReceived(object sender, HttpRequestEventArgs e) { if (!(sender is ISocket socket)) { return; } Stats.PacketsReceived++; Stats.AddInput(e.Transferred); PendingConnection connection; lock (pending) connection = pending.Find(s => s.Equals(sender)); if (connection != null) { //upgrading to a websocket connection? if (e.Headers.TryGetValue("CONNECTION", out string upgrade) && e.Headers.TryGetValue("UPGRADE", out string upgrade_type)) { if (Config.UseWebSockets) { e.Headers.TryGetValue("ORIGIN", out string origin); e.Headers.TryGetValue("SEC-WEBSOCKET-VERSION", out string version); e.Headers.TryGetValue("SEC-WEBSOCKET-KEY", out string key); var my_headers = new Dictionary <string, string>(); if (!string.IsNullOrEmpty(origin)) { my_headers.Add("Access-Control-Allow-Origin", origin); my_headers.Add("Access-Control-Allow-Credentials", "true"); my_headers.Add("Access-Control-Allow-Headers", "content-type"); } connection.Socket.IsWebSocket = true; connection.Socket.SendBytes(Http.WebSocketAcceptHeaderBytes(key, my_headers.ToArray())); } else //websockets disabled { Logging.Info( "AresServer", "Connection rejected from '{0}'. Chatroom is not configured to allow WebSocket connections.", socket.RemoteEndPoint.Address ); connection.Socket.Disconnect(); } } else if (PluginHost.OnHttpRequest(socket, e)) { Logging.Info( "AresServer", "Http request from '{0}' for resource '{1}' denied.", socket.RemoteEndPoint.Address, e.RequestUri ); connection.Socket.Disconnect(); } } else { //Http request is not from a pending connection IClient user = Users.Find(s => s.Socket == sender); //if not pending, they have at least sent a login packet but are processing, if (user != null && user.LoggedIn) { if (PluginHost.OnHttpRequest(user, e)) { Logging.Info( "AresServer", "Http request from '{0}' ({1}) for resource '{2}' denied.", user.Name, user.ExternalIp, e.RequestUri ); } } else { //this doesn't appear to happen typically, it would just be racing against !LoggedIn if it did. //dc for now unless it causes problems in the future. connection.Socket.Disconnect(); } } }
/// <summary> /// 디렉토리를 탐색하고 데이터베이스 파일을 생성합니다. /// </summary> /// <param name="path"></param> private async void ProcessPath(string path) { FileIndexor fi = new FileIndexor(); await fi.ListingDirectoryAsync(path); string root_directory = fi.RootDirectory; Dictionary <string, ZipArtistsArtistModel> artist_dic = new Dictionary <string, ZipArtistsArtistModel>(); foreach (var x in fi.Directories) { await Application.Current.Dispatcher.BeginInvoke(new Action( delegate { ProgressText.Text = x.Item1; })); Dictionary <string, HitomiJsonModel> article_data = new Dictionary <string, HitomiJsonModel>(); DateTime last_access_time = DateTime.MinValue; DateTime craete_time = DateTime.Now; foreach (var file in x.Item3) { if (!file.FullName.EndsWith(".zip")) { continue; } var zipFile = ZipFile.Open(file.FullName, ZipArchiveMode.Read); if (zipFile.GetEntry("Info.json") == null) { continue; } using (var reader = new StreamReader(zipFile.GetEntry("Info.json").Open())) { var json_model = JsonConvert.DeserializeObject <HitomiJsonModel>(reader.ReadToEnd()); article_data.Add(Path.GetFileName(file.FullName), json_model); } if (file.LastWriteTime < craete_time) { craete_time = file.LastWriteTime; } if (last_access_time < file.LastWriteTime) { last_access_time = file.LastWriteTime; } } if (article_data.Count == 0) { continue; } artist_dic.Add(x.Item1.Substring(root_directory.Length), new ZipArtistsArtistModel { ArticleData = article_data, CreatedDate = craete_time.ToString(), LastAccessDate = last_access_time.ToString(), ArtistName = Path.GetFileName(Path.GetDirectoryName(x.Item1)), Size = (long)x.Item2 }); } model = new ZipArtistsModel(); model.RootDirectory = root_directory; model.Tag = path; model.ArtistList = artist_dic.ToArray(); var tick = DateTime.Now.Ticks; ZipArtistsModelManager.SaveModel($"zipartists-{Path.GetFileName(root_directory)}-{tick}.json", model); rate_filename = $"zipartists-{Path.GetFileName(root_directory)}-{tick}-rating.json"; algorithm.Build(model); artist_list = artist_dic.ToList(); elems.Clear(); artist_list.ForEach(x => elems.Add(Tuple.Create(x, Tuple.Create(root_directory + x.Key, 0, false)))); day_before = raws = elems; sort_data(align_column, align_row); await Application.Current.Dispatcher.BeginInvoke(new Action( delegate { CollectStatusPanel.Visibility = Visibility.Collapsed; ArticleCount.Text = $"작가 {artist_dic.Count.ToString("#,#")}명"; PageCount.Text = $"작품 {artist_list.Select(x => x.Value.ArticleData.Count).Sum().ToString("#,#")}개"; max_page = artist_dic.Count / show_elem_per_page; initialize_page(); })); stack_clear(); stack_push(); }
public override PresentationResult OnInspectorGui(PresentationParamater parameter) { GUIStyle guiStyle = new GUIStyle(); EditorGUILayout.BeginVertical(guiStyle); Change change = new Change(); BalancePresentationData balancePresentationData = parameter.PresentationData as BalancePresentationData ?? new BalancePresentationData(); bool isFoldout = balancePresentationData.IsFoldout; balancePresentationData.IsFoldout = EditorGUILayout.Foldout(balancePresentationData.IsFoldout, parameter.Title); change.IsPresentationChanged = isFoldout != balancePresentationData.IsFoldout; Balance balance = (Balance)parameter.Instance; if (balance == null) { balance = new Balance(); } balance.SyncValues(); Dictionary <string, int> values = balance.Values; NumberPresentation[] numberPresentations = _numberPresentations; _numberPresentations = new NumberPresentation[values.Count]; KeyValuePair <string, int>[] pairs = values.ToArray(); if (balancePresentationData.IsFoldout) { change.ChildrenChange = new Change[_numberPresentations.Length]; for (int i = 0; i < _numberPresentations.Length; i++) { if (i < numberPresentations.Length) { _numberPresentations[i] = numberPresentations[i]; } PresentationParamater presentationParamater = new PresentationParamater(pairs[i].Value, null, pairs[i].Key, typeof(int), new PresentationSite { Base = parameter.Instance, BaseSite = parameter.PresentationSite, BasePresentation = this, SiteType = PresentationSiteType.None }, parameter.FortInspector); if (_numberPresentations[i] == null) { _numberPresentations[i] = new NumberPresentation(); } EditorGUILayout.BeginHorizontal(guiStyle); GUILayout.Space(FortInspector.ItemSpacing); EditorGUILayout.BeginVertical(guiStyle); PresentationResult presentationResult = _numberPresentations[i].OnInspectorGui(presentationParamater); EditorGUILayout.EndVertical(); EditorGUILayout.EndHorizontal(); change.ChildrenChange[i] = presentationResult.Change; values[pairs[i].Key] = (int)presentationResult.Result; } } EditorGUILayout.EndVertical(); return(new PresentationResult { Change = change, PresentationData = balancePresentationData, Result = balance }); }
private static int ProcessConfiguration(Settings settings) { settings.Require(nameof(settings)); var importSolutions = new List <ExportedSolution>(); var exportSolutions = settings.SolutionConfigs .Where(s => s.SolutionName.IsNotEmpty()).ToArray(); if (connectionFile.IsNotEmpty()) { var connectionParams = GetConnectionParams(); if (settings.SourceConnectionString.IsEmpty()) { log.Log("Using default source connection string from file."); settings.SourceConnectionString = connectionParams.SourceConnectionString; } if (settings.DestinationConnectionStrings?.Any() != true) { log.Log("Using default destination connection strings from file."); settings.DestinationConnectionStrings = connectionParams.DestinationConnectionStrings; } } if (exportSolutions.Any()) { importSolutions.AddRange(ExportSolutions(settings.SourceConnectionString, exportSolutions)); } var loadSolutionsConfig = settings.SolutionConfigs .Where(s => s.SolutionFile.IsNotEmpty()) .Select(s => s).ToArray(); if (loadSolutionsConfig.Any()) { importSolutions.AddRange(LoadSolutions(loadSolutionsConfig)); } var failures = new Dictionary <string, List <ExportedSolution> >(); ImportSolutions(settings.DestinationConnectionStrings, importSolutions, failures); while (failures.Any()) { log.Log("Some solutions failed to import.", LogLevel.Warning); if (isAutoRetryOnError) { log.Log($"Remaining retries: {retryCount}."); if (retryCount-- <= 0) { log.Log("Retry count has expired.", LogLevel.Warning); return(1); } log.Log($"Automatically retrying to import ..."); } else { Console.WriteLine(); Console.Write($"{failures.Sum(p => p.Value.Count)} total failures. Try again [y/n]? "); var answer = Console.ReadKey().KeyChar; Console.WriteLine(); if (answer != 'y') { return(1); } Console.WriteLine(); } var failuresCopy = failures.ToArray(); failures = new Dictionary <string, List <ExportedSolution> >(); foreach (var pair in failuresCopy) { ImportSolutions(new[] { pair.Key }, pair.Value, failures); } } return(0); }
object ReadCore() { SkipSpaces(); int c = PeekChar(); if (c < 0) { throw JsonError("Incomplete JSON input"); } switch (c) { case '[': ReadChar(); var list = new List <object> (); SkipSpaces(); if (PeekChar() == ']') { ReadChar(); return(list); } while (true) { list.Add(ReadCore()); SkipSpaces(); c = PeekChar(); if (c != ',') { break; } ReadChar(); continue; } if (ReadChar() != ']') { throw JsonError("JSON array must end with ']'"); } return(list.ToArray()); case '{': ReadChar(); var obj = new Dictionary <string, object> (); SkipSpaces(); if (PeekChar() == '}') { ReadChar(); return(obj); } while (true) { SkipSpaces(); if (PeekChar() == '}') { break; } string name = ReadStringLiteral(); SkipSpaces(); Expect(':'); SkipSpaces(); obj [name] = ReadCore(); // it does not reject duplicate names. SkipSpaces(); c = ReadChar(); if (c == ',') { continue; } if (c == '}') { break; } } #if MONOTOUCH int idx = 0; KeyValuePair <string, object> [] ret = new KeyValuePair <string, object> [obj.Count]; foreach (KeyValuePair <string, object> kvp in obj) { ret [idx++] = kvp; } return(ret); #else return(obj.ToArray()); #endif case 't': Expect("true"); return(true); case 'f': Expect("false"); return(false); case 'n': Expect("null"); // FIXME: what should we return? return((string)null); case '"': return(ReadStringLiteral()); default: if ('0' <= c && c <= '9' || c == '-') { return(ReadNumericLiteral()); } else { throw JsonError(String.Format("Unexpected character '{0}'", (char)c)); } } }
void Save(bool onlyupdated) { var created = 0; var updated = 0; var deleted = 0; var sw = new Stopwatch(); sw.Start(); var inactive = Statistics.GetInactive(); RemoveRouterInfo(inactive); using (var s = GetStore()) { lock ( RouterInfos ) { foreach (var one in RouterInfos.ToArray()) { try { if (one.Value.Value.Deleted) { if (one.Value.Value.StoreIx > 0) { s.Delete(one.Value.Value.StoreIx); } RouterInfos.Remove(one.Key); ++deleted; continue; } if (!onlyupdated || (onlyupdated && one.Value.Value.Updated)) { var rec = new BufLen[] { (BufLen)(int)StoreRecordId.StoreIdRouterInfo, new BufLen(one.Value.Key.ToByteArray()) }; if (one.Value.Value.StoreIx > 0) { s.Write(rec, one.Value.Value.StoreIx); ++updated; } else { one.Value.Value.StoreIx = s.Write(rec); ++created; } one.Value.Value.Updated = false; } } catch (Exception ex) { Logging.LogDebug("NetDb: Save: Store exception: " + ex.ToString()); one.Value.Value.StoreIx = -1; } } } var lookup = s.GetMatching(e => (StoreRecordId)e[0] == StoreRecordId.StoreIdConfig, 1); Dictionary <I2PString, int> str2ix = new Dictionary <I2PString, int>(); foreach (var one in lookup) { var reader = new BufRefLen(one.Value); reader.Read32(); var key = new I2PString(reader); str2ix[key] = one.Key; } AccessConfig(delegate(Dictionary <I2PString, I2PString> settings) { foreach (var one in settings) { var rec = new BufLen[] { (BufLen)(int)StoreRecordId.StoreIdConfig, new BufLen(one.Key.ToByteArray()), new BufLen(one.Value.ToByteArray()) }; if (str2ix.ContainsKey(one.Key)) { s.Write(rec, str2ix[one.Key]); } else { s.Write(rec); } } }); } Logging.Log($"NetDb.Save( {( onlyupdated ? "updated" : "all" )} ): " + $"{created} created, {updated} updated, {deleted} deleted."); Statistics.RemoveOldStatistics(); UpdateSelectionProbabilities(); sw.Stop(); Logging.Log($"NetDB: Save: {sw.Elapsed}"); }
/// <summary> /// Returns an enumerable collection of all quest definitions /// </summary> public static IEnumerable <KeyValuePair <string, QuestDef> > EnumerateDefs() { return(Defs.ToArray()); }
/// <exception cref="T:System.ArgumentNullException"> /// Thrown when a null reference is passed to a method that does not accept it as a /// valid argument. /// </exception> internal HttpRequestMessage AddAlbumImagesRequest( string url, IEnumerable <string> imageIds) { if (string.IsNullOrWhiteSpace(url)) { throw new ArgumentNullException(nameof(url)); } if (imageIds == null) { throw new ArgumentNullException(nameof(imageIds)); } Dictionary <string, string> source = new Dictionary <string, string>() { { "ids", string.Join(",", imageIds) } }; return(new HttpRequestMessage(HttpMethod.Put, url) { Content = (HttpContent) new FormUrlEncodedContent((IEnumerable <KeyValuePair <string, string> >)source.ToArray <KeyValuePair <string, string> >()) }); }
void test() { List <string> comList = new List <string>(); Dictionary <string, d> listTestFunction = new Dictionary <string, d>() { { "Read Com Use Thread Loop", readComUseThreadLoop }, { "Read Com Use Event DataReceive", readComUseEventDataReceive } }; comList.AddRange(SerialPort.GetPortNames()); if (comList.Count == 0) { Console.WriteLine("Can't find any com port\nPress any key to leave."); Console.ReadKey(); return; } Console.WriteLine("\nCom List:"); for (int i = 0; i < comList.Count; i++) { Console.WriteLine($"{i + 1}.{comList[i]}"); } Console.WriteLine("\nPlease select the com that you want to open."); if (!int.TryParse(Console.ReadLine(), out int pCom)) { return; } if (pCom <= 0 || pCom - 1 >= comList.Count) { return; } int p = 0; Console.WriteLine("\nTest Function List:"); foreach (KeyValuePair <string, d> f in listTestFunction) { Console.WriteLine($"{++p}.{f.Key}"); } Console.WriteLine("\nPlease select the Test Function that you want to use."); if (!int.TryParse(Console.ReadLine(), out int pTestFunc)) { return; } if (pTestFunc <= 0 || pTestFunc - 1 >= listTestFunction.Count) { return; } com = new SerialPort(comList[pCom - 1], 921600, Parity.None, 8) { ReadBufferSize = 4096 }; try { com.Open(); } catch (Exception e) { Console.WriteLine($"Open com fail:{e.ToString()}"); } listTestFunction.ToArray()[pTestFunc - 1].Value(); Console.WriteLine("Press any key to leave."); Console.ReadKey(); return; }
internal static void GrowPopulation(Entity colony) { // Get current population Dictionary <Entity, long> currentPopulation = colony.GetDataBlob <ColonyInfoDB>().Population; var instancesDB = colony.GetDataBlob <ComponentInstancesDB>(); List <KeyValuePair <Entity, PrIwObsList <Entity> > > infrastructure = instancesDB.SpecificInstances.GetInternalDictionary().Where(item => item.Key.HasDataBlob <PopulationSupportAtbDB>()).ToList(); long popSupportValue; // Pop Cap = Total Population Support Value / Colony Cost // Get total popSupport popSupportValue = 0; foreach (var installation in infrastructure) { //if(installations[kvp.Key] popSupportValue += installation.Key.GetDataBlob <PopulationSupportAtbDB>().PopulationCapacity; } long needsSupport = 0; foreach (KeyValuePair <Entity, long> kvp in currentPopulation) { // count the number of different population groups that need infrastructure support if (SpeciesProcessor.ColonyCost(colony.GetDataBlob <ColonyInfoDB>().PlanetEntity, kvp.Key.GetDataBlob <SpeciesDB>()) > 1.0) { needsSupport++; } } // find colony cost, divide the population support value by it foreach (KeyValuePair <Entity, long> kvp in currentPopulation.ToArray()) { double colonyCost = SpeciesProcessor.ColonyCost(colony.GetDataBlob <ColonyInfoDB>().PlanetEntity, kvp.Key.GetDataBlob <SpeciesDB>()); long maxPopulation; double growthRate; long newPop; if (colonyCost > 1.0) { maxPopulation = (long)((double)(popSupportValue / needsSupport) / colonyCost); if (currentPopulation[kvp.Key] > maxPopulation) // People will start dying { long excessPopulation = currentPopulation[kvp.Key] - maxPopulation; // @todo: figure out better formula growthRate = -50.0; newPop = (long)(kvp.Value * (1.0 + growthRate)); if (newPop < 0) { newPop = 0; } currentPopulation[kvp.Key] = newPop; } else { // Colony Growth Rate = 20 / (CurrentPop ^ (1 / 3)) // Capped at 10% before modifiers for planetary and sector governors, also affected by radiation growthRate = (20.0 / (Math.Pow(kvp.Value, (1.0 / 3.0)))); if (growthRate > 10.0) { growthRate = 10.0; } // @todo: get external factors in population growth (or death) newPop = (long)(kvp.Value * (1.0 + growthRate)); if (newPop > maxPopulation) { newPop = maxPopulation; } if (newPop < 0) { newPop = 0; } currentPopulation[kvp.Key] = newPop; } } else { // Colony Growth Rate = 20 / (CurrentPop ^ (1 / 3)) // Capped at 10% before modifiers for planetary and sector governors, also affected by radiation growthRate = (20.0 / (Math.Pow(kvp.Value, (1.0 / 3.0)))); if (growthRate > 10.0) { growthRate = 10.0; } // @todo: get external factors in population growth (or death) newPop = (long)(kvp.Value * (1.0 + growthRate)); if (newPop < 0) { newPop = 0; } currentPopulation[kvp.Key] = newPop; } } }
/// <summary> /// Execute the task. /// </summary> /// <param name="Job">Information about the current job</param> /// <param name="BuildProducts">Set of build products produced by this node.</param> /// <param name="TagNameToFileSet">Mapping from tag names to the set of files they include</param> public override void Execute(JobContext Job, HashSet <FileReference> BuildProducts, Dictionary <string, HashSet <FileReference> > TagNameToFileSet) { // Parse all the source patterns FilePattern SourcePattern = new FilePattern(CommandUtils.RootDirectory, Parameters.From); // Parse the target pattern FilePattern TargetPattern = new FilePattern(CommandUtils.RootDirectory, Parameters.To); // Apply the filter to the source files HashSet <FileReference> Files = null; if (!String.IsNullOrEmpty(Parameters.Files)) { SourcePattern = SourcePattern.AsDirectoryPattern(); Files = ResolveFilespec(SourcePattern.BaseDirectory, Parameters.Files, TagNameToFileSet); } // Build the file mapping Dictionary <FileReference, FileReference> TargetFileToSourceFile = FilePattern.CreateMapping(Files, ref SourcePattern, ref TargetPattern); // If we're not overwriting, remove any files where the destination file already exists. if (!Parameters.Overwrite) { TargetFileToSourceFile = TargetFileToSourceFile.Where(File => { if (FileReference.Exists(File.Key)) { CommandUtils.LogInformation("Not copying existing file {0}", File.Key); return(false); } return(true); }).ToDictionary(Pair => Pair.Key, Pair => Pair.Value); } // Check we got some files if (TargetFileToSourceFile.Count == 0) { CommandUtils.LogInformation("No files found matching '{0}'", SourcePattern); return; } // If the target is on a network share, retry creating the first directory until it succeeds DirectoryReference FirstTargetDirectory = TargetFileToSourceFile.First().Key.Directory; if (!DirectoryReference.Exists(FirstTargetDirectory)) { const int MaxNumRetries = 15; for (int NumRetries = 0;; NumRetries++) { try { DirectoryReference.CreateDirectory(FirstTargetDirectory); if (NumRetries == 1) { Log.TraceInformation("Created target directory {0} after 1 retry.", FirstTargetDirectory); } else if (NumRetries > 1) { Log.TraceInformation("Created target directory {0} after {1} retries.", FirstTargetDirectory, NumRetries); } break; } catch (Exception Ex) { if (NumRetries == 0) { Log.TraceInformation("Unable to create directory '{0}' on first attempt. Retrying {1} times...", FirstTargetDirectory, MaxNumRetries); } Log.TraceLog(" {0}", Ex); if (NumRetries >= 15) { throw new AutomationException(Ex, "Unable to create target directory '{0}' after {1} retries.", FirstTargetDirectory, NumRetries); } Thread.Sleep(2000); } } } // Copy them all KeyValuePair <FileReference, FileReference>[] FilePairs = TargetFileToSourceFile.ToArray(); CommandUtils.LogInformation("Copying {0} file{1} from {2} to {3}...", FilePairs.Length, (FilePairs.Length == 1)? "" : "s", SourcePattern.BaseDirectory, TargetPattern.BaseDirectory); foreach (KeyValuePair <FileReference, FileReference> FilePair in FilePairs) { CommandUtils.LogLog(" {0} -> {1}", FilePair.Value, FilePair.Key); } CommandUtils.ThreadedCopyFiles(FilePairs.Select(x => x.Value.FullName).ToList(), FilePairs.Select(x => x.Key.FullName).ToList(), bQuiet: true); // Update the list of build products BuildProducts.UnionWith(TargetFileToSourceFile.Keys); // Apply the optional output tag to them foreach (string TagName in FindTagNamesFromList(Parameters.Tag)) { FindOrAddTagSet(TagNameToFileSet, TagName).UnionWith(TargetFileToSourceFile.Keys); } }
private void RebuildItems() { foreach (var drityData in dirtyDataItems) { var path = drityData.Value; var userdata = drityData.Key; string[] strings = path.Split('/'); if (strings == null || strings.Length == 0) { return; } ITreeViewDirectory directory = this; for (int i = 0; i < strings.Length; i++) { string name = strings[i]; ITreeViewItem treeViewItem = directory.GetChild(name); if (treeViewItem == null) { if (i == strings.Length - 1) { TreeViewLeafItem treeViewLeafItem; var tryGetValue = this.dataItems.TryGetValue(userdata, out treeViewLeafItem); if (!tryGetValue) { treeViewLeafItem = new TreeViewLeafItem(); dataItems.Add(userdata, treeViewLeafItem); } //最后一个是数据节点,生成这个节点 treeViewLeafItem.userdata = userdata; treeViewLeafItem.OnSelected = this.OnSelected; treeViewItem = treeViewLeafItem; } else { //是路径节点,生成这个节点 TreeViewDirectoryItem treeViewDirectoryItem = new TreeViewDirectoryItem(); treeViewDirectoryItem.OnSelect = this.OnSelected; treeViewItem = treeViewDirectoryItem; } // treeViewItem.ParentDirectory = parent; // treeViewItem.Depth = i; treeViewItem.Name = name; // treeViewItem.GuiTreeView = this; directory.AddChild(treeViewItem); } if (treeViewItem is ITreeViewDirectory) { //进入路径的下一个目录 directory = (treeViewItem as ITreeViewDirectory); } } } foreach (var treeViewLeafItem in dataItems.ToArray()) { var userData = treeViewLeafItem.Key; var item = treeViewLeafItem.Value; //新数据中不存在了 if (!dirtyDataItems.ContainsKey(userData)) { item.ParentDirectory.RemoveChild(item); dataItems.Remove(item.userdata); } } dirtyDataItems.Clear(); }
public String generateJs(Dictionary <String, int> hashMap) { String html = ""; String template = "jcrud.js"; Textprocessor processor = new Textprocessor(); String readpath = this.sourcePath + "/" + template; string[] lines = System.IO.File.ReadAllLines(readpath); html += "<script>" + Environment.NewLine; for (int i = 0; i < lines.Length; i++) { if (lines[i].Trim() == "/*info_url*/") { html += "'info_" + this.name + "/id'"; } if (lines[i].Trim() == "//ParamsJsedit") { html += "$('input[name='id']').empty();" + Environment.NewLine; html += "$('input[name='id']').val(id);" + Environment.NewLine; foreach (var data in hashMap.ToArray()) { if (data.Value != 7) { html += "$('input[name='" + data.Key + "']').empty();" + Environment.NewLine; html += "$('input[name='" + data.Key + "']').val(res." + data.Key + ");" + Environment.NewLine; } else { html += "$('input[name='" + data.Key + "']').empty();" + Environment.NewLine; html += "$('input[name='" + data.Key + "']').append(res." + data.Key + ");" + Environment.NewLine; } } } if (lines[i].Trim() == "//ParamsJssave" || lines[i].Trim() == "//ParamsJscreate") { html += " var id = $('input[name='id']').val();" + Environment.NewLine; foreach (var data in hashMap.ToArray()) { html += " var " + data.Key + " = $('input[name='" + data.Key + "']').val();" + Environment.NewLine; } } if (lines[i].Trim() == "//Posdata") { foreach (var data in hashMap.ToArray()) { html += data.Key + ":" + data.Key + Environment.NewLine; } } if (lines[i].Trim() == "/*updateajax_url*/") { html += "'update_" + this.name + "/+id'"; } if (lines[i].Trim() == "/*createajax_url*/") { html += "'create_" + this.name + "/+id'"; } if (lines[i].Trim() == "/*deleteajax_url*/") { html += "'delete_" + this.name + "/+id'"; } else { html += lines[i]; } html += Environment.NewLine; } html += "</script>"; return(html); }
static int Main(string[] args) { string tempFolder = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); string outputFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); Directory.CreateDirectory(tempFolder); Directory.SetCurrentDirectory(tempFolder); try { // Find paths string HeaderFile = FindFile("DbgEng.h", HeaderFiles); string MidlPath = FindExe("midl.exe", MidlPaths); string UmPath = FindFolder("um", UmPaths); string SharedPath = FindFolder("um", SharedPaths); string VCBinPath = FindFolder("VC\\bin", VCBinPaths); string TlbImpPath = FindExe("TlbImp.exe", TlbImpPaths); string DiaIncludePath = FindFolder("include", VCDiaSdkIncludePaths); string DiaIdlPath = FindFolder("idl", VCDiaSdkIdlPaths); // Generate IDL file Regex defineDeclarationRegex = new Regex(@"#define\s+([^(]+)\s+((0x|)[0-9a-fA-F]+)$"); Regex typedefStructOneLineRegex = new Regex(@"typedef struct.*;"); Regex typedefStructMultiLineRegex = new Regex(@"typedef struct[^;]+"); Regex typedefInterfaceOneLineRegex = new Regex("typedef interface DECLSPEC_UUID[(]\"([^\"]+)\""); Regex declareInterfaceRegex = new Regex(@"DECLARE_INTERFACE_[(](\w+)"); Dictionary <string, string> uuids = new Dictionary <string, string>(); Dictionary <string, string> references = new Dictionary <string, string>(); StringBuilder outputString = new StringBuilder(); Dictionary <string, string> constants = new Dictionary <string, string>(); using (StreamWriter output = new StreamWriter("output.idl")) using (StreamReader reader = new StreamReader(HeaderFile)) { while (!reader.EndOfStream) { string line = reader.ReadLine(); Match match; // Check if it is enum definition match = defineDeclarationRegex.Match(line); if (match != null && match.Success && match.Groups[1].ToString().ToUpper() != "INTERFACE" && match.Groups[2].Length <= 10) { constants.Add(match.Groups[1].Value, match.Groups[2].Value); continue; } // Check if it is typedef of one-line struct match = typedefStructOneLineRegex.Match(line); if (match != null && match.Success) { outputString.AppendLine(string.Format(" {0}", line)); continue; } // Check if it is typedef of multi-line struct match = typedefStructMultiLineRegex.Match(line); if (match != null && match.Success) { int brackets = 0; outputString.AppendLine(); while (!reader.EndOfStream) { string newLine = StripWin32Defs(RemoveSpaces(line)); brackets -= line.Count(c => c == '}'); outputString.AppendLine(string.Format(" {0}{1}", new string(' ', brackets * 4), newLine)); brackets += line.Count(c => c == '{'); if (brackets == 0 && newLine.EndsWith(";")) { break; } line = reader.ReadLine(); } outputString.AppendLine(); continue; } // Check if it is typedef of interface UUID match = typedefInterfaceOneLineRegex.Match(line); if (match != null && match.Success) { string uuid = match.Groups[1].Value; string definition = ""; while (!reader.EndOfStream) { line = reader.ReadLine(); definition += line; if (definition.Contains(';')) { break; } } // Check if definition contains interface pointer type match = Regex.Match(definition, @"(\w+)\s*\*\s+(\w+);"); if (match == null || !match.Success) { continue; } // Save definition string interfaceName = match.Groups[1].Value; string interfaceReference = match.Groups[2].Value; uuids.Add(interfaceName, uuid); references.Add(interfaceReference, interfaceName); continue; } // Check if it is interface declaration match = declareInterfaceRegex.Match(line); if (match != null && match.Success) { string interfaceName = match.Groups[1].Value; string uuid = uuids[interfaceName]; StringBuilder definitionBuilder = new StringBuilder(); List <Tuple <string, string, string> > interfaceMethods = new List <Tuple <string, string, string> >(); while (!reader.EndOfStream) { line = reader.ReadLine(); definitionBuilder.AppendLine(line); if (line.StartsWith("};")) { break; } } string definition = definitionBuilder.ToString(); // Remove comments definition = Regex.Replace(definition, "/[*].*[*]/", ""); definition = Regex.Replace(definition, "//[^\n]*", ""); // Extract methods string[] methods = definition.Split(";".ToCharArray()); foreach (string method in methods) { match = Regex.Match(method, @"[(]([^)]+)[)].*[(](([^)]*[)]?)*)[)] PURE"); if (match != null && match.Success) { string[] methodReturnValueAndName = match.Groups[1].Value.Split(",".ToCharArray()); string methodName = methodReturnValueAndName.Length > 1 ? methodReturnValueAndName[1].Trim() : methodReturnValueAndName[0].Trim(); string returnValue = methodReturnValueAndName.Length > 1 ? methodReturnValueAndName[0].Trim() : "HRESULT"; string parametersString = match.Groups[2].Value; if (methodName != "QueryInterface" && methodName != "AddRef" && methodName != "Release") { // Clean parameters StringBuilder parameters = new StringBuilder(); parametersString = RemoveSpaces(parametersString.Replace("THIS_", "").Replace("THIS", "")); if (parametersString.Length > 0) { // Check if there are SAL notation parenthesis that have comma inside and replace with semicolon var matches = Regex.Matches(parametersString, "[(][^)]*[)]"); foreach (Match m in matches) { parametersString = parametersString.Replace(m.Value, m.Value.Replace(",", ":")); } // Fix parameters bool optionalStarted = false; string[] parametersArray = parametersString.Split(",".ToCharArray()); int outParameters = 0; bool forbidOptional = false; if (methodName == "Breakpoint" && (interfaceName == "IDebugEventCallbacks" || interfaceName == "IDebugEventCallbacksWide")) { returnValue = "int"; } if (parametersString.Contains("...")) { returnValue = "[vararg] " + returnValue; forbidOptional = true; } for (int i = 0; i < parametersArray.Length; i++) { string parameter = parametersArray[i]; if (parameters.Length != 0) { parameters.Append(", "); } bool outAttribute = Regex.IsMatch(parameter, @"OUT\s|_Out_[a-zA-Z_]*([(][^)]*[)])?\s|__out\w*\s|__inout|_Inout\w*\s"); bool optionalAttribute = (Regex.IsMatch(parameter, @"_(In|Out)[a-zA-Z_]*opt[a-zA-Z_]*([(][^)]*[)])?\s|OPTIONAL") || optionalStarted) && !forbidOptional; Match sizeAttribute = Regex.Match(parameter, @"_(In|Out)_(reads_|writes_)(bytes_|)(opt_|)[(]([^)]*)[)]"); Match maxAttribute = Regex.Match(parameter, @"_Out_writes_to_(opt_|)[(]([^):]*):([^)]*)[)]"); bool convertToArray = false; if (Regex.IsMatch(parameter, @"[(][^)]*[)]") && (sizeAttribute == null || sizeAttribute.Success == false) && (maxAttribute == null || maxAttribute.Success == false)) { throw new Exception("Not all SAL attributes are parsed"); } if (outAttribute) { outParameters++; } optionalStarted = optionalAttribute; parameters.Append('['); parameters.Append(outAttribute ? "out" : "in"); if (optionalAttribute) { parameters.Append(",optional"); } if (sizeAttribute != null && sizeAttribute.Success) { parameters.Append(",size_is("); parameters.Append(sizeAttribute.Groups[5].Value); parameters.Append(")"); convertToArray = true; } else if (maxAttribute != null && maxAttribute.Success) { parameters.Append(",size_is("); parameters.Append(maxAttribute.Groups[2].Value); parameters.Append(")"); convertToArray = true; } if (outParameters == 1 && outAttribute && i == parametersArray.Length - 1 && !optionalAttribute) { parameters.Append(",retval"); } parameters.Append("] "); foreach (var reference in references) { parameter = parameter.Replace(reference.Key + " ", reference.Value + "* "); parameter = parameter.Replace(reference.Key + "*", reference.Value + "**"); } parameter = RemoveSpaces(StripWin32Defs(parameter)); if (convertToArray) { int pointerIndex = parameter.LastIndexOf('*'); if (pointerIndex >= 0) { parameter = RemoveSpaces(parameter.Remove(pointerIndex, 1) + "[]"); } else if (!parameter.StartsWith("LPStr") && !parameter.StartsWith("LPWStr")) { parameter += "[]"; } } parameters.Append(parameter); } } interfaceMethods.Add(Tuple.Create(returnValue, methodName, parameters.ToString())); } } else if (method.Trim() != "" && method.Trim() != "}") { throw new Exception("Wrong method parsing"); } } // Print interface definition outputString.AppendLine(string.Format(@" /////////////////////////////////////////////////////////// [ object, uuid({0}), helpstring(""{1}"") ] interface {1} : IUnknown {{", uuid, interfaceName)); foreach (var method in interfaceMethods) { outputString.AppendLine(string.Format(" {0} {1}({2});", method.Item1, method.Item2, method.Item3)); } outputString.AppendLine(" };"); outputString.AppendLine(); continue; } // TODO: Unknown line } // Write constants var remainingConstants = constants.ToArray(); var usedConstants = new HashSet <string>(); WriteConstants(outputString, usedConstants, ref remainingConstants, "DEBUG_REQUEST_", "DebugRequest", (s) => s.StartsWith("DEBUG_LIVE_USER_NON_INVASIVE")); WriteConstants(outputString, usedConstants, ref remainingConstants, "DEBUG_SCOPE_GROUP_"); WriteConstants(outputString, usedConstants, ref remainingConstants, "DEBUG_OUTPUT_", "DebugOutput", null, (s) => !s.StartsWith("DEBUG_OUTPUT_SYMBOLS_") && !s.StartsWith("DEBUG_OUTPUT_IDENTITY_DEFAULT")); WriteConstants(outputString, usedConstants, ref remainingConstants, "DEBUG_MODNAME_"); WriteConstants(outputString, usedConstants, ref remainingConstants, "DEBUG_OUTCTL_"); WriteConstants(outputString, usedConstants, ref remainingConstants, "DEBUG_EXECUTE_"); WriteConstants(outputString, usedConstants, ref remainingConstants, "", "Defines"); // Write file header FileVersionInfo fileVersion = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location); output.WriteLine(@"import ""oaidl.idl""; import ""ocidl.idl""; #if (__midl >= 501) midl_pragma warning( disable: 2362 ) #endif [ uuid({0}), helpstring(""DbgEng Type Library""), version({1}.{2}), ] library DbgEng {{ importlib(""stdole32.tlb""); importlib(""stdole2.tlb""); /////////////////////////////////////////////////////////// // interface forward declaration", Guid.NewGuid(), fileVersion.ProductMajorPart, fileVersion.ProductMinorPart); foreach (var uuid in uuids) { output.WriteLine(" interface {0};", uuid.Key); } output.WriteLine(@" /////////////////////////////////////////////////////////// // missing structs enum {EXCEPTION_MAXIMUM_PARAMETERS = 15}; // maximum number of exception parameters typedef struct _EXCEPTION_RECORD64 { DWORD ExceptionCode; DWORD ExceptionFlags; LONGLONG ExceptionRecord; LONGLONG ExceptionAddress; DWORD NumberParameters; DWORD __unusedAlignment; LONGLONG ExceptionInformation[EXCEPTION_MAXIMUM_PARAMETERS]; } EXCEPTION_RECORD64, *PEXCEPTION_RECORD64; typedef struct _IMAGE_FILE_HEADER { WORD Machine; WORD NumberOfSections; DWORD TimeDateStamp; DWORD PointerToSymbolTable; DWORD NumberOfSymbols; WORD SizeOfOptionalHeader; WORD Characteristics; } IMAGE_FILE_HEADER, *PIMAGE_FILE_HEADER; typedef struct _IMAGE_DATA_DIRECTORY { DWORD VirtualAddress; DWORD Size; } IMAGE_DATA_DIRECTORY, *PIMAGE_DATA_DIRECTORY; enum { IMAGE_NUMBEROF_DIRECTORY_ENTRIES = 16}; typedef struct _IMAGE_OPTIONAL_HEADER64 { WORD Magic; BYTE MajorLinkerVersion; BYTE MinorLinkerVersion; DWORD SizeOfCode; DWORD SizeOfInitializedData; DWORD SizeOfUninitializedData; DWORD AddressOfEntryPoint; DWORD BaseOfCode; ULONGLONG ImageBase; DWORD SectionAlignment; DWORD FileAlignment; WORD MajorOperatingSystemVersion; WORD MinorOperatingSystemVersion; WORD MajorImageVersion; WORD MinorImageVersion; WORD MajorSubsystemVersion; WORD MinorSubsystemVersion; DWORD Win32VersionValue; DWORD SizeOfImage; DWORD SizeOfHeaders; DWORD CheckSum; WORD Subsystem; WORD DllCharacteristics; ULONGLONG SizeOfStackReserve; ULONGLONG SizeOfStackCommit; ULONGLONG SizeOfHeapReserve; ULONGLONG SizeOfHeapCommit; DWORD LoaderFlags; DWORD NumberOfRvaAndSizes; IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES]; } IMAGE_OPTIONAL_HEADER64, *PIMAGE_OPTIONAL_HEADER64; typedef struct _IMAGE_NT_HEADERS64 { DWORD Signature; IMAGE_FILE_HEADER FileHeader; IMAGE_OPTIONAL_HEADER64 OptionalHeader; } IMAGE_NT_HEADERS64, *PIMAGE_NT_HEADERS64; struct _WINDBG_EXTENSION_APIS32 { DWORD NotSupported; }; struct _WINDBG_EXTENSION_APIS64 { DWORD NotSupported; }; struct _MEMORY_BASIC_INFORMATION64 { ULONGLONG BaseAddress; ULONGLONG AllocationBase; DWORD AllocationProtect; DWORD __alignment1; ULONGLONG RegionSize; DWORD State; DWORD Protect; DWORD Type; DWORD __alignment2; }; "); output.WriteLine(); output.WriteLine(" ///////////////////////////////////////////////////////////"); output.WriteLine(outputString); output.WriteLine("};"); } ProcessStartInfo startInfo = new ProcessStartInfo(MidlPath); string midlPlatform = IntPtr.Size == 4 ? "/win32 /robust" : "/x64"; startInfo.Arguments = string.Format(@"/I""{0}"" /I""{1}"" output.idl /tlb output.tlb {2}", UmPath, SharedPath, midlPlatform); startInfo.UseShellExecute = false; startInfo.EnvironmentVariables["Path"] = VCBinPath + ";" + startInfo.EnvironmentVariables["Path"]; using (Process process = Process.Start(startInfo)) { process.WaitForExit(); } #if X64 string tlbimpPlatform = "x64"; #elif X86 string tlbimpPlatform = "x86"; #else string tlbimpPlatform = "Agnostic"; #endif startInfo = new ProcessStartInfo(TlbImpPath); startInfo.Arguments = @"output.tlb /machine:" + tlbimpPlatform; startInfo.UseShellExecute = false; startInfo.EnvironmentVariables["Path"] = VCBinPath + ";" + startInfo.EnvironmentVariables["Path"]; using (Process process = Process.Start(startInfo)) { process.WaitForExit(); } // Create Dia2Lib.tlb startInfo = new ProcessStartInfo(MidlPath); startInfo.Arguments = $"/I \"{DiaIncludePath}\" /I \"{DiaIdlPath}\" /I \"{UmPath}\" /I \"{SharedPath}\" dia2.idl /tlb dia2lib.tlb"; startInfo.UseShellExecute = false; startInfo.EnvironmentVariables["Path"] = VCBinPath + ";" + startInfo.EnvironmentVariables["Path"]; using (Process process = Process.Start(startInfo)) { process.WaitForExit(); } // Create Dia2Lib.dll startInfo = new ProcessStartInfo(TlbImpPath); startInfo.Arguments = "dia2lib.tlb"; startInfo.UseShellExecute = false; startInfo.EnvironmentVariables["Path"] = VCBinPath + ";" + startInfo.EnvironmentVariables["Path"]; using (Process process = Process.Start(startInfo)) { process.WaitForExit(); } // Copy files to output folder string[] filesToCopy = new[] { "Dia2Lib.dll", "DbgEng.dll" }; foreach (string fileToCopy in filesToCopy) { string inputFile = Path.Combine(tempFolder, fileToCopy); string outputFile = Path.Combine(outputFolder, fileToCopy); if (File.Exists(outputFile)) { File.Delete(outputFile); } File.Move(inputFile, outputFile); } } finally { Directory.SetCurrentDirectory(outputFolder); Directory.Delete(tempFolder, true); } return(0); }
//------------------------------------------------------------------------------------------------------------------------ #endregion #region Functions //------------------------------------------------------------------------------------------------------------------------ protected void RebuildCachedCollections() { lock (locker) { if (cached_revision != revision) { //update revision cached_revision = revision; //rebuild cached sets cached_Keys = InternalObject == null || InternalObject.Count == 0 ? empty_Keys : InternalObject.Keys.ToArray(); cached_Values = InternalObject == null || InternalObject.Count == 0 ? empty_Values : InternalObject.Values.ToArray(); cached_KeyValue = InternalObject == null || InternalObject.Count == 0 ? empty_KeyValue : InternalObject.ToArray(); } } }
public static KeyValuePair <string, Bitmap>[] GetCapturedShadows() { return(_captured.ToArray()); }
// Private method for retrieving an authentication token private async Task <bool> Authenticate() { try { // Setup a base list of parameters var baseParameters = new Dictionary <string, string>(); // Add the parameters always required by the API AddRequiredRequestParams(baseParameters, "auth.gettoken", null, false); // Retrieve the Authentication token without using authentication _authToken = await UnauthenticatedGet <AuthenticationToken>("auth.gettoken", baseParameters.ToArray()).ConfigureAwait(false); } catch (Exception ex) { Logger.FileLogger.Write(_logfilePathAndName, "API Client Request", $"Failed to authenticate due to an error: {ex}"); Console.WriteLine(ex); } return(!string.IsNullOrEmpty(_authToken?.Token)); }
public void CopyTo(KeyValuePair <TK, TD>[] array, int arrayIndex) { Array.Copy(_underlying.ToArray(), 0, array, arrayIndex, Math.Min(array.Length - arrayIndex, _underlying.Count)); }
public TextileTable( string[] header, string[] styles, IList <string[]> details) { Header = header.Select(txt => { var cell = new TextileTableCell(txt); // Ignore Header Row-span cell.RowSpan = 1; return(cell); }).ToList <ITableCell>(); Details = details.Select(row => row.Select(txt => new TextileTableCell(txt)).ToList <ITableCell>() ).ToList(); // column-idx vs text-alignment Dictionary <int, TextAlignment> styleMt = styles .Select((txt, idx) => { var firstChar = txt[0]; var lastChar = txt[txt.Length - 1]; return ((firstChar == ':' && lastChar == ':') ? Tuple.Create(idx, (TextAlignment?)TextAlignment.Center) : (lastChar == ':') ? Tuple.Create(idx, (TextAlignment?)TextAlignment.Right) : (firstChar == ':') ? Tuple.Create(idx, (TextAlignment?)TextAlignment.Left) : Tuple.Create(idx, (TextAlignment?)null)); }) .Where(tpl => tpl.Item2.HasValue) .ToDictionary(tpl => tpl.Item1, tpl => tpl.Item2.Value); var styleColumnCount = styleMt.Count; // apply cell style to header var headerColumnCount = 0; { var colOffset = 0; foreach (TextileTableCell cell in Header) { cell.ColumnIndex = colOffset; // apply text align if (styleMt.TryGetValue(colOffset, out var style)) { cell.Horizontal = style; } colOffset += cell.ColSpan; } headerColumnCount = colOffset; } // apply cell style to header var colCntAtDetail = new List <int>(); var maxColCntInDetails = 1; { var multiRowsAtColIdx = new Dictionary <int, MdSpan>(); for (var rowIdx = 0; rowIdx < Details.Count; ++rowIdx) { List <ITableCell> row = Details[rowIdx]; var hasAnyCell = false; var colOffset = 0; var rowspansColOffset = multiRowsAtColIdx .Select(ent => ent.Value.ColSpan) .Sum(); /* * In this row, is space exists to insert cell? * * eg. has space * __________________________________ * | 2x1 cell | 1x1 cell | 1x1 cell | * -> | |‾‾‾‾‾‾‾‾‾‾|‾‾‾‾‾‾‾‾‾‾| * ‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ * * eg. has no space: multi-rows occupy all space in this row. * __________________________________ * | 2x1 cell | 2x2 cell | * -> | | | * ‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ * */ if (rowspansColOffset < maxColCntInDetails) { int colIdx; for (colIdx = 0; colIdx < row.Count;) { int colSpan; if (multiRowsAtColIdx.TryGetValue(colOffset, out var span)) { colSpan = span.ColSpan; } else { hasAnyCell = true; var cell = (TextileTableCell)row[colIdx]; cell.ColumnIndex = colOffset; // apply text align if (!cell.Horizontal.HasValue && styleMt.TryGetValue(colOffset, out var style)) { cell.Horizontal = style; } colSpan = cell.ColSpan; if (cell.RowSpan > 1) { multiRowsAtColIdx[colOffset] = new MdSpan(cell.RowSpan, cell.ColSpan); } ++colIdx; } colOffset += colSpan; } foreach (var left in multiRowsAtColIdx.Where(tpl => tpl.Key >= colOffset) .OrderBy(tpl => tpl.Key)) { while (colOffset < left.Key) { var cell = new TextileTableCell(null); cell.ColumnIndex = colOffset++; row.Add(cell); } colOffset += left.Value.ColSpan; } } colOffset += multiRowsAtColIdx .Where(ent => ent.Key >= colOffset) .Select(ent => ent.Value.ColSpan) .Sum(); foreach (var spanEntry in multiRowsAtColIdx.ToArray()) { if (--spanEntry.Value.Life == 0) { multiRowsAtColIdx.Remove(spanEntry.Key); } } colCntAtDetail.Add(colOffset); maxColCntInDetails = Math.Max(maxColCntInDetails, colOffset); if (!hasAnyCell) { Details.Insert(rowIdx, new List <ITableCell>()); } } // if any multirow is left, insert an empty row. while (multiRowsAtColIdx.Count > 0) { var row = new List <ITableCell>(); Details.Add(row); var colOffset = 0; foreach (var spanEntry in multiRowsAtColIdx.OrderBy(tpl => tpl.Key)) { while (colOffset < spanEntry.Key) { var cell = new TextileTableCell(null); cell.ColumnIndex = colOffset++; row.Add(cell); } colOffset += spanEntry.Value.ColSpan; if (--spanEntry.Value.Life == 0) { multiRowsAtColIdx.Remove(spanEntry.Key); } } colCntAtDetail.Add(colOffset); } } ColCount = Math.Max(Math.Max(headerColumnCount, styleColumnCount), maxColCntInDetails); RowCount = Details.Count; // insert cell for the shortfall for (var retry = Header.Sum(cell => cell.ColSpan); retry < ColCount; ++retry) { var cell = new TextileTableCell(null); cell.ColumnIndex = retry; Header.Add(cell); } for (var rowIdx = 0; rowIdx < Details.Count; ++rowIdx) { for (var retry = colCntAtDetail[rowIdx]; retry < ColCount; ++retry) { var cell = new TextileTableCell(null); cell.ColumnIndex = retry; Details[rowIdx].Add(cell); } } }
// Public method for getting a Session Token from the API public async Task <SessionToken> GetSessionToken() { // Create an empty parameter base var baseParameters = new Dictionary <string, string>(); // Add the current authentication token baseParameters.Add("token", _authToken.Token); // Add any required parameters AddRequiredRequestParams(baseParameters, "auth.getSession", null, true); try { // Post the request using unauthenticated methods and get the response var userSession = await UnauthenticatedGet <Session>("auth.getSession", baseParameters.ToArray()).ConfigureAwait(false); // Persist the current session token _sessionToken = userSession?.SessionToken; } catch (Exception ex) { _sessionToken = null; Console.WriteLine(ex); Logger.FileLogger.Write(_logfilePathAndName, "API Client Request", $"Failed to retrieve a session token due to an error: {ex}"); } return(_sessionToken); }
public static void MapDistListMembers2To1( IEnumerable <DistributionListMember> sourceMembers, IDistListItemWrapper target, IEntitySynchronizationLogger logger, DistributionListSychronizationContext context) { var outlookMembersByAddress = new Dictionary <string, GenericComObjectWrapper <Recipient> >(StringComparer.InvariantCultureIgnoreCase); try { for (int i = 1; i <= target.Inner.MemberCount; i++) { var recipientWrapper = GenericComObjectWrapper.Create(target.Inner.GetMember(i)); if (!string.IsNullOrEmpty(recipientWrapper.Inner?.Address) && !outlookMembersByAddress.ContainsKey(recipientWrapper.Inner.Address)) { outlookMembersByAddress.Add(recipientWrapper.Inner.Address, recipientWrapper); } else { recipientWrapper.Dispose(); } } foreach (var sourceMember in sourceMembers) { GenericComObjectWrapper <Recipient> existingRecipient; if (!string.IsNullOrEmpty(sourceMember.EmailAddress) && outlookMembersByAddress.TryGetValue(sourceMember.EmailAddress, out existingRecipient)) { outlookMembersByAddress.Remove(sourceMember.EmailAddress); existingRecipient.Dispose(); } else { var recipientString = !string.IsNullOrEmpty(sourceMember.DisplayName) ? sourceMember.DisplayName : sourceMember.EmailAddress; if (!string.IsNullOrEmpty(recipientString)) { using (var recipientWrapper = GenericComObjectWrapper.Create(context.OutlookSession.CreateRecipient(recipientString))) { if (recipientWrapper.Inner.Resolve()) { target.Inner.AddMember(recipientWrapper.Inner); } else { // Add a member which is not in the Addressbook var builder = new StringBuilder(); if (!string.IsNullOrEmpty(sourceMember.DisplayName)) { builder.Append(sourceMember.DisplayName); builder.Append(" <"); builder.Append(sourceMember.EmailAddress); builder.Append(">"); } else { builder.Append(sourceMember.EmailAddress); } using (var tempRecipientMember = GenericComObjectWrapper.Create(context.OutlookSession.CreateRecipient(builder.ToString()))) { tempRecipientMember.Inner.Resolve(); target.Inner.AddMember(tempRecipientMember.Inner); } } } } } } foreach (var existingRecipient in outlookMembersByAddress.ToArray()) { target.Inner.RemoveMember(existingRecipient.Value.Inner); outlookMembersByAddress.Remove(existingRecipient.Key); } } catch (COMException ex) { s_logger.Warn("Can't access member of Distribution List!", ex); logger.LogWarning("Can't access member of Distribution List!", ex); } finally { foreach (var existingRecipient in outlookMembersByAddress.Values) { existingRecipient.Dispose(); } } }