/// <summary> /// Cleans the expired items from the cache. /// </summary> /// <remarks>CFI, 2012-03-10</remarks> private void CleanExpired() { var expired = from l in lifetime.AsParallel() where l.Value <= DateTimeOffset.Now select l; expired.ForAll((e) => { values.Remove(e.Key); lifetime.Remove(e.Key); }); }
public void Update <T>(string key, T newvalue) { if (_persistentDictionary.ContainsKey(key)) { _persistentDictionary.Remove(key); } Put(key, newvalue); }
/// <summary> /// Test dictionary insert/replace/delete. /// </summary> /// <typeparam name="TKey">Key type of the dictionary.</typeparam> /// <typeparam name="TValue">Value type of the dictionary.</typeparam> /// <param name="dictionary">The dictionary to test.</param> /// <param name="key">Key that is present in the dictionary.</param> /// <param name="value">Value associated with the key in the dictionary.</param> private static void TestBasicOperations <TKey, TValue>(PersistentDictionary <TKey, TValue> dictionary, TKey key, TValue value) where TKey : IComparable <TKey> { var kvp = new KeyValuePair <TKey, TValue>(key, value); // Add a record dictionary.Add(key, value); // Test PersistentDictionary.Add error handling try { dictionary.Add(key, value); Assert.Fail("Expected ArgumentException from Add"); } catch (ArgumentException) { // Expected } // Overwrite a value dictionary[key] = value; // Retrieve a value Assert.AreEqual(value, dictionary[key], "Retrieve with [] failed"); TValue t; Assert.IsTrue(dictionary.TryGetValue(key, out t), "TryGetValue({0}) failed", key); Assert.AreEqual(value, t, "TryGetValue({0}) returned the wrong value", key); // Clear and re-insert dictionary.Clear(); Assert.AreEqual(0, dictionary.Count, "Dictionary is empty. Count is wrong"); dictionary[key] = value; Assert.AreEqual(1, dictionary.Count, "Item was just inserted. Count is wrong"); // Get the keys and values Assert.AreEqual(dictionary.Keys.First(), key, "Keys collection"); Assert.AreEqual(dictionary.Values.First(), value, "Values collection"); // Test PersistentDictionary.Contains (true) Assert.IsTrue(dictionary.ContainsKey(key), "Dictionary should have contained key {0}", key); Assert.IsTrue(dictionary.ContainsValue(value), "Dictionary should have contained value {0}", value); Assert.IsTrue(dictionary.Contains(kvp), "Dictionary should have contained <{0},{1}>", key, value); // Test PersistentDictionary.Remove Assert.IsTrue(dictionary.Remove(key), "Key {0} should exist, but removal failed", key); Assert.IsFalse(dictionary.Remove(key), "Key {0} doesn't exist, but removal succeeded", key); dictionary.Add(kvp); Assert.IsTrue(dictionary.Remove(kvp), "KeyValuePair <{0},{1}> should exist, but removal failed", kvp.Key, kvp.Value); Assert.IsFalse(dictionary.Remove(kvp), "KeyValuePair <{0},{1}> doesn't exist, but removal succeeded", kvp.Key, kvp.Value); // Test PersistentDictionary.Contains (false) Assert.IsFalse(dictionary.ContainsKey(key), "Dictionary should have contained key {0}", key); Assert.IsFalse(dictionary.ContainsValue(value), "Dictionary should have contained value {0}", value); Assert.IsFalse(dictionary.Contains(kvp), "Dictionary should have contained <{0},{1}>", key, value); }
public bool Remove(string key) { Cache.Remove(key); var s = EsentDic.Remove(key); return(s); }
public bool Remove(string key) { lock (syncRoot) { Cache.Remove(key); var s = EsentDic.Remove(key); return(s); } }
public void Delete(string objId) { if (mutex.Wait(TimeSpan.FromSeconds(DefaultTime))) { if (!_persistentDictionary.ContainsKey(objId)) { return; } _persistentDictionary.Remove(objId); var expFile = objId + "-expiration.json"; if (_persistentDictionary.ContainsKey(expFile)) { _persistentDictionary.Remove(expFile); } _persistentDictionary.Flush(); mutex.Release(); } }
static void Benchmark() { var payload = new byte[4 * 1024]; var dir = "temp"; if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); Utility.Timeit("File system", 1, () => { var random = new Random(); for (var i = 0; i < 40000; ++i) { var path = string.Format("{0}/{1}.txt", dir, random.Next(1000)); switch (random.Next(2)) { case 0: File.WriteAllBytes(path, payload); break; case 1: if (File.Exists(path)) File.Delete(path); break; default: throw new NotSupportedException(); } } }); Utility.Timeit("PersistentDictionary", 1, () => { if (File.Exists("1.txt")) File.Delete("1.txt"); var random = new Random(); using (var dict = new PersistentDictionary("1.txt")) { for (var i = 0; i < 40000; ++i) { var key = string.Format("{0}/{1}.txt", dir, random.Next(1000)); switch (random.Next(2)) { case 0: if (dict.ContainsKey(key)) dict[key] = payload; else dict.Add(key, payload); break; case 1: if (dict.ContainsKey(key)) dict.Remove(key); break; default: throw new NotSupportedException(); } } } }); }
public void changeConfig(string name, string value) { using (PersistentDictionary <string, string> dictionary = new PersistentDictionary <string, string>(getConfigLogPath())) { if (dictionary.ContainsKey(name)) { dictionary.Remove(name); dictionary.Add(name, value); } } }
static void Test() { using (var dict = new PersistentDictionary("1.txt")) { string line; while ((line = Console.ReadLine()) != null) { try { var tokens = line.Split(); switch (tokens[0].ToLower()) { case "add": dict.Add(tokens[1], Encoding.UTF8.GetBytes(tokens[2])); break; case "update": dict[tokens[1]] = Encoding.UTF8.GetBytes(tokens[2]); break; case "remove": dict.Remove(tokens[1]); break; case "dump": { foreach (var kv in dict.OrderBy(kv => kv.Key)) Console.WriteLine("\t{0}: {1}", kv.Key, Encoding.UTF8.GetString(kv.Value)); } break; default: throw new NotSupportedException(); } Console.WriteLine("Done."); } catch (Exception e) { Console.WriteLine(e); } } } }
private void ProcessingThread() { // Start AcquireFrame/ReleaseFrame loop while (senseManager.AcquireFrame(true) >= pxcmStatus.PXCM_STATUS_NO_ERROR) { // Acquire the color image data PXCMCapture.Sample sample = senseManager.QuerySample(); Bitmap colorBitmap; PXCMImage.ImageData colorData; int topScore = 0; FaceExpression expression = FaceExpression.None; sample.color.AcquireAccess(PXCMImage.Access.ACCESS_READ, PXCMImage.PixelFormat.PIXEL_FORMAT_RGB24, out colorData); colorBitmap = colorData.ToBitmap(0, sample.color.info.width, sample.color.info.height); try { IBarcodeReader reader = new BarcodeReader(); // load a bitmap //var barcodeBitmap = (Bitmap)Bitmap.LoadFrom("C:\\sample-barcode-image.png"); // detect and decode the barcode inside the bitmap var result = reader.Decode(colorBitmap); // do something with the result if (result != null) { MessageBox.Show(result.BarcodeFormat.ToString()); MessageBox.Show(result.Text); } } catch (Exception ex) { } // Get face data if (faceData != null) { faceData.Update(); numFacesDetected = faceData.QueryNumberOfDetectedFaces(); if (numFacesDetected > 0) { // Get the first face detected (index 0) PXCMFaceData.Face face = faceData.QueryFaceByIndex(0); // Retrieve face location data PXCMFaceData.DetectionData faceDetectionData = face.QueryDetection(); if (faceDetectionData != null) { PXCMRectI32 faceRectangle; faceDetectionData.QueryBoundingRect(out faceRectangle); if ((faceRectangle.h > 90) || (faceRectangle.w > 90)) { faceRectangleHeight = faceRectangle.h * 3 / 2; faceRectangleWidth = faceRectangle.w * 3 / 2; } else if (((faceRectangle.h < 90) || (faceRectangle.w < 90)) && ((faceRectangle.h > 70) || (faceRectangle.w > 70))) { faceRectangleHeight = faceRectangle.h * 2; faceRectangleWidth = faceRectangle.w * 2; } else { faceRectangleHeight = faceRectangle.h * 5 / 2; faceRectangleWidth = faceRectangle.w * 5 / 2; } faceRectangleX = faceRectangle.x; faceRectangleY = faceRectangle.y; } // Retrieve pose estimation data PXCMFaceData.PoseData facePoseData = face.QueryPose(); if (facePoseData != null) { PXCMFaceData.PoseEulerAngles headAngles; facePoseData.QueryPoseAngles(out headAngles); headRoll = headAngles.roll; headPitch = headAngles.pitch; headYaw = headAngles.yaw; } // Retrieve expression data PXCMFaceData.ExpressionsData expressionData = face.QueryExpressions(); if (expressionData != null) { PXCMFaceData.ExpressionsData.FaceExpressionResult score; expressionData.QueryExpression(PXCMFaceData.ExpressionsData.FaceExpression.EXPRESSION_KISS, out score); expressionScore[Convert.ToInt32(FaceExpression.Kiss)] = score.intensity; expressionData.QueryExpression(PXCMFaceData.ExpressionsData.FaceExpression.EXPRESSION_MOUTH_OPEN, out score); expressionScore[Convert.ToInt32(FaceExpression.Open)] = score.intensity; expressionData.QueryExpression(PXCMFaceData.ExpressionsData.FaceExpression.EXPRESSION_SMILE, out score); expressionScore[Convert.ToInt32(FaceExpression.Smile)] = score.intensity; expressionData.QueryExpression(PXCMFaceData.ExpressionsData.FaceExpression.EXPRESSION_TONGUE_OUT, out score); expressionScore[Convert.ToInt32(FaceExpression.Tongue)] = score.intensity; // Determine the highest scoring expression for (int i = 1; i < TotalExpressions; i++) { if (expressionScore[i] > topScore) { expression = (FaceExpression)i; } } } // Process face recognition data if (face != null) { // Retrieve the recognition data instance recognitionData = face.QueryRecognition(); // Set the user ID and process register/unregister logic if (recognitionData.IsRegistered()) { userId = Convert.ToString(recognitionData.QueryUserID()); if (doUnregister) { recognitionData.UnregisterUser(); SaveDatabaseToFile(); doUnregister = false; if (_persistentDict.ContainsKey(userId) == true) { _persistentDict.Remove(userId); } } } else { if (doRegister) { int uId = recognitionData.RegisterUser(); SaveDatabaseToFile(); if (newUserName != "") { if (_persistentDict.ContainsKey(uId.ToString()) == false) { _persistentDict.Add(uId.ToString(), newUserName); _persistentDict.Flush(); newUserName = ""; } } // Capture a jpg image of registered user colorBitmap.Save("image.jpg", System.Drawing.Imaging.ImageFormat.Jpeg); doRegister = false; } else { userId = "New User"; } } } } else { userId = "No users in view"; } } //hand = senseManager.QueryHand(); //if (hand != null) //{ // // Retrieve the most recent processed data // handData = hand.CreateOutput(); // handData.Update(); // // Get number of tracked hands // nhands = handData.QueryNumberOfHands(); // if (nhands > 0) // { // // Retrieve hand identifier // handData.QueryHandId(PXCMHandData.AccessOrderType.ACCESS_ORDER_BY_TIME, 0, out handId); // // Retrieve hand data // handData.QueryHandDataById(handId, out ihand); // PXCMHandData.BodySideType bodySideType = ihand.QueryBodySide(); // if (bodySideType == PXCMHandData.BodySideType.BODY_SIDE_LEFT) // { // leftHand = true; // } // else if (bodySideType == PXCMHandData.BodySideType.BODY_SIDE_RIGHT) // { // leftHand = false; // } // // Retrieve all hand joint data // for (int i = 0; i < nhands; i++) // { // for (int j = 0; j < 0x20; j++) // { // PXCMHandData.JointData jointData; // ihand.QueryTrackedJoint((PXCMHandData.JointType)j, out jointData); // nodes[i][j] = jointData; // } // } // // Get world coordinates for tip of middle finger on the first hand in camera range // handTipX = nodes[0][Convert.ToInt32(PXCMHandData.JointType.JOINT_MIDDLE_TIP)].positionWorld.x; // handTipY = nodes[0][Convert.ToInt32(PXCMHandData.JointType.JOINT_MIDDLE_TIP)].positionWorld.y; // handTipZ = nodes[0][Convert.ToInt32(PXCMHandData.JointType.JOINT_MIDDLE_TIP)].positionWorld.z; // swipehandTipX = nodes[0][Convert.ToInt32(PXCMHandData.JointType.JOINT_MIDDLE_TIP)].positionImage.x; // swipehandTipY = nodes[0][Convert.ToInt32(PXCMHandData.JointType.JOINT_MIDDLE_TIP)].positionImage.y; // swipehandTipZ = nodes[0][Convert.ToInt32(PXCMHandData.JointType.JOINT_MIDDLE_TIP)].positionImage.z; // //Console.Out.WriteLine("Before x={0}", swipehandTipX); // //Console.Out.WriteLine("Before speed={0}", nodes[0][Convert.ToInt32(PXCMHandData.JointType.JOINT_MIDDLE_TIP)].speed.x); // // Retrieve gesture data // if (handData.IsGestureFired("spreadfingers", out gestureData)) { gesture = Gesture.FingerSpread; } // else if (handData.IsGestureFired("two_fingers_pinch_open", out gestureData)) { gesture = Gesture.Pinch; } // else if (handData.IsGestureFired("wave", out gestureData)) { gesture = Gesture.Wave; } // else if (handData.IsGestureFired("swipe_left", out gestureData)) { gesture = Gesture.SwipeLeft; } // else if (handData.IsGestureFired("swipe_right", out gestureData)) { gesture = Gesture.SwipeRight; } // else if (handData.IsGestureFired("fist", out gestureData)) { gesture = Gesture.Fist; } // else if (handData.IsGestureFired("thumb_up", out gestureData)) { gesture = Gesture.Thumb; } // } // else // { // gesture = Gesture.Undefined; // } // //UpdateUI(); // if (handData != null) handData.Dispose(); //} // Display the color stream and other UI elements //UpdateUI(colorBitmap, expression, gesture); UpdateUI(colorBitmap, expression); // Release resources colorBitmap.Dispose(); sample.color.ReleaseAccess(colorData); sample.color.Dispose(); // Release the frame senseManager.ReleaseFrame(); } }
public void DeleteUser(string username) { _users.Remove(username); }