w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML Categories
Modification of lock object when another thread has acquired lock on that object
someObject.a = 10 // Will this work when Thread 1 has a lock on someObject? Yes. You can even write someObject = new SomeObject() if you so desire, irrespective of any/all locks. The lock keyword is mainly syntactic sugar around the Monitor class which needs an (any) object reference as key, has no impact on the actual objects. That being said, considering how easily and how fast threading can become complex, stick to simple patterns: if you need some synchronization of a code block, just use a dummy object explicitly for that purpose.

Categories : C#

Is there any way, in Python, to programmatically change the CAPS LOCK/NUM LOCK/SCROLL LOCK states on a hidraw device
Using library at Jakub Wilk's library at http://jwilk.net/software/python-keyboardleds, it is pretty simple: lk = LedKit('/dev/input/event1') lk.num_lock.reset() lk.caps_lock.reset() The trick is to determine which input device your keyboard is. To figure that out, you look at /proc/bus/input/devices. (Thanks to Jakub for this solution) I tested this on two a keyboards: PS1 keyboard connected via PS1 to USB adaptor with Holtek chipset (04d9:1400) A cheap numeric keypad, also with Holtek chipset (04d9:1603), HT82M99E. Result: It works for the former but not the latter. Perhaps someone knows whether that's a driver issue or a problem of the hardware itself (not responding to requests from the driver).

Categories : Python

Mongoose: CastError: Cast to ObjectId failed for value "[object Object]" at path "_id"
Short answer: use mongoose.Types.ObjectId. Mongoose (but not mongo) can accept object Ids as strings and "cast" them properly for you, so just use: MyClass.findById(req.params.id) However, the caveat is if req.params.id is not a valid format for a mongo ID string, that will throw an exception which you must catch. So the main confusing thing to understand is that mongoose.SchemaTypes has stuff you only use when defining mongoose schemas, and mongoose.Types has the stuff you use when creating data objects you want to store in the database or query objects. So mongoose.Types.ObjectId("51bb793aca2ab77a3200000d") works, will give you an object you can store in the database or use in queries, and will throw an exception if given an invalid ID string. findOne takes a query object and passe

Categories : Node Js

Mongoose - Cast to ObjectId failed for value "[object Object]" at path _id
I think you can only do .populate('users.id'). Populate is to use the reference Object to replace the id field. Please take a look at the doc.

Categories : Node Js

Mongoose TypeError: Cannot use 'in' operator to search for '_id' in [object Object]
So it was due to the way my color object was being unescaped when the request was being handled. Upon entering it was seeing the object but the nested values were not valid and therfore was throwing off the write tot eh db as it was expecting Strings. I ended up doing a POST instead and passing the json object in the data param and then reading it back out through the body and it works as expected and has automatically created the db as desired. Thanks Noah for the response!

Categories : Node Js

Lock a NSMutableArray of an object but not the rest of my object when using GCD
I would fetch the locations in a background thread into a separate array, and only assign it to the user when the data is complete, something like: dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSMutableArray *locations; // ... fill locations ... dispatch_sync(dispatch_get_main_queue(), ^{ user.locations = locations; // ... perhaps refresh some view or send a notification ... }) }); Then user.locations is always accessible on the main thread, and is either nil or contains the fetched locations.

Categories : Iphone

Create a schema in mongoose nodejs for one record only
Yes, this is possible without anything special really other than only put 1 document into that collection. I would just leave your default set of configuration settings as a simple javascript object in code and if you find a configuration record in mongo, just use that to override the defaults via _.defaults or similar. For what it's worth, more commonly identifying the blog admin would be stored on the user record, not in a blog configuration object (user.isAdmin = true for a simple case), but either way will work.

Categories : Database

Error 'Object has no method xxx ' while using Mongoose
The methods property of a model object in Mongoose is used to add functions to instances of model objects. So, in your code, the function list is added to an instance of UserModel. If you instead want to have a static like singleton function, then you could add it directly to the UserModel object returned by the call to mongoose.model('UserModel', userModelSchema);: UserModel.list = list; Now, you can call it to return the list of all users. Note that it's still an asynchronous function though. So, you can't just return the results of calling the function, as it will be empty normally. find is async, so your list function also needs to accept a callback that can be called when the list has been returned: UserModel.list(function(list) { res.render(list); });

Categories : Javascript

