public ProfileResult Convert() { var resultIndex = new ResultIndex(repository, connector, index.Item2); var result = resultIndex.Create(); if (index.Item1 == 1 || index.Item1 == 8) { var connectorProfile = new ConnectorProfile(); ProfileResult requirementProfileResult = new ProfileResult(); if (index.Item1 == 1) { requirementProfileResult = result.ProfileResults.FirstOrDefault(p => p.Name == "I8"); } else { requirementProfileResult = result; } var i8 = repository.FindById("I8"); foreach (var coeff in i8.Coefficients.Select((value, i) => new { value, i })) { int count = 0; var requirementProfile = new List <Profile>(); GetRequiremetProfile(profileListView, coeff.i + 1, ref count, ref requirementProfile); var newRepository = new ProfileRepository(requirementProfile); var profileResult = new ResultIndex(newRepository, connectorProfile, "I9").Create(); profileResult.Coeff = coeff.value.Value; requirementProfileResult.ProfileResults.Add(profileResult); } } return(result); }
private ProfileResult Create(string index) { ProfileResult result = new ProfileResult(); result.Name = index; result.ProfileResults = new List <ProfileResult>(); if (index == "I8") { result.Coeff = repository.GetCoefficientValue("I1", "K2"); } else if (!connector.ContainsKey(index)) { var profile = repository.FindById(index); foreach (var coeff in profile.Coefficients) { var resultMetric = new ResultMetric(repository, new SearchMetric(coeff.Name, index, coeff.Metric.Name)); var profileResult = resultMetric.Create(); result.ProfileResults.Add(profileResult); } } else { foreach (var test in connector[index]) { ProfileResult profile = new ProfileResult(); profile = Create(test.Index); profile.Coeff = repository.GetCoefficientValue(index, test.Coefficient); result.ProfileResults.Add(profile); } } return(result); }
public void CanCreateFromProfileTest() { var profile = Model.Create <Profile>(); var sut = new ProfileResult(profile); sut.Should().BeEquivalentTo(profile, opt => opt.ExcludingMissingMembers()); }
public ProfileResult Profile() { ProfileResult result = new ProfileResult { Name = nameof(Messenger) }; return(result); }
public ProfileResult Profile() { ProfileResult result = new ProfileResult { Name = nameof(SettingsService) }; return(result); }
/// <summary> /// Update user profile /// </summary> /// <param name="user"></param> /// <returns>dynamic data maybe dangerous but i think some time dangerous is good LOL!!! - cause i'm lazy</returns> private UpdateProfileResult UpdateProfile(ProfileResult profile) { Debug.WriteLine("Update profile"); string chainingEnable = "", data = ""; try { chainingEnable = profile.form_data.chaining_enabled ? "on" : "off"; data = $"first_name={WebUtility.UrlEncode(profile.form_data.first_name)}&email={profile.form_data.email}&username={WebUtility.UrlEncode(profile.form_data.username)}&phone_number={WebUtility.UrlEncode(profile.form_data.phone_number)}&gender={profile.form_data.gender}&biography={WebUtility.UrlEncode(profile.form_data.biography)}&external_url={WebUtility.UrlEncode(profile.form_data.external_url)}&chaining_enabled={chainingEnable}"; } catch (Exception ex) { Debug.WriteLine(ex.Message); throw; } try { var content = Encoding.ASCII.GetBytes(data); var request = HttpRequestBuilder.Post("https://www.instagram.com/accounts/edit/", mCoockieC); request.Referer = "https://www.instagram.com/accounts/edit/"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = content.Length; request.KeepAlive = true; request.Headers["Origin"] = "https://www.instagram.com"; // maybe exception if mCookieC not contain csrftoken request.Headers["X-CSRFToken"] = mCoockieC.GetCookies(new Uri("https://www.instagram.com"))["csrftoken"].Value; request.Headers["X-Instagram-AJAX"] = "1"; request.Headers["X-Requested-With"] = "XMLHttpRequest"; using (var requestStream = request.GetRequestStream()) { requestStream.Write(content, 0, content.Length); using (var response = request.GetResponse() as HttpWebResponse) { mCoockieC.Add(response.Cookies); using (var responseStream = response.GetResponseStream()) using (var streamReader = new StreamReader(responseStream)) { // If we get result, it always return status ok. Otherwise, exception will occur. var responseData = streamReader.ReadToEnd(); return(JsonConvert.DeserializeObject <UpdateProfileResult>(responseData)); } } } } catch (Exception ex) { // When you change your username with existed username, you will receive 404 error // and obviously exception will occur. In this case, just return false Debug.WriteLine(ex.Message); throw ex; } }
protected async Task SentNetworkProfile(Network network) { string jsonData = ""; Device device = MposFramework.Instance.DeviceController.Device; try { if (device != null) { jsonData = new ProfileResult(device, network).ToJson(); } else { jsonData = network.ToJson(); } streamSocket = new StreamSocket(); await streamSocket.ConnectAsync(hostName, server.SaveProfilePort.ToString()); using (DataWriter writer = new DataWriter(streamSocket.OutputStream)) { writer.WriteString(jsonData); await writer.StoreAsync(); await writer.FlushAsync(); //wait ok comeback... using (DataReader reader = new DataReader(streamSocket.InputStream)) { reader.InputStreamOptions = InputStreamOptions.Partial; await reader.LoadAsync(256); } } System.Diagnostics.Debug.WriteLine("[ProfileNetworkTask]: Sent profile to server with success"); } catch (AggregateException e) { e.Handle((ex) => { if (ex is IOException) { System.Diagnostics.Debug.WriteLine("[ProfileNetworkTask]: Error on transmition to remote data -> " + ex.ToString()); return(true); } return(false); }); } finally { Close(ref streamSocket); } }
public override ProfileResult Create() { ProfileResult result = new ProfileResult(); result.Name = searchMetric.Metric; result.Coeff = repository.GetCoefficientValue(searchMetric.Index, searchMetric.Coefficient); result.Value = repository.GetMetricValue(searchMetric.Index, searchMetric.Metric); result.ProfileResults = new List <ProfileResult>(); return(result); }
public void CanCreateDefaultInstanceTest() { var sut = new ProfileResult(); sut.Status.Should().Be(default(ProfileStatus)); sut.Id.Should().BeEmpty(); sut.BirthYear.Should().NotHaveValue(); sut.FirstName.Should().BeNull(); sut.Gender.Should().BeNull(); sut.LastName.Should().BeNull(); sut.TimeZone.Should().BeNull(); sut.YearStartedInTech.Should().NotHaveValue(); }
public ProfileResult Profile() { ProfileResult result = new ProfileResult { Name = nameof(BindingApplicator) }; result.Metrics.Add(Profile1()); result.Metrics.Add(Profile2()); result.Metrics.Add(Profile3()); return(result); }
/// <summary> /// Change UserBiography /// </summary> /// <param name="bioGraphy"></param> /// <returns></returns> public UpdateProfileResult SetBiography(string newBiography) { try { ProfileResult profile = GetProfile(); profile.form_data.biography = newBiography; return(UpdateProfile(profile)); } catch (Exception ex) { Debug.WriteLine("Change biography error " + ex.Message); throw ex; } }
private static ProfileResult ProfileTime <T>(int numberOfIterations, int numberOfRepeats, int numElements, bool toCheckIsInRange) { var numberGenerator = new Random(); T[] arrayData = GenerateArray <T>(numElements); // Todo - maybe pass in array of data so it can be of different types HashSet <T> hashSetData = new HashSet <T>(arrayData); var stopwatchArray = new Stopwatch(); var stopwatchHashSet = new Stopwatch(); var results = new ProfileResult[numberOfRepeats]; for (int j = 0; j < numberOfRepeats; j++) { var toCheck = GenerateValue <T>(numberGenerator, numElements, toCheckIsInRange); stopwatchArray.Start(); for (int i = 0; i < numberOfIterations; i++) { var contains = arrayData.Contains(toCheck); } stopwatchArray.Stop(); var arrayTime = stopwatchArray.ElapsedMilliseconds; stopwatchArray.Reset(); stopwatchHashSet.Start(); for (int i = 0; i < numberOfIterations; i++) { var contains = hashSetData.Contains(toCheck); } stopwatchHashSet.Stop(); var hashSetTime = stopwatchHashSet.ElapsedMilliseconds; stopwatchHashSet.Reset(); results[j] = new ProfileResult(arrayTime, hashSetTime); } // We skip ~ 10% of repeats to reduce the impact of CPU spikes. var arrayAverage = results.OrderByDescending(r => r.ArrayTime).Skip(numberOfRepeats / 10).Average(r => r.ArrayTime); var hashSetAverage = results.OrderByDescending(r => r.HashSetTime).Skip(numberOfRepeats / 10).Average(r => r.HashSetTime); return(new ProfileResult(arrayAverage, hashSetAverage)); }
public static void BeginScope(string name) { if (currentSession == null) { Log.Core.Error($"[profiler] no session to profile scope '{name}'"); return; } ProfileResult result = new ProfileResult(name, Thread.CurrentThread.ManagedThreadId, (float)(DateTime.Now - appStarted).Ticks / TimeSpan.TicksPerMillisecond); mutex.WaitOne(); profileResultsStack.Push(result); mutex.ReleaseMutex(); }
public static void Function(string name) { if (currentSession == null) { Log.Core.Error($"[profiler] no session to profile function '{name}'"); return; } mutex.WaitOne(); ProfileResult result = new ProfileResult(name, Thread.CurrentThread.ManagedThreadId, (float)(DateTime.Now - appStarted).Ticks / TimeSpan.TicksPerMillisecond); WriteProfile(ref result); mutex.ReleaseMutex(); }
/// <inheritdoc /> public ProfileResult GetProfile(string name, string keyAddress) { var result = new ProfileResult(); var t2Node = this.xServerPeerList.GetPeers().Where(n => n.Tier == (int)TierLevel.Two).OrderBy(n => n.ResponseTime).FirstOrDefault(); if (t2Node != null) { string xServerURL = Utils.GetServerUrl(t2Node.NetworkProtocol, t2Node.NetworkAddress, t2Node.NetworkPort); var client = new RestClient(xServerURL); client.UseNewtonsoftJson(); var getPriceLockRequest = new RestRequest("/getprofile", Method.GET); getPriceLockRequest.AddParameter("name", name); getPriceLockRequest.AddParameter("keyAddress", keyAddress); var createPLResult = client.Execute <ProfileResult>(getPriceLockRequest); if (createPLResult.StatusCode == HttpStatusCode.OK) { if (createPLResult.Data == null) { result.Success = false; } else { result = createPLResult.Data; result.Success = true; } } else { var errorResponse = JsonConvert.DeserializeObject <ErrorResponse>(createPLResult.Content); if (errorResponse != null) { result.ResultMessage = errorResponse.errors[0].message; } else { result.ResultMessage = "Failed to access xServer"; } result.Success = false; } } else { result.ResultMessage = "Not connected to any tier 2 servers"; } return(result); }
public static void EndScope() { if (currentSession == null) { Log.Core.Error("[profiler] no session to end a scope"); return; } mutex.WaitOne(); ProfileResult result = profileResultsStack.Pop(); result.ElapsedTime = ((float)(DateTime.Now - appStarted).Ticks / TimeSpan.TicksPerMillisecond) - result.Start; WriteProfile(ref result); mutex.ReleaseMutex(); }
private float Calculate(ProfileResult profileResult) { if (profileResult.Value != null) { return(profileResult.Value.Value * profileResult.Coeff.Value); } else { var results = new List <float>(); foreach (ProfileResult r in profileResult.ProfileResults) { float result = Calculate(r) * (r.Value.HasValue ? 1 : r.Coeff.Value); results.Add(result); } return(results.Sum()); } }
/// <summary> /// Set instagram username /// </summary> /// <param name="username"></param> /// <returns></returns> public UpdateProfileResult SetUsername(string newUsername) { try { ProfileResult profile = GetProfile(); profile.form_data.username = newUsername; var updateProfileResult = UpdateProfile(profile); if (updateProfileResult.status == "ok") { Username = newUsername; } return(updateProfileResult); } catch (Exception ex) { Debug.WriteLine("Change username error " + ex.Message); throw ex; } }
private static void WriteProfile(ref ProfileResult result) { string json = ""; json += ",{"; json += "\"cat\":\"function\","; json += "\"dur\":" + result.ElapsedTime.ToString(nfi) + ','; json += "\"name\":\"" + result.Name + "\","; json += "\"ph\":\"X\","; json += "\"pid\":0,"; json += "\"tid\":" + result.ThreadID + ","; json += "\"ts\":" + result.Start.ToString(nfi); json += "}"; if (currentSession != null) { streamWriter.Write(json); streamWriter.Flush(); outputStream.Flush(); } }
private static void CheckForProductionDataPresence(ProfileResult profile, List <StationLLPoint> points = null) { //Check for no production data at all - Raptor may return cells but all heights will be NaN bool gotData = profile.cells != null && profile.cells.Count > 0; var heights = gotData ? (from c in profile.cells where !float.IsNaN(c.firstPassHeight) select c).ToList() : null; if (heights != null && heights.Count > 0) { profile.minStation = profile.cells.Min(c => c.station); profile.maxStation = profile.cells.Max(c => c.station); profile.minHeight = heights.Min(h => h.minHeight); profile.maxHeight = heights.Max(h => h.maxHeight); profile.alignmentPoints = points; } else { profile.minStation = double.NaN; profile.maxStation = double.NaN; profile.minHeight = double.NaN; profile.maxHeight = double.NaN; profile.alignmentPoints = points; } }
private void UpdateResultsCache(Profile profile) { // We need to update cache information for the publicly visible profiles var results = _cache.GetProfileResults(); if (results == null) { // There are no results in the cache so we don't need to update it return; } var cachedResult = results.FirstOrDefault(x => x.Id == profile.Id); var cacheRequiresUpdate = false; if (cachedResult != null) { // We found this profile in the cache, the profile has been updated, has been deleted // or is hidden or banned We need to start by removing the existing profile from the cache results.Remove(cachedResult); cacheRequiresUpdate = true; } if (profile.Status != ProfileStatus.Hidden && profile.BannedAt == null) { // The profile is visible so the updated profile needs to be added into the results cache var newResult = new ProfileResult(profile); results.Add(newResult); cacheRequiresUpdate = true; } if (cacheRequiresUpdate) { _cache.StoreProfileResults(results); } }
public ProfileResult CreateAnswer(Profile answer) { var answerresult = new ProfileResult(); return(answerresult); }
public async Task <UpdateProfileResult> UpdateProfile(ProfileResult profile, string mail) { Debug.WriteLine("Update profile"); CookieContainer reserve = mCoockieC; Exception exeption = new Exception(); for (int i = 0; i < 5; i++) { string chainingEnable = "", data = ""; try { chainingEnable = profile.form_data.chaining_enabled ? "on" : "off"; data = $"first_name={WebUtility.UrlEncode(profile.form_data.first_name)}&email={mail}&username={WebUtility.UrlEncode(profile.form_data.username)}&phone_number={WebUtility.UrlEncode(String.Empty)}&gender={profile.form_data.gender}&biography={WebUtility.UrlEncode(profile.form_data.biography)}&external_url={WebUtility.UrlEncode(profile.form_data.external_url)}&chaining_enabled={chainingEnable}"; } catch (Exception ex) { Debug.WriteLine(ex.Message); lock (LogIO.locker) logging.Invoke(LogIO.mainLog, new Log() { UserName = null, Date = DateTime.Now, LogMessage = $"{ex.Message}", Method = "HttpAndroid.LogIn" }); throw; } try { var content = Encoding.ASCII.GetBytes(data); var request = HttpRequestBuilder.Post("https://www.instagram.com/accounts/edit/", _userAgent, mCoockieC); request.Referer = "https://www.instagram.com/accounts/edit/"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = content.Length; request.KeepAlive = true; request.Headers["Origin"] = "https://www.instagram.com"; // maybe exception if mCookieC not contain csrftoken request.Headers["X-CSRFToken"] = mCoockieC.GetCookies(new Uri("https://www.instagram.com"))["csrftoken"].Value; request.Headers["X-Instagram-AJAX"] = "1"; request.Headers["X-Requested-With"] = "XMLHttpRequest"; request.Proxy = _proxy; using (var requestStream = request.GetRequestStream()) { requestStream.Write(content, 0, content.Length); HttpWebResponse response = null; try { response = await request.GetResponseAsync() as HttpWebResponse; } catch (WebException e) { response = (HttpWebResponse)e.Response; } using (var responseStream = response.GetResponseStream()) using (var streamReader = new StreamReader(responseStream)) { // If we get result, it always return status ok. Otherwise, exception will occur. mCoockieC.Add(response.Cookies); var responseData = streamReader.ReadToEnd(); return(JsonConvert.DeserializeObject <UpdateProfileResult>(responseData)); } } } catch (Exception ex) { // When you change your username with existed username, you will receive 404 error // and obviously exception will occur. In this case, just return false exeption = ex; Debug.WriteLine("UpdateProfile progress occur exception " + ex.Message); lock (LogIO.locker) logging.Invoke(LogIO.mainLog, new Log() { UserName = null, Date = DateTime.Now, LogMessage = $"Exception! {ex.Message}", Method = "HttpAndroid.UpdateProfile" }); mCoockieC = reserve; continue; } } throw exeption; }
static void Main(string[] args) { #region Setup and Authentication var clientId = File.ReadAllText(clientIdFile); var secretKey = File.ReadAllText(secretKeyFile); var code = File.Exists(codeFile) ? File.ReadAllText(codeFile) : null; var authToken = File.Exists(tokenFile) ? JsonConvert.DeserializeObject <AuthToken>(File.ReadAllText(tokenFile)) : null; var api = new HFAPI(clientId, secretKey, authToken); if (authToken == null) { if (api.TryGetAuthToken(code, out authToken)) { File.WriteAllText(tokenFile, JsonConvert.SerializeObject(authToken)); api.SetAuthToken(authToken); } else { Console.WriteLine("Failed to acquire authentication token from code in file: " + codeFile); Console.WriteLine(authToken.ExceptionMessage); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); Environment.Exit(1); } } #endregion //--------------------- Reads ------------------------- // Profile ProfileResult profile = api.ProfileRead(); AdvancedProfileResult AdvancedProfileRead = api.AdvancedProfileRead(); // Forums ForumResult ForumGet = api.ForumGet(2); // Threads ThreadResult ThreadGet = api.ThreadGet(6083735); // Automatically loads nested result types UserResult firstPostUser = ThreadGet.FirstPost.User; ThreadResult[] ThreadSearchByUserId = api.ThreadSearchByUserId(authToken.UserId, 55709, 3); // Posts PostResult PostGet = api.PostGet(59991944); PostResult[] PostSearchByThreadId = api.PostSearchByThreadId(6083735, 1, 2); PostResult[] PostSearchByUserId = api.PostSearchByUserId(55709, 1, 4); // Byte Transactions ByteTransactionResult[] ByteTransactionSearchByUserId = api.ByteTransactionSearchByUserId(55709, 1, 2); ByteTransactionResult[] ByteTransactionSearchByFromUserId = api.ByteTransactionSearchByFromUserId(55709, 1, 3); ByteTransactionResult[] ByteTransactionSearchByToUserId = api.ByteTransactionSearchByToUserId(55709, 1, 4); ByteTransactionResult ByteTransactionGet = api.ByteTransactionGet(ByteTransactionSearchByUserId.First().Id); // Contracts ContractResult[] ContractSearchByUserId = api.ContractSearchByUserId(55709, 1, 1); ContractResult ContractGet = api.ContractGet(ContractSearchByUserId.First().Id); //--------------------- Writes ------------------------- // ThreadResult createThread = api.ThreadCreate(375, "HFAPI.ThreadCreate Test", "Testing thread creation with my C# wrapper for the HF API."); }
private string GenerateProfileUnitTestCall(BehaviourTestSuite testSuite, int index, ProfileResult expected, Dictionary <string, string> tags, bool invertPriority) { _skeleton.AddDep("debug_table"); var parameters = new Dictionary <string, string>(); var keysToCheck = new List <string>(); foreach (var(key, value) in tags) { if (key.StartsWith("#")) { parameters[key.TrimStart('#')] = value; } if (key.StartsWith("_relation:")) { keysToCheck.Add(key); } } foreach (var key in keysToCheck) { var newKey = key.Replace(".", "_"); if (newKey == key) { continue; } tags[newKey] = tags[key]; tags.Remove(key); } foreach (var(paramName, _) in parameters) { tags.Remove("#" + paramName); } var expectedPriority = "" + expected.Priority; if (invertPriority) { expectedPriority = $"inv({expectedPriority})"; } // Generates something like: // function unit_test_profile(profile_function, profile_name, index, expected, tags) return ($"unit_test_profile(behaviour_{testSuite.Profile.Name.AsLuaIdentifier()}_{testSuite.BehaviourName.AsLuaIdentifier()}, " + $"\"{testSuite.BehaviourName}\", " + $"{index}, " + $"{{access = \"{D(expected.Access)}\", speed = {expected.Speed}, oneway = \"{D(expected.Oneway)}\", priority = {expectedPriority} }}, " + tags.ToLuaTable() + ")"); }
public CalculateProfile(ProfileResult result) { this.result = result; }
public ActionResult ProfileResult(ProfileResult answer) { return(View(answer)); }
/// <summary> /// Get profile. /// </summary> public ProfileResult GetProfile(ProfileRequest profileRequest) { ProfileResult result = null; if (!string.IsNullOrWhiteSpace(profileRequest.KeyAddress)) { var profile = database.dataStore.GetProfileByKeyAddress(profileRequest.KeyAddress); if (profile != null) { result = new ProfileResult() { KeyAddress = profile.KeyAddress, Name = profile.Name, Signature = profile.Signature, PriceLockId = profile.PriceLockId, Status = profile.Status, ReturnAddress = profile.ReturnAddress, BlockConfirmed = profile.BlockConfirmed }; } else { var profileReservation = database.dataStore.GetProfileReservationByKeyAddress(profileRequest.KeyAddress); if (profileReservation != null) { result = new ProfileResult() { KeyAddress = profileReservation.KeyAddress, Name = profileReservation.Name, Signature = profileReservation.Signature, PriceLockId = profileReservation.PriceLockId, Status = profileReservation.Status, ReservationExpirationBlock = profileReservation.ReservationExpirationBlock }; } } } else if (!string.IsNullOrWhiteSpace(profileRequest.Name)) { var profile = database.dataStore.GetProfileByName(profileRequest.Name); if (profile != null) { result = new ProfileResult() { KeyAddress = profile.KeyAddress, Name = profile.Name, Signature = profile.Signature, PriceLockId = profile.PriceLockId, Status = profile.Status, BlockConfirmed = profile.BlockConfirmed }; } else { var profileReservation = database.dataStore.GetProfileReservationByName(profileRequest.Name); if (profileReservation != null) { result = new ProfileResult() { KeyAddress = profileReservation.KeyAddress, Name = profileReservation.Name, Signature = profileReservation.Signature, PriceLockId = profileReservation.PriceLockId, Status = profileReservation.Status, ReservationExpirationBlock = profileReservation.ReservationExpirationBlock }; } } } return(result); }
internal void AddProfile(ProfileResult result) { #if PROFILE profileResults.Add(result); #endif }
/// <summary> /// Update user profile /// </summary> /// <param name="user"></param> /// <returns>dynamic data maybe dangerous but i think some time dangerous is good LOL!!! - cause i'm lazy</returns> private UpdateProfileResult UpdateProfile(ProfileResult profile) { Debug.WriteLine("Update profile"); string chainingEnable = "", data = ""; try { chainingEnable = profile.form_data.chaining_enabled ? "on" : "off"; data = $"first_name={WebUtility.UrlEncode(profile.form_data.first_name)}&email={profile.form_data.email}&username={WebUtility.UrlEncode(profile.form_data.username)}&phone_number={WebUtility.UrlEncode(profile.form_data.phone_number)}&gender={profile.form_data.gender}&biography={WebUtility.UrlEncode(profile.form_data.biography)}&external_url={WebUtility.UrlEncode(profile.form_data.external_url)}&chaining_enabled={chainingEnable}"; } catch (Exception ex) { Debug.WriteLine(ex.Message); throw; } try { var content = Encoding.ASCII.GetBytes(data); var request = HttpRequestBuilder.Post("https://www.instagram.com/accounts/edit/", mCoockieC); request.Referer = "https://www.instagram.com/accounts/edit/"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = content.Length; request.KeepAlive = true; request.Headers["Origin"] = "https://www.instagram.com"; // maybe exception if mCookieC not contain csrftoken request.Headers["X-CSRFToken"] = mCoockieC.GetCookies(new Uri("https://www.instagram.com"))["csrftoken"].Value; request.Headers["X-Instagram-AJAX"] = "1"; request.Headers["X-Requested-With"] = "XMLHttpRequest"; using (var requestStream = request.GetRequestStream()) { requestStream.Write(content, 0, content.Length); using (var response = request.GetResponse() as HttpWebResponse) { mCoockieC.Add(response.Cookies); using (var responseStream = response.GetResponseStream()) using (var streamReader = new StreamReader(responseStream)) { // If we get result, it always return status ok. Otherwise, exception will occur. var responseData = streamReader.ReadToEnd(); return JsonConvert.DeserializeObject<UpdateProfileResult>(responseData); } } } } catch (Exception ex) { // When you change your username with existed username, you will receive 404 error // and obviously exception will occur. In this case, just return false Debug.WriteLine(ex.Message); throw ex; } }
public static void Main(string[] args) { var benchmarksnames = new string[0]; var sshkey = String.Empty; var optindex = 0; for (; optindex < args.Length; ++optindex) { if (args [optindex] == "-b" || args [optindex] == "--benchmarks") { benchmarksnames = args [++optindex].Split(',').Select(s => s.Trim()).Union(benchmarksnames).ToArray(); } else if (args [optindex] == "--sshkey") { sshkey = args [++optindex]; } else if (args [optindex].StartsWith("--help")) { UsageAndExit(); } else if (args [optindex] == "--") { optindex += 1; break; } else if (args [optindex].StartsWith("-")) { Console.Error.WriteLine("unknown parameter {0}", args [optindex]); UsageAndExit(); } else { break; } } if (args.Length - optindex < 2) { UsageAndExit(null, 1); } var project = args [optindex++]; var architecture = args [optindex++]; var resultsfolder = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), Path.GetRandomFileName())).FullName; var graphsfolder = Directory.CreateDirectory(Path.Combine(resultsfolder, "graphs")).FullName; Console.WriteLine("Downloading results files into \"{0}\"", resultsfolder); RSyncFromRemote(sshkey, String.Format("/volume1/storage/benchmarker/runs/{0}/{1}/*", project, architecture), resultsfolder); Console.WriteLine("Reading results files"); IEnumerable <ProfileResult> profiles = Directory.EnumerateFiles(resultsfolder, "*.json.gz", SearchOption.AllDirectories) .AsParallel() .Where(f => !f.EndsWith(".counters.json.gz")) .Select(f => ProfileResult.LoadFrom(f, true)); if (benchmarksnames.Length > 0) { profiles = profiles.Where(p => benchmarksnames.Any(n => p.Benchmark.Name == n)); } profiles = profiles.AsParallel().ToArray(); Console.WriteLine("Generating graphs data in \"{0}\"", graphsfolder); { // Time + Counters data for each benchmark Parallel.ForEach(profiles.GroupBy(p => p.Benchmark), benchmark => { // Counter.Name | "Time" => Config.Name => List [KeyValuePair[Revision.Commit, Value]] var data = new Dictionary <string, Dictionary <string, List <KeyValuePair <string, double> > > > (); Console.Write("Benchmark: {0}, Counter: {1}{2}", benchmark.Key.Name, "Time", Environment.NewLine); data.Add("Time", BenchmarkData(benchmark.Key, benchmark, run => run.WallClockTime.TotalMilliseconds)); foreach (var counter in ExtractIntersectCounters(benchmark)) { try { Console.Write("Benchmark: {0}, Counter: {1}{2}", benchmark.Key.Name, counter, Environment.NewLine); data.Add(counter.ToString(), BenchmarkData(benchmark.Key, benchmark.AsEnumerable(), run => ExtractLastCounterValue(run, counter))); } catch (InvalidCastException e) { Console.Out.WriteLine("Cannot convert \"{0}\" last value to double : {1}{2}", counter, Environment.NewLine, e.ToString()); } } using (var stream = new FileStream(Path.Combine(graphsfolder, benchmark.Key.Name + ".json"), FileMode.Create)) using (var writer = new StreamWriter(stream)) writer.Write(JsonConvert.SerializeObject( data.Select(kv => KeyValuePair.Create( kv.Key, kv.Value.Select(kv1 => KeyValuePair.Create(kv1.Key, kv1.Value.Select(kv2 => new { Commit = kv2.Key, Value = kv2.Value }).ToList())) .ToDictionary(kv1 => kv1.Key, kv1 => kv1.Value) )) .ToDictionary(kv => kv.Key, kv => kv.Value), Formatting.Indented )); }); } { // Min/Average/Max counter data for each config Parallel.ForEach(profiles.GroupBy(p => p.Config), config => { // Counter.Name | "Time" => List [KeyValuePair[Revision.Commit, Tuple[Min, Average, Max]]] var data = new Dictionary <string, List <KeyValuePair <string, Tuple <double, double, double> > > > (); Console.Write("Config: {0}, Counter: {1}{2}", config.Key.Name, "Time", Environment.NewLine); data.Add("Time", ConfigData(config.Key, config, run => run.WallClockTime.TotalMilliseconds)); foreach (var counter in ExtractIntersectCounters(config)) { try { Console.Write("Config: {0}, Counter: {1}{2}", config.Key.Name, counter, Environment.NewLine); data.Add(counter.ToString(), ConfigData(config.Key, config.AsEnumerable(), run => ExtractLastCounterValue(run, counter))); } catch (InvalidCastException e) { Console.Out.WriteLine("Cannot convert \"{0}\" last value to double : {1}{2}", counter, Environment.NewLine, e.ToString()); } } using (var stream = new FileStream(Path.Combine(graphsfolder, config.Key.Name + ".config.json"), FileMode.Create)) using (var writer = new StreamWriter(stream)) writer.Write(JsonConvert.SerializeObject( data.Select(kv => KeyValuePair.Create( kv.Key, kv.Value.Select(kv1 => new { Commit = kv1.Key, Min = kv1.Value.Item1, Average = kv1.Value.Item2, Max = kv1.Value.Item3 }) .ToList() )) .ToDictionary(kv => kv.Key, kv => kv.Value) )); }); } Console.WriteLine("Uploading graphs"); SCPToRemote(sshkey, Directory.EnumerateFileSystemEntries(graphsfolder).ToList(), String.Format("/volume1/storage/benchmarker/graphs/{0}/{1}", project, architecture)); }