w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML Categories
How do I pass an ordinal position into the update document in Pymongo for an $inc update
You need to generate your key programmatically: In the shell: var num = 4; var inc = {}; inc['nested.' + num + '.c'] = 1; db.collection.update({_id: 'adsjfdsau7Hukad'}, {$inc: inc}) In pymongo: num = 4 db.collection.update( {'_id': 'adsjfdsau7Hukad'}, {'$inc': {'nested.' + str(num) + '.c': 1}})

Categories : Mongodb

Given a list of username, do an update on all of them at once using Pymongo
The precise answer depends on which version of MongoDB you are using (the syntax for update has changed), however the key is to set multi to true, which will update all documents that match the query. In this case, your query could be an array of usernames with which you would use the $in operator. Update Multiple Documents $in operator

Categories : Python

mongodb (pymongo) `update` didn't work
The query part of your update isn't matching any documents, so nothing is matched to be updated. As you know the _id then querying against just e["_id"] will ensure your query is targeted correctly. jp.update(e['_id'], {'$set':{'sensesJa':sensesJa,'last':'#pushFormsAndSetNewAtt'}, '$push':{'forms':{'$each':forms_to_push}}}) Update Querying by a whole document is fine and as long as there is a match it will update. Here is an example of querying and finding a document: from pymongo import * client = MongoClient() coll = client.test.test coll.save({'_id': 1, 'hello': 'world'}) e = coll.find_one() print(e) coll.find(e).count() The output is 1 because it matches one document. The only time that would fail is if I changed e or something (another process) removed

Categories : Python

Python - Pymongo Insert and Update Documents
Use upsert option: from pymongo import MongoClient cl = MongoClient() coll = cl["local"]["test2"] data = [{"_id" : 1, "foo" : "HELLO"}, {"_id" : 2, "Blah" : "Bloh"}] for d in data: coll.update({'_id':d['_id']}, d, True)

Categories : Python