Mongoose find with reference to object
What you need is a closure since the loop, and item with it, will be done before any callback is called. for(var idx in items){ (function(item){ Model.find({'_id': item.id}, function(err, matches){ console.log(item); }); })(items[idx]); } Which should be pretty much the same as the following (assuming items is an array): items.forEach(function(item){ Model.find({'_id': item.id}, function(err, matches){ console.log(item); }); })(items[idx]);

Categories : Node Js

Does Mongoose Actually Validate the Existence of An Object Id?
No, an ObjectId field that's defined in your schema as a reference to another collection is not checked as existing in the referenced collection on a save. You could do it in Mongoose middleware, if needed.

Categories : Mongodb

how to return full object with mongoose
The key is to use the default attribute in a type definition to provide a default value. var userSchema = new Schema({ username : {type: String, index: {unique: true, dropDups: true}} , password : String , email : {type: String, index: {unique: true, dropDups: true}} , gender : {type: String, default: "Unknown" } }) For more information, the documentation is here.

Categories : Mongodb

Node and Mongoose create/use field that increases +1 for each new added
I can see several ways to do so. First, you may store last_id in a global variable: var last_id = 0; app.post('/app/new', function (req, res) { var newApp = app.db.models.userApp({ appid: ++last_id, appname: req.param('appname'), appdesc: req.param('appdesc') }); newApp.save(); }); You may add a proper initialization of last_id, so it'll "catch up" with your database when your application starts. The only disadvantage of this approach is that you can't use it if you have several node.js processes. Second, you may query your database each time you want to create new document: app.post('/app/new', function (req, res, next) { app.db.models.userApp.find() .sort({_id: -1}) .limit(1) .select('_id') .exec(function (err, docs) { if (err) return nex

Categories : Javascript

Mongoose Static Not Returning Object After Query
What about using a callback function? userSchema.statics = { getMongoIdByTwitterName : function (twittername, callback){ this.findOne(findOne({twitterID : req.user.id}, callback(err, user); ) } }

Categories : Mongodb

Storing Json Object in Mongoose String key
Yes, you can just store {myJsonProperty: JSON.stringify(myObject)}. Hopefully you know that you can also just set {myJsonProperty: Object} in your mongoose schema and store the whole object without converting it to a string for no reason. It doesn't have to be a nested document with a schema, it can be just a plain javascript object.

Categories : Node Js

how to find any document in database with an object id with mongoose?
Operations in MongoDB only always work on one collection. If you want to do a find on multiple collections, then you need to run multiple queries - one per collection. Of course, it's quite for Mongoose to implement a convenience function for that, but I don't think it has, or should, as it is against one of MongoDB's paradigms.

Categories : Node Js

Create a custom lock screen Windows 7
You need to implement a Credential Provider. There are several examples on the web, and the link above to MSDN should get you started. (Believe it or not, it's much simpler than implementing a GINA provider was in XP.)

Categories : C++

How to lock a object when using load balancing
This is a tricky problem - you need a distributed lock, or some sort of shared state. Since you already have the database, you could change your implementation from a "static C# lock" and instead the database to manage your lock for you over the whole "transaction". You don't say what database you are using, but if it's SQL Server, then you can use an application lock to achieve this. This lets you explicitly "lock" an object, and all other clients will wait until that object is unlocked. Check out: http://technet.microsoft.com/en-us/library/ms189823.aspx I've coded up an example implementation below. Start two instances to test it out. using System; using System.Data; using System.Data.SqlClient; using System.Transactions; namespace ConsoleApplication1 { class Program {

Categories : C#

How can I lock object's height on pygtk3?
When you pack_start() your widgets into the boxes, don't pass True, True for the "expand" and "fill" parameters unless you really want them to expand into and fill the available space. In this case, writing self.vbox.pack_start(self.hbox2, False, False, 0) will prevent the button and entry from growing larger in the vertical direction. You might consider using Gtk.Grid for arranging your widgets - Gtk.Box doesn't necessarily listen to the hexpand and vexpand properties.

Categories : Python

How to choose what object to lock on in Java?
This should fix the issue. public Object getValue() { synchronized(System.out){ System.out.print(" Doing "); System.out.println(" get "); System.out.flush(); return value; } }

Categories : Java

lock performance cloning object or not
Clone is O(n), but that doesn't tell the full story. A clone can be a shallow clone (just copy the references in the table) or a deep clone (copy the objects themselves). A deep clone can be a very expensive operation. Searching time can vary, too, from a quick search that checks just a single integer field, to a complex search that compares multiple values and is pretty expensive. In addition, if your data is sorted on the field that you're searching, then search is O(log n), which will be considerably faster than O(n). If you need to take into account the possibility that somebody will add, modify, or delete rows, then you either have to lock or clone. If you're doing a single search, then cloning doesn't really make sense because you'd have to lock the table in order to clone it. And c

Categories : C#

release lock from object in java
When you use notifyAll, you should also have a state changed and when you use wait, you should check that state change. In your case it is likely that notifyAll will be called long before the threads really have time to start. (For a computer, starting a thread takes an eternity, like 10,000,000 clock cycles) This means the notifyAll is lost. (It only notifies threads which are actually waiting right at that moment)

Categories : Java

Save object without releasing lock?
Successful save() returns the instance itself, you can lock() that again if you are not worried about the infinitesimal chance of a fetch while update. domain.save()?.lock()

Categories : Hibernate

StaleObjectStateException while trying to lock domain object
I suppose you use the db locking in order to support multi-servers that can use the same db. It looks like you code is fine. What can cause this exception is having run on debug and stop without proper finish the execution, therefore the db transaction is not committed and the lock remains. Try to execute this when no transaction is open for the same cmd.superBooking.id. Or try to use different ids when testing. In general, if it is more likely that your application will not perform several update on the same row, use optimistic locking instead. I.e. Instead of using lock method use try and catch for StaleObjectException.

Categories : Hibernate

Why is a redundant lock object needed?
lock keyword cannot exist on it's own, it always takes a parameter which will act as a semaphore (synchronizing object), allowing only one thread to proceed. http://www.albahari.com/threading/part2.aspx#_Locking Only one thread can lock the synchronizing object (in this case, thisLock) at a time, and any contending threads are blocked until the lock is released. If more than one thread contends the lock, they are queued on a “ready queue” and granted the lock on a first-come, first-served basis (a caveat is that nuances in the behavior of Windows and the CLR mean that the fairness of the queue can sometimes be violated).

Categories : C#

Synchronizaton Object Lock Confusion
So in this example, will the lock be acquired on AccountDanger instance or Account object? Yes. One trick I've seen used a lot is to synchronize on this when you have only a small block of code that actually needs to be synchronized. For example: int balance = -1; synchronized(this) { balance = account.getBalance(); account.withdraw(amt); } //IO, etc. after that. In general this speeds things up.

Categories : Java

Query nested object dynamically in Mongodb + Mongoose.js
var user_id = req.params.id; var query = {}; query['ratings.' + user_id] = {$exists: true}; Item.find(query, function(err, items) { ... }); The key in the object you send to Item.find have to be a string. To construct a string of any arbitrary values you have to first create the object and then use the bracket notation to define it (that is: query[anything+here] = data).

Categories : Javascript

mongoose model inheritance within javascript prototypal object
This turns out to be unrelated to javascript prototypes and completely due to how mongoose does Mixed Type Schemas: In order to tell mongoose the document has changed you need to markModified(field) example here: http://mongoosejs.com/docs/schematypes.html#mixed

Categories : Node Js

Why doesn't my Mongoose schema method "see" my required object?
I believe the issue is that you've created a circular dependency. Story executes require(config.models) which requires Story again inside index.js. Rather than storing a string and requireing it everywhere, try storing the models directly in config.models: config.js module.exports = { test: 'test', models: require(__dirname + '/models') };

Categories : Node Js

Difference between saved/load json object in Mongoose
If you look at the document saved to the MongoDB, you'll see that the twitter object isn't actually present unless the properties of the sub object are set. The object is created so that you can conveniently set properties without needing to worry about creating the sub/nested object. So you can do this: var user = new User(); user.twitter.id = 'wiredprairie'; user.save(); Results: { "_id" : ObjectId("522259394eb9ed0c30000002"), "twitter" : { "id" : "wiredprairie" }, "__v" : 0 } And if you went one step further and wanted a more "pure" view of the data, you could use toJSON on the Mongoose model instance: console.log(user.toJSON()); results: { _id: 522259ad3621834411000001, twitter: { id: 'wiredprairie' } }

Categories : Javascript

what logic should be used to create a lock screen like in angry birds
As per my view you don't have to use text file for any of the purpose in game development. Either you have to use database or shared preferences. This thing well discussed in following websites http://www.matim-dev.com/data-storage.html http://developer.android.com/guide/topics/data/data-storage.html

Categories : Java

Express cookieSession and Mongoose: how can I make request.session.user be a Mongoose model?
Express session is stored as separate storage and has limitations to what can be stored there. It cannot store prototype data (methods). Look at it more like key<>value storage. Reasons for this is that session can be stored anywhere (pretty much), such as: process memory; databases (mongodb); redis; etc. Because of this, once you put anything in session object and request is finished, express will take session data, parse it and stick into session store just as pure object. By default it is process memory, but as mentioned before - can be any other storages. So when next http request happens, session middleware will try to restore session using cookie (if it is used) data in request headers, and will ask session storage to provide data back. As it is already formatted - it will n

Categories : Node Js

Mongoose connect method fails on simple Node Server. Express, Mongoose, Path
You need to actually successfully get mongod running and listening for connections. Just type mongod with no options, hit ENTER, and let it run. Then in a separate terminal start your express app. Note that mongod is the mongodb server daemon whereas mongo is the command line client where you can run an interactive REPL and issue database commands.

Categories : Node Js

Inserting Object ID's into array in existing Mongoose schema with Node.js
Keep the category names you want to search for in an array { categories: ["cat1", "cat2"] } then you can add an index to it and do a $in query. the current schema is not very good because you cannot look for the category in a single query but need to resolve all the "categories" links first.

Categories : Javascript

Java program unable to create lock on Neo4j database
Are you sure that the uid which the neo4j server uses has write privileges to the data directory? And are you sure that there are no multiple instances running? You can check that with a ps axf|grep neo4j on your terminal.

Categories : Neo4j

Do create an EclipseLink EntityManager per method call or guard with a lock?
EntityManagers are not thread safe, and are designed to represent a unit of work. Each method/thread should have its own unless participating in a larger transaction. It is also better to close/clear them at logical points because they maintain a cache of managed entities that can grow large with long lived EntityManagers. There are numerous posts on what the best way to go is outside and inside a container. EclipseLink's EntityManager uses EclipseLink's native sessions and unitOfWork underneath, which will lazily fetch resources as required, and release them when done. But they can be configured to operate differently.

Categories : Java

Which time the calling thread gets object's intrinsic lock?
A synchronized block prevents other threads to enter the same or another synchonized block on the same object. You have a single synchronized block here, and only one thread enters it. So all the other threads can execute whatever they want.

Categories : Java

Removing Attribute from JavaScript Object, Returned by Mongoose's "findOneAndUpdate" Method
Set select: false in the schema for properties usually not wanted mongodb allows queries to specify which properties the database should send back in the response objects. Mongoose supports this with several things including explicit field lists as well as in the schemas the notion that each property can be selected by default or not. So for this use case the best thing to do is set your password field to deselected by default: var userSchema = new mongoose.Schema({ passwordHash: {type: String, select: false} ... }); Then you know it will never come back automatically. However, when you actually go to process a login request you do need it, in which case you explicitly request it: User.findOne({email: theEmail}, '+passwordHash', callback); For the annoying _id property, use sche

Categories : Javascript

Mongoose ignoring part of object unless defined as Schema.Types.Mixed
The type property of attr is likely tripping up Mongoose to thinking attr is a string instead of an embedded object. Use a more explicit definition for the property, like this: attr: appearance: String aroma: String flavor: String from: String grade: String lineage: String name: String overall: String packaging: String pickupdate: String price: String reason: String story: String type: type: String

Categories : Javascript

I want to remove warning: "Replace this with a lock against an object with strong-identity"
You can just declare a separate object to use for locking: private AxVIDEOPLAYERUILib.AxVideoPlayerUI axVideoPlayerUI; private object axVideoPlayerUILock = new object(); and: lock (axVideoPlayerUILock) { ... COM Proxies are implemented by System.__ComObject, which in turn derives from MarshalByRefObject. Perhaps the guidance could be clearer that types derived from those mentioned are also not usable.

Categories : C#

Why does FileSystemWatcher.Changed and StreamReader or FileStream lock the file even though I lock(...){...} it?
You are seriously confusing the idea of locking. Your lock statement in the Changed event handler is the kind of lock you'd use to prevent another thread from using a shared resource. We can't see such a resource being used in your snippet. A lock on a file is an entirely different kind of animal. The FileShare enumeration is relevant, it says what kind of access other code has to the file. Including code in another process, something that's never the case with the lock keyword. You are very permissive in your own code, using FileShare.ReadWrite. Which allows any other process to both read and write to the file. Which is something you have to fret about a bit, does your code still work properly when another process can write to the file while you are reading it? In other words, ca

Categories : Dotnet



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.