w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
MongooseJS modify document during pre hook
pre hooks work for both doc.save() and doc.update(). In both cases this refers to the document itself. Note that hooks need to be added to your schema before compiling your model. schema.pre('save', function(next) { if(typeof this.tags === 'string') { this.tags = this.tags.split(','); } }); var Location = mongoose.model('Location', schema);

Categories : Node Js

How to search emblemled documents in document mongoosejs?
First point, to search for a match within an array is identical to searching a plain string. Mongo is smart enough to see that the property is an array and search it's content. ... Dishes.find({steps: new RegExp(name, "i")}) ... will work as you would hope/expect. Second point, for comments, ingredients, categories, your schema is designed with separate collections interreferenced by ObjectId. Mongo cannot do joins like a relational database, so your query above will never match anything. Any given mongo operation is going to look in one and only one collection. You'll need to search each collection separately and then find the corresponding Dish records, or redesign your schema to use nested documents instead of references.

Categories : Node Js

error when trying to save geojson object using mongoosejs
I tried the following with the latest mongoose and it did work for me. Which version are you using? And as for the { type: {type: String } } question, I believe it is because type is also a mongoose keyword type: var zipSchema = new mongoose.Schema({ zc_code : String, zc_population : Number, zc_households : Number, zc_housevalue : Number, zc_householdincome : Number, zc_statecode : String, zc_state : String, zc_city : String, zc_cityname : String, modified_at : Date, center: { type: {type:String}, coordinates: [Number] } }) zipSchema.index({ center: '2dsphere' }); var zipInfo = { zc_code: '78746', zc_population: 26928, zc_households: 10839, zc_housevalue

Categories : Node Js

manipulate XML document with linq
var doc = XDocument.Load("Input.txt"); var tables = from t in doc.Root.Elements("Table") select new Table { RoleId = (int)t.Element("RoleId"), Code = (string)t.Element("Code"), Description = (string)t.Element("Description"), Task = (string)t.Element("Task"), TaskId = (int)t.Element("TaskId"), Country = (string)t.Element("Country"), CountryId = (int)t.Element("CountryId") }; var groups = tables.GroupBy(x => new { x.RoleId, x.Code, x.Description }); var resultDoc = new XDocument( new XElement("NewDataSet", from g in groups select new XElement("Table",

Categories : C#

Rails - Manipulate has_many with join model through single form
Is a join model necessary here? class Site < ActiveRecord::Base has_and_belongs_to_many :templates end In the form, easiest if using simple_form: <%= form.input :template_ids, :as => :radio_buttons, :collection => Template.order(:name), :label => 'Templates installed:' %> If the join model is necessary, then I would have a dropdown or list of templates I could add, each with a button that submits the form and adds that template. Then I'd use the update_only nested attributes form to display the currently installed templates with their settings. class Site < ActiveRecord::Base ... attr_accessor :install_template_id before_validation :check_for_newly_installed_template def check_for_newly_installed_template if install_template_id.present? templ

Categories : Ruby On Rails

Parse.com manipulate Response Object
In your cloud code before you make any response, create and object and extract from it the attributes/members you need and then response it. like so: //lets say result is some Parse.User or any other Parse.Object function(result) { var responseObj = {}; responseObj.name = responseObj.get("name"); responseObj.age = responseObj.get("age"); responseObj.id = responseObj.id; response.success(responseObj); } on the response side you will get {"result": {"name": "jhon", "age": "26", "id": "zxc123s21"}} Hope this would help you

Categories : Parse Com

How I can get parent document object From SVG document JavaScript?
There's a HTMLDocument interface and an SVGDocument interface, both derive from a base Document interface which provides some common methods. Cookies are part of the HTMLDocument interface and so only HTML documents get cookies. If you're talking about a situation where the <svg> is embedded in an html document via an <object>, <embed> or <iframe> tag then parent.document or top.document will get you the parent html document from a script in the SVG object provided that the SVG and HTML documents are on the same domain. This works for me on Firefox at least... <html> <body> <object id="object" data="embedded.svg" type="image/svg+xml" width="450" height="300"> </object> </body> </html> together with em

Categories : Javascript

How to let multiple threads manipulate one data object in Java
I'm afraid you don't specify the question precisely enough for it to be answered. Does it work if I just put the HashMap<...> words about the for (int....) statement? It almost does; that is, it will indeed create a new hash map (provided that "the words" are right). What it won't do is it won't make sure that has map is synchronized. As @Thilo says in the comment above, there are two easy ways to do so: ConcurrentHashMap provides you with an easy multithreading-ready map implementation Collections.synchronizedMap wraps a map of your choice making it ready for a multithreaded environment Pros and cons of the approaches (and way more) can be found at What's the difference between ConcurrentHashMap and Collections.synchronizedMap(Map)?

Categories : Java

Backbone on JSON nested structure: use single Model to manipulate whole structure
Creating Backbone model with any nested structure is as simple as : var Package = Backbone.Model.extend(); var package = new Package({ "@ID": "a1a2a3a4", "Name": "Package Name", "Category_ID": { "@Product_Line_ID": "11", "#text": "11" }, "Effective_Start_Date": "2013-08-09", "Available_Start_Date": "2013-08-09", "Product_Name": "Web National Promotion", "Product_To_Product": [] // might have nested objects }); package.get("Name"); // Package Name package.get("Category_ID").get("#text"); // TypeError: no get method found But, the only advantage you would get out of this is using Backbone.Model APIs and Events on the direct attributes (@ID, Name, Category_ID, etc and not @Product_Line_ID, #text) of you

Categories : Json

How to manipulate pixels of rendered screen or Display Object in Actionscript 3?
I'm pretty sure you'll need to render the screen to BitmapData at some point if you want to manipulate the pixels in that way. You could try using BitmapData.draw() to render the entire stage to BitmapData, but performance will most likely be miserable unless you're just using it on a fairly static screen (like a menu). Otherwise you're probably better off with a game engine that blits to a bitmap canvas instead of using the display list.

Categories : Actionscript

HQL - Only return single object for each object property sorted by how recently the object was updated
in HQL you can't use TOP, LIMIT, ROWNUM because are managed in different ways in owner DBMS. So if you want get only one element you must change your query, introducing a clause of NOT EXISTS based on some conditions allow you to choose the "last" element. In your case, fixed a play list your condtion is field "updated" Try this: select p from PlaylistDayStats p where not exists( select 'next' from PlayListDayStat p2 where p2.playList = p.playList and p2.updated > p.updated and p2.user = p.user ) and p.user = YOURVARIABLE If you have other conditions about discrimination of your records, add them in where clause of sub query

Categories : Hibernate

MongooseJS FindById ObjectId
from the documentation id <ObjectId, HexId> objectid, or a value that can be casted to one you can simply put string of id

Categories : Node Js

Mongoosejs can't query with findById
Seems that your _id field isn't an ObjectId. The method findById on Mongoose expects: id objectid, or a value that can be casted to one So, if your _id in fact isn't an ObjectId, you should query using findOne method account = Account.findOne { "_id" : req.params.account_id }

Categories : Mongodb

Using on() or once() for `open` event in MongooseJS
You are correct that it doesn't matter if you use (2) or (3) when your application is constantly connected to the database. As far as a persistent connection goes, the only cost of that is a tcp keepalive packet every once in a while. It's up to you to determine if the extra socket is worth not having to make a new connection for every call.

Categories : Database

RavenDB namespace change on document object throws "Unable to cast object" Error
Putting aside the rename and what might have worked before, the error matches the query you are attempting. You are indexing documents of type RewardProviderLog, and retrieving them directly as type ImportMonitorViewModel. You say all of the properties are the same in both classes, but that alone won't get RavenDB to duck-type them for you. You have to be a little more explicit. This will probably work: model = (from log in session.Query<RewardProviderLog>("ImportMonitorLogs") orderby log.lastRun descending select log).As<ViewModels.ImportMonitorViewModel>().ToList(); Or if you want slightly cleaner syntax (IMHO), this is equivalent: model = session.Query<RewardProviderLog>("ImportMonitorLogs") .OrderByDescending(x=> x.lastRun)

Categories : C#

Pass arguments in MFC-single-document
In a dialog dervived from CDialog or CDialogEx`, you would normally declare member variables which are connected to the controls in the dialog box -- see MSDN article Dialog Data Exchange. Once you call UpdateData(), the values from the connected controls are available in the dialog member variables. In your calling function, you would do something like CPropertyDlg dlg; dlg.m_origin_x = m_startPoint.x; dlg.m_origin_y = m_startPoint.y; dlg.m_width = coordinate.m_OldPoint.x-coordinate.m_startPoint.x; dlg.m_height = coordinate.m_OldPoint.y-coordinate.m_startPoint.y; if (dlg.DoModal == IDOK) { m_startPoint.x = dlg.m_origin_x; m_startPoint.y = dlg.m_origin_y; coordinate.m_OldPoint.x = m_startPoint.x + dlg.m_width; coordinate.m_OldPoint.y = m_startPoint.y + dlg.m_height; //

Categories : C++

How to store coordinates in MFC-single-document?
Declare m_Points member of CPropertyDlg as CList<CPoint,CPoint>* and pass pointer to this dialog: void CDrawToolView::OnEditProperty() { CPropertyDlg dlg; dlg.Points = &m_Points; if (dlg.DoModal() == IDOK) { //m_Points = dlg.Points; // not necessary because Points is changed in-place } } The problem in your existing code, that you are trying to pass CList by value, which requires copying the whole object. This is not allowed by MFC authors by making operator= private. BTW, if you are trying to implement drawing functionality, check out MFC sample DRAWCLI.

Categories : C++

Single qoute in MongoDB document
I had same problem before 2 days and i have solved it using below query. below is the solution for me. SELECT * FROM tags WHERE `name` = 'limit\''s' LIMIT 0 , 30 SEE HERE

Categories : PHP

How to get a document object from a file object in a Google-Apps Script
DocsList and DocumentApp have at least one method in common which is that they have access to the ID of documents so it is quite straightforward to pass this ID parameter from one method to the other. This code demonstrates : function myFunction() { var folder = DocsList.getFolder('yourfolder'); var contents = folder.getFilesByType(DocsList.FileType.DOCUMENT); var docObject = []; for(var c in contents){ docObject.push(DocumentApp.openById(contents[c].getId())); } Logger.log(docObject);// now you have an array of DocumentApp objects }

Categories : Google Apps Script

Getting "Error: Can't use $geoWithin with Array" from MongooseJS
Looks like $geoWithin wasn't implemented in the version of Mongoose that I'm using. My solution for the time being is to use the native mongodb library, until the stable build of Mongoose is updated with support for $geoWithin. var mongodb = require('mongodb'); mongodb.MongoClient.connect(app.get('mongodb connection string'), function(err, db) { if (err) throw err; db.collection('places') .find({location:{ $geoWithin:{ $box:[[Number(req.query.northEastLng), Number(req.query.northEastLat)], [Number(req.query.southWestLng), Number(req.query.southWestLat)]]}}}) .toArray(function(err, results) { if (!results) results = []; res.render('nearbyplaces', { results:

Categories : Node Js

Mongoosejs set/save vs. update for validation
The main downside to your approach is that you lose atomicity of your updates, because another update can occur in-between the time of your findOne call and the call to doc.save. You also lose the power of the various update operators like $addToSet that provide tested logic that you would otherwise have to implement in code.

Categories : Node Js

Writing each line from Textarea in a single document
So if you wanna have the lines split in your database, what would do, is something like this: class Book field :lines, type: Array def text=(t) doc = [] t.each_line { |l| dpc << l } self.lines = doc end end

Categories : Ruby On Rails

how can i delete a single field in a document in couch db?
First we have to get the document from database After that delete the required field using delete operator and then update the document like delete doc.tradeinfo; Here tradeinfo is the field that I want to delete in the document(doc)

Categories : Database

How can I use a document class in a single AS3 movie clip?
Now I understand your problem. First of all, I suggest to never write code on the timeline, except simple stuff like stop() or gotoAndPlay("loop"). The easiest way to achieve what you want is to do the following: Make a blank MovieClip in Flash IDE Ctrl + F8 Give it a linkage like this: Then click the edit button (marked with a red rectangle) Open in Flash Professional if asked Save the file in your .FLA directory and copy the contents of your Main.as file into this file Remove the package name ("com.pixeljunkyard") Change the public class Main extends Sprite to public class ConfettiContainer extends MovieClip and import flash.display.MovieClip Now you have a class ConfettiContainer which does the same stuff that you Main.as file did. Don't forget to copy anything that this Main.as

Categories : Actionscript

Textarea Linebreak in ExpressJS, MongooseJS and Jade
There are more ways. First way - is a change of content and replacing for a <br />: p !{escape(foo).replace(/ /g, '<br/>')} Second way - You can apply custom CSS, so you don't need to replace content and break <style> p { white-space: pre; } </style>

Categories : Node Js

Should MongooseJS be emitting events on replica set disconnection?
I've been having similar problems with Mongoose, asked on SO also. More recently, I've found this issue on Mongoose GitHub repository which led to this issue on the driver repository. The Mongo driver wasn't emitting any of these events more than once, and today this has been fixed for single connections on v1.3.19. It seems that it's a "won't fix" for now.

Categories : Node Js

Doing update on MongooseJS Schema Array that is using Populate
Just realized that the values I pre-populated should have been in the format that I am getting back since it is set as a "type:ObjectId" in the Schema. I believe I will have to repopulate to match the ObjectId structure

Categories : Node Js

MongooseJS Query select attributes of subdocument
You can use the $elemMatch projection operator to identity the matching b element to include: foo.find({a: A}, {b: {$elemMatch: {c: C}}}, function(err, doc) { // doc.b[0].d contains the value of d you're looking for. });

Categories : Mongodb

adding data in fields of a single document in mongodb
The value of the $push operator must refer to the array to be updated. So when the array field is embedded in other documents you need to use dot notation like this: db.abcd.update({_id: 1}, {$push: {"details.contacts.phones": {tag:"office", rname:"9823"}}});

Categories : Mongodb

Powershell: Merge lines with different data in a single CSV document
Try something like this: $csv = "$env:USERPROFILEDesktop$ip.csv" $expr = '/SolarWinds_SwitchPortMap/Interfaces/Interface' $XML | Select-Xml -XPath $expr | select -Expand Node | % { New-Object -Type PSCustomObject -Property @{ "Interface" = $_.Interface; "Description" = $_.Description; "Speed" = $_.ifSpeed; "MACAddress" = $_.MACs.MAC.MACAddress; "IPAddress" = $_.MACs.Mac.ip; "DNS" = $_.MACs.MAC.DNS; "VLAN" = $_.MACs.MAC.VLAN; } } | Export-Csv $csv -NoTypeInformation

Categories : Xml

Powershell - How can I save a single page from a word document?
One thing to keep in mind that a "page" is a relative term. Word is nothing more than a text editor, with cool formatting, so the file is basically one huge string set with things like /t for tabs and /n for new lines. So finding that specific page may pose some issues. As a point, if you were to open that same text document, in say, Notepad, you may not have the exact same number of words on that same page, or even the same content for that matter. Depending on the content of the file, you may be able to find start and end points, and pull out the needed section of content. You would read the file in line by line, looking for a particular identifier to, and pull that content out. Hope this helps.

Categories : Powershell

mongooseJS with TypeError: Cannot read property 'constructor' of undefined
MongoDB may ignore fields set to undefined, but Mongoose doesn't as it has a schema to work from and will try and cast values to the right types as defined in the schema. For a case like this you can build up your $pushAll value programmatically to only include the attributes you want: var value = {}; if (data[5] !== '') { value.attr1 = {val: data[5], dt: date}; } if (data[6] !== '') { value.attr2 = {val: data[6], dt: date}; } if (data[10] !== '') { value.attr3 = {val: data[10], dt: date}; } BioMetrics.update({AID: AID}, {$pushAll: value}, options, callback);

Categories : Mongodb

Get size of single pages in a multi-page pdf document in objective-c
There is no such information in iOS/OS X PDF related APIs. Due to the structure of PDF files computing the size a PDF page occupies on disk is quite complicated. Also because pages can share resources, the sum of separate page sizes will not equal the size of the final file.

Categories : Objective C

How to determine if I'm selecting multiple or a single element with document.querySelector
function (selector) { return document[selector[0] === '#' ? 'querySelector' : 'querySelectorAll'](selector) } Or you can do this: function (selector) { var result = document.querySelectorAll(selector); if(result.length === 1) return result[0]; return result; } EDIT jquery selectors always return array like object despite of item count in it, so what you are trying to do is different from jQuery behaviour

Categories : Javascript

where to code business logic in nodejs with expressjs, mongoosejs and redis
Here's a question that might help: Mongoose-based app architecture You should also look at the http://mean.io stack, as their templates will show you how to best structure your app, including where to store your logic.

Categories : Node Js

ElasticSearch Java API to query and return single column instead of the whole json document
You can specify the fields to be returned from a search, per documentation. This can be set via SearchRequestBuilder.addFields(String... fields), ie: SearchRequestBuilder srb = client.prepareSearch("heros") .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) .addFields("name");

Categories : Java

passing and escaping aposthrope or single quote in document.createTextNode in javascript
Erm... Why on earth are you doing that? var theText= "John's car"; var par= document.createElement('p'); par.style.textAlign='left'; par.appendChild(document.createTextNode(theText)); myDiv.appendChild(par);

Categories : Javascript

(3d object to json to webgl). Will I be able to manipulate skin of that 3d from webgl/javascript?
Yes, you will be able to manipulate the material. Take a look at: http://threejs.org/examples/#webgl_materials_cars As you can see, each car is a single object that also holds informations about which triangle that model is made of corresponds to which material that is exported. There are many different ways to control the apperiance of the object, but the answer remains the same - it is possible, it's up to you to decide how're you gonna do it. Hope this helps.

Categories : Javascript

Interface or type-hint for single object and multiple object class in php
Instead of reinventing the wheel you might want to try Doctrine or at least take a look at its architecture. I'm not sure if I get your exact issue... But if you want to go for your own code I would first abstract the DB layer as well and have some base classes like Database, Table, Row, Field that an describe the DB stack and extend them as needed with some magic methods. So when you do Student extends Table it would automatically check for a "students" table or whatever else convention you like to implement. Alternatively you could just pass the table name as arg. Whatever Object is returning the result set from the database would have to construct a single Row object for each row and add it to a collection of rows that I would name ResultSet and contains all the row objects and return

Categories : PHP

Using RestKit, is there a way I can run code when the object mapping on a single object completes?
Instead of implementing setters you can iterate through all objects after mapping operation completed: [RKObjectManager sharedManager] getObjectsAtPath:@"path/to/my/objects" parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) { NSArray *objects = mappingResult.array; for (id obj in objects) { if ([obj isKindOfClass:[Entity class]]) { Entity *entity = obj; if (entity.someProperty && entity.anotherProperty) { //do stuff } } } } failure:^(RKObjectRequestOperation *operation, NSError *error) { }];

Categories : IOS



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