Update a few fields in nested array in mongodb (with pymongo)
I can't be certain, but this might be what's going on. From your example document, your model has this schema: { id: Number, tweets: Array } When you search for the instance of the model in collection.update( { "id": 987654321, "tweets.id": 281061376275906560, "tweets.urls.url": "http://t.co/hbFt7t1n" }, ...)` It's likely that it's not finding the instance of the model you're looking for. I would try running this script to see if your search criteria are valid: console.log(collection.find({ "id": 987654321, "tweets.id": 281061376275906560, "tweets.urls.url": "http://t.co/hbFt7t1n" })); Hope it helps!

Categories : Python

update depending on item within document mongodb pymongo
hey just do something like this in pymongo from pymongo import MongoClient cursor_object = MongoClient()[your_db][your_collection] for object in cursor_object.find(): id = object['_id'] val1 = object['value1'] update = val1/2 cursor_object.update({"_id":id},{"$set":{"value2":update}})

Categories : Python

spring mvc update operation
The preferred way is to create a dto representing only the fields that should be accessible, you then send this to and from the form. public DishDto { public getName(){}; public setName(){}; private String name; } This strategy also allows you to mix two different entities/tables within one dto/form.

Categories : Jsp

Eloquent Conditional Update
You may try this $form = !FormDB::find('blah@blah.com') ? new FormDB : FormDB::find('blah@blah.com'); $form->email = !$form->email ? "blah@blah.com" : $form->email; $form->text = !$form->text ? "Inserted" : "Updated"; $form->save();

Categories : PHP

Conditional UPDATE in MySql
Unfortunately it's not very clear what you want to get in the end, but here is how you could correctly use conditional SET in your UPDATE UPDATE relation SET name1 = CASE WHEN userid1 = 3 THEN 'jack' ELSE name1 END, name2 = CASE WHEN userid2 = 3 THEN 'jack' ELSE name2 END WHERE (userid1 = 3 AND userid2 = 4) OR (userid1 = 4 AND userid2 = 3); Here is SQLFiddle demo.

Categories : Mysql

Ruby array update operation
After the first update, you replace the third element with another array. So your array looks like the following: [4, 5, ["a", "b", "c"]] That's why the length of resulting array is 3.

Categories : Ruby

WriteResult mongoDB for update operation
The n value in a WriteResult provides the number of documents that were updated, and it can only be 0 if your update query didn't match any documents and you're not doing an upsert. Your best bet here might be to use findAndModify and make a comparison to the old document.

Categories : Mongodb

AFJSONRequestOperation, update UI if operation is successful
The completion block of requestAccessToAccountsWithType is called on an arbitrary queue so you can't call a UI element (your postTextField) in it. You should wrap the code with dispatch_async call: - (void)postToTwitter { ACAccountType *accountType = [self.accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter]; [self.accountStore requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error) { dispatch_async(dispatch_get_main_queue(), ^{ if (granted == YES) { if ([self.twitterAccounts count] > 0) { ACAccount *twitterAccount = [self.twitterAccounts objectAtIndex:[AppController sharedAppController].currentUser.twitterAccount.accountId.integerValue];

Categories : IOS

Sql Server update with conditional join
I am not sure I fully understand what you are trying to accomplish, but perhaps the following would help: UPDATE employees SET employees.RefID = ed.RefID FROM #tmpEmployees employees JOIN EmployeeDirectory ed ON ed.ABC = employees.ABC OR ed.ABC IS NULL AND employees.ABC IS NULL OR ed.DEF = employees.DEF OR ed.DEF IS NULL AND employees.DEF IS NULL If the NULL value handling is not what you want (or the opposite of what you want), you can modify/invert it.

Categories : Sql Server

How to update a view without waiting for another operation to finish
The BackgroundWorker will deliver what you are after. Sample code: BackgroundWorker bg = new BackgroundWorker(); bg.DoWork += new DoWorkEventHandler(getExternalIPv4Back); bg.RunWorkerCompleted += new RunWorkerCompletedEventHandler(writeLabel); bg.RunWorkerAsync(); //The code below this point will be executed while the BackgroundWorker does its work You have to define getExternalIPv4Back as a DoWork Event Method and include inside it the code to be executed in parallel; also writeLabel as a RunWorkerCompleted Event(required to edit the label without provoking muti-threading-related errors). That is: private void getExternalIPv4Back(object sender, DoWorkEventArgs e) { IP = "External IPv4: " + getExternalIPv4(); //IP -> Globally defined variable } private void writeLabel(object se

Categories : C#

How to update a list after a database operation in AngularJS
To followup on the comment from @Duncan, here's a quote from the documentation: It is important to realize that invoking a $resource object method immediately returns an empty reference (object or array depending on isArray). Once the data is returned from the server the existing reference is populated with the actual data. This is a useful trick since usually the resource is assigned to a model which is then rendered by the view. Having an empty object results in no rendering, once the data arrives from the server then the object is populated with the data and the view automatically re-renders itself showing the new data. This means that in most case one never has to write a callback function for the action methods. The action methods on the class object or instance object can be

Categories : Angularjs

how to use temporary variables in conditional postgresql update?
The point is - you cannot use a variables for this, until you'll loop through the rows. Variables can hold scalar values, and you want to calculate tipoi and tempc for each row. I think in your case you could use precalculated columns, something like this. CREATE OR REPLACE FUNCTION updatecosto(v_centro smallint, v_desde date) RETURNS void AS $BODY$ declare tempc numeric; tipoi boolean; begin with cte1 as ( select * (select ivafronterizo from destinos where destinos.destino=fletes.origen)=2 and (select ivafronterizo from destinos where fletes.destino=destinos.destino)=2 as tipoi, from fletes where diaembarque>=v_desde and diaembarque<=coalesce((select desde - 1 from costof where desde>v_desde and centroemabrcador=v_centro o

Categories : Postgresql

How can I make a Django update with a conditional case?
If I understand correctly, you take the maximum time between now and the value in database. If that is so, you can do it in one line with the max function: from django.db.models import F MyData.objects.filter(pk=dataID).update(targetTime=max(F('targetTime'),timezone.now()) + timedelta(days=XX))

Categories : Django

prevent update operation globally in the application after evening 6.00 pm
You could override the method SaveChanges of your context and do the intervall check inside. See the following link public override int SaveChanges(SaveOptions options) { if(DateTime.Now.TimeOfDay.Hours < 6 || DateTime.Now.TimeOfDay.Hours >= 18) { { throw new Exception("Changes to database are not allowed"); } else { return base.SaveChanges(options); } }

Categories : Asp Net Mvc

Running async operation after location update in background
From what I know, in didUpdateToLocation method you can perform any thing, so try there will be no harm. I also suggest to check this question: Understanding background tracking of user's location in iOS Beside for the iOS7, luckily there will be significant improvement in the background and multi tasking, from Apple's developer portal: Keep the content of your app up-to-date by adopting the new multitasking APIs in iOS 7. The new services allow your app to update information and download content in the background without draining the battery unnecessarily. The updates can happen at opportunistic times and are intelligently scheduled according to usage, so your app can update content in the background just when your users need it. But it is under NDA now, so I suggest

Categories : IOS

SQL Conditional Insert or update statement depending on a pair of columns. Using unique index?
CREATE UNIQUE INDEX index_name ON funddata(priceDate, price); Then use INSERT... ON DUPLICATE KEY UPDATE But still,this break the first normal form.http://en.wikipedia.org/wiki/First_normal_form

Categories : Mysql

Why is Xamarin Studio saying "version control operation failed due to unmerged path error" when I try to update my solution?
Have you tried using the github desktop tool itself and selecting ok. It will tell you more and allow you to fix the changes. My guess is that you have conflicts in your code with the changes already stored on github. Are you the only one working on this project? If not it most likely means someone else has changed those pieces and pushed them. Again use the github application, it is free, to see what is going on. I do not use the built in github interface. I had initial issue with it and just went back to my favorite. Using the external tool also makes it easier to manage if using other dev environments.

Categories : IOS

how can a file upload / download operation be cancelled without terminating the thread that performs this operation?
I would expect a properly-designed file download method to be interruptible. So you need to interrupt the thread in which the download is being done, which should cancel the download (the method should throw an InterruptedException). Once you have caught the exception from the downloading thread, you can then decide what to do, for example wait for a new file download to be submitted (i.e. not exit).

Categories : Java

How can I change the background operation priority dynamically using Dispatch or Operation queues.
I'm afraid the only way to do that is to cancel running operation before starting new one. You cannot remove it from queue until it's done or canceled. As an improvement for your problem I would suggest to load things even user doesn't need them in background - so you can load them from cache after it's there. You can create 2 NSOperationQueue with 2 different priorities and download things in background whenever user is idle on LowPriorityQueue. For important operations you can have high priority queue - which you will cancel each time search term changes. On top of that you just need to cache results from both of those queues.

Categories : IOS

Lightswitch with WCF RIA Services datasource - Query operation [operation name] could not be found on the service
It turns out I was indeed doing something very wrong...the md_SKURevMngtRRPPhantom object that I was returning, was an object defined in the Lightswitch project's DataSource that I was adding a property to by creating a partial class of it in my DomainService project. Seems this was a bad idea. I changed the DomainService project to return a newly-defined class instead of a the md_SKURevMngtRRPPhantom class, and all worked fine.

Categories : Misc

Is moped's (Ruby mongodb driver) remove_all operation a background operation?
The code that performs this operation in Moped is definitely not asynchronous and it will block while the operation is being sent to MongoDB (and potentially, by default, while waiting for a response from the database). https://github.com/mongoid/moped/blob/master/lib/moped/query.rb#L290-L307 https://github.com/mongoid/moped/blob/master/lib/moped/node.rb#L466-L468 However, as Chris Heald has already alluded too, if you use a write concern of w=0 (the so called "fire-and-forget" mode) this tells Moped not to wait around for a response from the server. You won't receive confirmation that the remove_all completed successfully but you can effectively background the work to your MongoDB server through this method. Here's some more info on how MongoDB's write-concerns work for unacknowledged

Categories : Mongodb

How to update multiple rows / How to perform Operation on multiple records (C#, SQL Server)
You need to define an UPDATE SQL statement to do your update call that UPDATE from your C# code use parametrized query to avoid SQL injection and bad performance !! put your usage of SqlConnection and SqlCommand into using() {....} blocks to ensure proper disposal Something like this: // define your UPDATE query string updateQuery = "UPDATE dbo.Players SET Score = Score + @Value WHERE Team_id = @TeamID"; // two nested "using" blocks for conenction and command using (SqlConnection conn = new SqlConnection(.....)) using (SqlCommand cmd = new SqlCommand(updateQuery, con)) { // define the parameters and provide values cmd.Parameters.Add("@Value", SqlDbType.Int).Value = someValue; cmd.Parameters.Add("@TeamID", SqlDbType.Int).Value = teamID; // open connection, execute t

Categories : Sql Server

Meteor Security: should all database insert, update, remove operation be a Meteor.call() to the server?
For the first point, you can choose any of the two possibilities, but i prefer to use the second one : Client can do insert/update/delete Server has some security checks With this system you use the latency compensation of meteor. So it seems to be a good way of doing. For the second point, you can imagine to store in Session where you are on the list when you click on the detail. Then when you come back to the list, you check the session value and you just have to use it to restore the state.

Categories : Javascript

Make an AFNetworking operation complete before next code line after [operation start] and how to handle nested operations
This is not an AFNetworking related question, rather a general Objective-C or asynchronous question. You may try to reload the table view whenever the images of one model have been loaded: - (void)getAllModels{ NSURLRequest *request = ...; AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { for(NSDictionary *model in JSON){ Model *model = [Model alloc] initWithId:...; [model getPhotosWithCompletionBlock: ^(NSArray *results){ dispatch_async(dispatch_get_main_queue(), ^{ model.photos = results; [self.tableView reloadData]; }); }failureBlock:^(NSError *error) { N

Categories : Misc

Inversing number: what is the fastest operation? Using bitwise operation or Using if statement?
If you are programming in shell then surely speed is not your primary concern? Especially not micro-optimizations like this. In any case, the speed would greatly depend on the shell you choose to use, and the specific version of that shell. The tags suggest bash, but you don't actually say. The only advice I can give is to test it and see; write yourself a benchmark that does this a million times and then find out which runs quickest. Then, when you're done testing all that in bash, try dash. It's said the be faster, if perhaps less feature rich.

Categories : Linux

How to rollback hibernate operation when Exception occured after the operation?
All you need to do is annotate the method with @Transactional like this: public class EmployeeDAO extends AbstractHibernateDAO { @Transactional public void save(Employee emp) throws HibernateException { super.save(emp); // inside this method, it calls hibernate session.save(). This super.save method can throws HibernateException doSometingElse(emp); // inside this method, it doesn't call any hibernate methods. It can throws Exception too. } } That way if an exception is thrown in the EmployeeDAO save the whole method worth of hibernate operations will be rolled back. If you prefer for all the methods in this class to run in their own transaction, then annotate the class @Transactional instead. You'll also need to make sure you do have a transacti

Categories : Spring

How to Update contact image using contact provider operation.
Here is one way: public void writeDisplayPhoto(long rawContactId, byte[] photo) { Uri rawContactPhotoUri = Uri.withAppendedPath( ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), RawContacts.DisplayPhoto.CONTENT_DIRECTORY); try { AssetFileDescriptor fd = getContentResolver().openAssetFileDescriptor(rawContactPhotoUri, "rw"); OutputStream os = fd.createOutputStream(); os.write(photo); os.close(); fd.close(); } catch (IOException e) { // Handle error cases. } }

Categories : Android

Conditional updating of matrix elements based on conditional statement
for is not your friend in R, here's a solution using apply and conditional indexing ## create some toy data matrix( ncol=5, nrow = 100, c( runif(300), sample(c('A','G','C','T','a','c','g','t'), replace=T, 200))) -> data flip_allele_freqs <- function(x) { ## function will return 1-x on any x that looks like a number less than 1 n = as.numeric(x) if ( is.na(n) ) { ## cant convert to numeric, must be str return(x) } if (n < 1) { return( 1 - n ) } else { return x } } ## apply the flip alleles function to the rows where the two last columns are equal ##fold the new data back into the old matrix data[toupper(data[,5]) == toupper(data[,4]),] <- apply(data[toupper(data[,5]) == toupper(data[,4]),], c(1,2), flip_allele_freqs)

Categories : R

Is it possible to make conditional includes and conditional function calls?
You can have 2 activities (for a single activity extending 2 different classes) and can launch the activities conditionally. if (MODE == MODE.ANDROID) startActivity(A) else startActivity(B) But your launcher activity has to be one, that cannot be designed in this way. I was wondering why are you trying to do this ??

Categories : Java

Can conditional and combinatorial conditional relationships be designed in Neo4j?
This question really seems oriented toward your app domain logic, not about Neo4j itself. With Neo4j, it's entirely possible to dynamically add/remove nodes, add/remove relationships, etc. For function 1, you'd just need to add or remove the relationship between E1 and S1/S2 (via your app logic; there's no automatic conditional-relationship mechanism to rely upon). And for function 2, again you'd add or remove a relationship between E1/E2 and S1-S5 (or just leave E1 & E2 without any relationship). You'll be able to do any of the query+add or query+remove via Cypher (latest documentation is here).

Categories : Neo4j

Will Python skip over reading an 'else' conditional if the 'if' conditional was already run?
You cannot use a conditional after else, only after elif. elif is only checked if the preceding if or elif conditionals did not match. Demo: >>> foo = 'bar' >>> if foo == 'bar': ... print 'foo-ed the bar' ... foo = 'baz' ... elif foo == 'baz': ... print 'uhoh, bazzed the foo' ... foo-ed the bar Even though foo was set to baz in the first block, the elif condition did not match. Quoting from the if statement documentation: It selects exactly one of the suites by evaluating the expressions one by one until one is found to be true [...]; then that suite is executed (and no other part of the if statement is executed or evaluated). If all expressions are false, the suite of the else clause, if present, is executed. Emphasis mine. In fact, this extends

Categories : Python

Advantages of conditional-preprocessor over conditional statements
Conditional compilation means ifdef-ed out code is never actually in the final linked application. Just using language conditionals means both branches are in the final code making it bigger and potentially harder to test etc. Use #ifdef etc when you know at compile time what is required. Language conditionals are used when you don't know what you need until runtime.

Categories : C++

PyMongo statistics
Looks like it's a task for the mongodb aggregation framework: db.collection.aggregate([{$group: {_id: "$_country_code", count: {$sum: 1}}}]) will produce results like: { "result" : [ { "_id" : "US", "count" : 302000 }, { "_id" : "CA", "count" : 180000 }, ... ], "ok" : 1 } The same query using pymongo: db.command('aggregate', 'collection', pipeline=[{"$group": {"_id": "$_country_code", "count": {"$sum": 1}}}]) Hope that helps.

Categories : Python

PyMongo $inc having issues
$inc isn't a valid Python identifier. You should pass it as a string, like everything else: mongo_db.campaign.update({'_id': str(campaign_id)}, {'$inc': {'item': 1}}) The MongoDB docs you linked are the general MongoDB documentation, not PyMongo-specific; you can't copy/paste them literally and expect things to work.

Categories : Python

Pymongo and n-grams search
If you want an efficient system, you'll need to break down the n-grams ahead of time and index them. When I wrote the 5-Gram Experiment (unfortunately the backend is offline now as I had to give back the hardware), I've created a map of word => integer id, and then stored in MongoDB a hex id sequence in the document key field of a collection (for example, [10, 2] => "a:2"). Then, randomly distributing the ~350 million 5-grams to 10 machines running MongoDB offered sub-second query times for the whole data set. You can a similar scheme. With a document such as: {_id: "a:2", seen: [docId1, docId2, ...]} You'll be able to find where the given n-gram was found. Update: Actually, a small correction: in the system that went live I ended up using the same scheme, but encoding the n-gra

Categories : Python

Convert an SQL into pymongo query
Actually your query is not a valid SQL. You have to quote strings SELECT a, b, c, d from Table WHERE d='D' AND e='E' GROUP BY a And still this query will work only in MySQL. For AnsiSQL you should specify aggregates for you columns, like SELECT a, min(b) as b, max(c) as c from Table WHERE d='D' AND e='E' GROUP BY a then your mongodb query would be like db.<your collection>.aggregate([ {$match:{"d":"D", "e":"E"}}, {$group:{_id:"$g.a", b: { $min: "$g.b"}, c: {$max:"$g.c"}}} ]) if you want an array of a, b, c, d values, this should work: db.<your collection>.aggregate([ {$match:{"d": "D", "e": "E"}}, { $group: { _id: "$g.a", data: {$push: {"a": "$g.a", "b": "$g.b", "c": "$g.c", "d": "$d"}} } } ]) Just tested this co

Categories : Python



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