It's probably easiest to create your query object directly as:
Test.find({
$and: [
{ $or: [{a: 1}, {b: 1}] },
{ $or: [{c: 1}, {d: 1}] }
]
}, function (err, results) {
...
}
But you can also use the Query#and
helper that's available in recent 3.x Mongoose releases:
Test.find()
.and([
{ $or: [{a: 1}, {b: 1}] },
{ $or: [{c: 1}, {d: 1}] }
])
.exec(function (err, results) {
...
});
MongoDB has a simple web based administrative port at 28017 by default.
There is no HTTP access at the default port of 27017 (which is what the error message is trying to suggest). The default port is used for native driver access, not HTTP traffic.
To access MongoDB, you'll need to use a driver like the MongoDB native driver for NodeJS. You won't "POST" to MongoDB directly (but you might create a RESTful API using express which uses the native drivers). Instead, you'll use a wrapper library that makes accessing MongoDB convenient. You might also consider using Mongoose (which uses the native driver) which adds an ORM-like model for MongoDB in NodeJS.
If you can't get to the web interface, it may be disabled. Normally, I wouldn't expect that you'd need it for doing development unless you're checking logs and such.
I have a situation where I have to create the model dynamically with each request and because of that I received this error, however, what I used to fix it is using deleteModel method like the following:
var contentType = 'Product'
var contentSchema = new mongoose.Schema(schema, virtuals);
var model = mongoose.model(contentType, contentSchema);
mongoose.deleteModel(contentType);
I hope this could help anybody.
Above solution works best if multiple matching sub documents are required. $elemMatch also comes in very use if single matching sub document is required as output
db.test.find({list: {$elemMatch: {a: 1}}}, {'list.$': 1})
Result:
{
"_id": ObjectId("..."),
"list": [{a: 1}]
}
in python the operators should be in quotes: db.ProductData.update({'fromAddress':'http://localhost:7000/'}, {"$set": {'fromAddress': 'http://localhost:5000/'}},{"multi": True})
Since MongoDB version 3.2 you can use updateMany():
> db.yourCollection.updateMany({}, {$set:{"someField": "someValue"}})
Update:
For mongodb versions 2.2+ more efficient way to do this described by @JohnnyHK in another answer.
1.Using $where
db.accommodations.find( { $where: "this.name.length > 1" } );
But...
Javascript executes more slowly than the native operators listed on this page, but is very flexible. See the server-side processing page for more information.
2.Create extra field NamesArrayLength
, update it with names array length and then use in queries:
db.accommodations.find({"NamesArrayLength": {$gt: 1} });
It will be better solution, and will work much faster (you can create index on it).
Recently migrated from mongodb to Postgres. This is how I used the scripts.
mongo < scripts.js > inserts.sql
Read the scripts.js
and output redirect to inserts.sql
.
scripts.js
looks like this
use myDb;
var string = "INSERT INTO table(a, b) VALUES";
db.getCollection('collectionName').find({}).forEach(function (object) {
string += "('" + String(object.description) + "','" + object.name + "'),";
});
print(string.substring(0, string.length - 1), ";");
inserts.sql
looks like this
INSERT INTO table(a, b) VALUES('abc', 'Alice'), ('def', 'Bob'), ('ghi', 'Claire');
The best way I found to make this to my purpose was to increment from the max value you have in the field and for that, I used the following syntax:
maxObj = db.CollectionName.aggregate([
{
$group : { _id: '$item', maxValue: { $max: '$fieldName' } }
}
];
fieldNextValue = maxObj.maxValue + 1;
$fieldName
is the name of your field, but without the $
sign.
CollectionName
is the name of your collection.
The reason I am not using count()
is that the produced value could meet an existing value.
The creation of an enforcing unique index could make it safer:
db.CollectionName.createIndex( { "fieldName": 1 }, { unique: true } )
The answer anhic gave can be very inefficient if you have a large database and the attribute name is present only in some of the documents.
To improve efficiency you can add a $match to the aggregation.
db.collection.aggregate(
{"$match": {"name" :{ "$ne" : null } } },
{"$group" : {"_id": "$name", "count": { "$sum": 1 } } },
{"$match": {"count" : {"$gt": 1} } },
{"$project": {"name" : "$_id", "_id" : 0} }
)
vim /etc/default/locale
add to it:
LC_ALL="en_US.UTF-8"
You can use Case Insensitive Indexes:
The following example creates a collection with no default collation, then adds an index on the name field with a case insensitive collation. International Components for Unicode
/*
* strength: CollationStrength.Secondary
* Secondary level of comparison. Collation performs comparisons up to secondary * differences, such as diacritics. That is, collation performs comparisons of
* base characters (primary differences) and diacritics (secondary differences). * Differences between base characters takes precedence over secondary
* differences.
*/
db.users.createIndex( { name: 1 }, collation: { locale: 'tr', strength: 2 } } )
To use the index, queries must specify the same collation.
db.users.insert( [ { name: "Oguz" },
{ name: "oguz" },
{ name: "OGUZ" } ] )
// does not use index, finds one result
db.users.find( { name: "oguz" } )
// uses the index, finds three results
db.users.find( { name: "oguz" } ).collation( { locale: 'tr', strength: 2 } )
// does not use the index, finds three results (different strength)
db.users.find( { name: "oguz" } ).collation( { locale: 'tr', strength: 1 } )
or you can create a collection with default collation:
db.createCollection("users", { collation: { locale: 'tr', strength: 2 } } )
db.users.createIndex( { name : 1 } ) // inherits the default collation
According to mongoDB documentation: "...That is, for MongoDB to use indexes to evaluate an $or expression, all the clauses in the $or expression must be supported by indexes."
So add indexes for your other fields and it will work. I had a similar problem and this solved it.
You can read more here: https://docs.mongodb.com/manual/reference/operator/query/or/
For dump, your DB fallow the below CMD
mongodump -d <your d name> -o <dump path>
Ex:mongodump -d qualetics -o D:\dbpackup\qualetics
If you would like to populate another level deeper, here's what you need to do:
Airlines.findById(id)
.populate({
path: 'flights',
populate:[
{
path: 'planeType',
model: 'Plane'
},
{
path: 'destination',
model: 'Location',
populate: { // deeper
path: 'state',
model: 'State',
populate: { // even deeper
path: 'region',
model: 'Region'
}
}
}]
})
You can use the javascript in the second link provided by Ravi Khakhkhar or you are going to have to perform some string manipulation to convert your orginal string (as some of the special characters in your original format aren't being recognised as valid delimeters) but once you do that, you can use "new"
training:PRIMARY> Date()
Fri Jun 08 2012 13:53:03 GMT+0100 (IST)
training:PRIMARY> new Date()
ISODate("2012-06-08T12:53:06.831Z")
training:PRIMARY> var start = new Date("21/May/2012:16:35:33 -0400") => doesn't work
training:PRIMARY> start
ISODate("0NaN-NaN-NaNTNaN:NaN:NaNZ")
training:PRIMARY> var start = new Date("21 May 2012:16:35:33 -0400") => doesn't work
training:PRIMARY> start
ISODate("0NaN-NaN-NaNTNaN:NaN:NaNZ")
training:PRIMARY> var start = new Date("21 May 2012 16:35:33 -0400") => works
training:PRIMARY> start
ISODate("2012-05-21T20:35:33Z")
Here's some links that you may find useful (regarding modification of the data within the mongo shell) -
http://cookbook.mongodb.org/patterns/date_range/
http://www.mongodb.org/display/DOCS/Dates
http://www.mongodb.org/display/DOCS/Overview+-+The+MongoDB+Interactive+Shell
Late reply, but adding that Mongoose also has the concept of Subdocuments
With this syntax, you should be able to reference your userSchema
as a type in your postSchema
like so:
var userSchema = new Schema({
twittername: String,
twitterID: Number,
displayName: String,
profilePic: String,
});
var postSchema = new Schema({
name: String,
postedBy: userSchema,
dateCreated: Date,
comments: [{body:"string", by: mongoose.Schema.Types.ObjectId}],
});
Note the updated postedBy
field with type userSchema
.
This will embed the user object within the post, saving an extra lookup required by using a reference. Sometimes this could be preferable, other times the ref/populate route might be the way to go. Depends on what your application is doing.
Found the problem, need to use function(err,obj)
instead:
Auth.findOne({nick: 'noname'}, function(err,obj) { console.log(obj); });
MongoDB's ISODate() is just a helper function that wraps a JavaScript date object and makes it easier to work with ISO date strings.
You can still use all of the same methods as working with a normal JS Date, such as:
ISODate("2012-07-14T01:00:00+01:00").toLocaleTimeString()
// Note that getHours() and getMinutes() do not include leading 0s for single digit #s
ISODate("2012-07-14T01:00:00+01:00").getHours()
ISODate("2012-07-14T01:00:00+01:00").getMinutes()
There are ways to do this without having to quit the CLI and pipe mongo
output to a non-tty.
To save the output from a query with result x
we can do the following to directly store the json output to /tmp/x.json
:
> EDITOR="cat > /tmp/x.json"
> x = db.MyCollection.find(...).toArray()
> edit x
>
Note that the output isn't strictly Json but rather the dialect that Mongo uses.
Please see the GridFS docs for details on storing such binary data.
Support for your specific language should be linked to at the bottom of the screen.
You can use $lookup
( multiple ) to get the records from multiple collections:
Example:
If you have more collections ( I have 3 collections for demo here, you can have more than 3 ). and I want to get the data from 3 collections in single object:
The collection are as:
db.doc1.find().pretty();
{
"_id" : ObjectId("5901a4c63541b7d5d3293766"),
"firstName" : "shubham",
"lastName" : "verma"
}
db.doc2.find().pretty();
{
"_id" : ObjectId("5901a5f83541b7d5d3293768"),
"userId" : ObjectId("5901a4c63541b7d5d3293766"),
"address" : "Gurgaon",
"mob" : "9876543211"
}
db.doc3.find().pretty();
{
"_id" : ObjectId("5901b0f6d318b072ceea44fb"),
"userId" : ObjectId("5901a4c63541b7d5d3293766"),
"fbURLs" : "http://www.facebook.com",
"twitterURLs" : "http://www.twitter.com"
}
Now your query will be as below:
db.doc1.aggregate([
{ $match: { _id: ObjectId("5901a4c63541b7d5d3293766") } },
{
$lookup:
{
from: "doc2",
localField: "_id",
foreignField: "userId",
as: "address"
}
},
{
$unwind: "$address"
},
{
$project: {
__v: 0,
"address.__v": 0,
"address._id": 0,
"address.userId": 0,
"address.mob": 0
}
},
{
$lookup:
{
from: "doc3",
localField: "_id",
foreignField: "userId",
as: "social"
}
},
{
$unwind: "$social"
},
{
$project: {
__v: 0,
"social.__v": 0,
"social._id": 0,
"social.userId": 0
}
}
]).pretty();
Then Your result will be:
{
"_id" : ObjectId("5901a4c63541b7d5d3293766"),
"firstName" : "shubham",
"lastName" : "verma",
"address" : {
"address" : "Gurgaon"
},
"social" : {
"fbURLs" : "http://www.facebook.com",
"twitterURLs" : "http://www.twitter.com"
}
}
If you want all records from each collections then you should remove below line from query:
{
$project: {
__v: 0,
"address.__v": 0,
"address._id": 0,
"address.userId": 0,
"address.mob": 0
}
}
{
$project: {
"social.__v": 0,
"social._id": 0,
"social.userId": 0
}
}
After removing above code you will get total record as:
{
"_id" : ObjectId("5901a4c63541b7d5d3293766"),
"firstName" : "shubham",
"lastName" : "verma",
"address" : {
"_id" : ObjectId("5901a5f83541b7d5d3293768"),
"userId" : ObjectId("5901a4c63541b7d5d3293766"),
"address" : "Gurgaon",
"mob" : "9876543211"
},
"social" : {
"_id" : ObjectId("5901b0f6d318b072ceea44fb"),
"userId" : ObjectId("5901a4c63541b7d5d3293766"),
"fbURLs" : "http://www.facebook.com",
"twitterURLs" : "http://www.twitter.com"
}
}
it happens when you pass an invalid id to mongoose. so first check it before proceeding, using mongoose isValid
function
import mongoose from "mongoose";
// add this inside your route
if( !mongoose.Types.ObjectId.isValid(id) ) return false;
Starting in MongoDB 3.4, you can use the $sortByCount
aggregation.
Groups incoming documents based on the value of a specified expression, then computes the count of documents in each distinct group.
https://docs.mongodb.com/manual/reference/operator/aggregation/sortByCount/
For example:
db.contest.aggregate([
{ $sortByCount: "$province" }
]);
I would abuse the connect function in mongo cli mongo doc. so that means you can start one or more connection. if you want to copy customer collection from test to test2 in same server. first you start mongo shell
use test
var db2 = connect('localhost:27017/test2')
do a normal find and copy the first 20 record to test2.
db.customer.find().limit(20).forEach(function(p) { db2.customer.insert(p); });
or filter by some criteria
db.customer.find({"active": 1}).forEach(function(p) { db2.customer.insert(p); });
just change the localhost to IP or hostname to connect to remote server. I use this to copy test data to a test database for testing.
How to design table like this in mongodb?
First, to clarify some naming conventions. MongoDB uses collections
instead of tables
.
I think there are no foreign keys!
Take the following model:
student
{
_id: ObjectId(...),
name: 'Jane',
courses: [
{ course: 'bio101', mark: 85 },
{ course: 'chem101', mark: 89 }
]
}
course
{
_id: 'bio101',
name: 'Biology 101',
description: 'Introduction to biology'
}
Clearly Jane's course list points to some specific courses. The database does not apply any constraints to the system (i.e.: foreign key constraints), so there are no "cascading deletes" or "cascading updates". However, the database does contain the correct information.
In addition, MongoDB has a DBRef standard that helps standardize the creation of these references. In fact, if you take a look at that link, it has a similar example.
How can I solve this task?
To be clear, MongoDB is not relational. There is no standard "normal form". You should model your database appropriate to the data you store and the queries you intend to run.
Clearly many people have answered upon your query of how to make mongoDb work, I'd answer the second part: Regarding an appropriate GUI for mongoDB
My suggestion is, go for MongoChef (now Studio 3T)
You can easily install and use it.
You might want want to refer to (from 03:10- to 08:50): https://www.youtube.com/watch?v=0ws3oIyqieY&index=2&list=PLS1QulWo1RIZtR6bncmSaH8fB81oRl6MP
For a step by step guide to the GUI tool.
import endOfDayfrom 'date-fns/endOfDay'
import startOfDay from 'date-fns/startOfDay'
MyModel.find({
createdAt: {
$gte: startOfDay(new Date()),
$lte: endOfDay(new Date())
}
})
const moment = require('moment')
const today = moment().startOf('day')
MyModel.find({
createdAt: {
$gte: today.toDate(),
$lte: moment(today).endOf('day').toDate()
}
})
Important: all moments are mutable!
tomorrow = today.add(1, 'days')
does not work since it also mutates today
. Calling moment(today)
solves that problem by implicitly cloning today
.
I encountered the same thing. In package.json, change mongodb line to "mongodb": "^2.2.33". You will need to npm uninstall mongodb; then npm install to install this version.
This resolved the issue for me. Seems to be a bug or docs need to be updated.
After frequent attempt finally I got to troubleshoot the problem...
Step 1: ps aux | grep mongo
Step 2: sudo rm /var/lib/mongodb/mongod.lock
Step 3: sudo mongod --repair
Step 4: mongo
Probably you have this:
const db = mongoose.connect('mongodb://localhost:27017/db');
// Do some stuff
db.disconnect();
but you can also have something like this:
mongoose.connect('mongodb://localhost:27017/db');
const model = mongoose.model('Model', ModelSchema);
model.find().then(doc => {
console.log(doc);
}
you cannot call db.disconnect()
but you can close the connection after you use it.
model.find().then(doc => {
console.log(doc);
}).then(() => {
mongoose.connection.close();
});
The best way is to store native JavaScript Date objects, which map onto BSON native Date objects.
> db.test.insert({date: ISODate()})
> db.test.insert({date: new Date()})
> db.test.find()
{ "_id" : ObjectId("..."), "date" : ISODate("2014-02-10T10:50:42.389Z") }
{ "_id" : ObjectId("..."), "date" : ISODate("2014-02-10T10:50:57.240Z") }
The native type supports a whole range of useful methods out of the box, which you can use in your map-reduce jobs, for example.
If you need to, you can easily convert Date
objects to and from Unix timestamps1), using the getTime()
method and Date(milliseconds)
constructor, respectively.
1) Strictly speaking, the Unix timestamp is measured in seconds. The JavaScript Date object measures in milliseconds since the Unix epoch.
Copy the contents of /var/lib/mongodb
to /data/db
. The files you should be looking for should have names like your_db_name.ns
and your_dbname.n
where n
is a number starting with 0. If you do not see such files under /var/lib/mongodb
, search for them on your filesystem.
Once copied over, use --dbpath=/data/db
when starting MongoDB via the mongod
command.
Put your query (e.g. db.someCollection.find().pretty()
) to a javascript file, let's say query.js
. Then run it in your operating system's shell using command:
mongo yourDb < query.js > outputFile
Query result will be in the file named 'outputFile'.
By default Mongo prints out first 20 documents IIRC. If you want more you can define new value to batch size in Mongo shell, e.g.
DBQuery.shellBatchSize = 100
.
Another interesing way is to use $redact, which is one of the new aggregation features of MongoDB 2.6. If you are using 2.6, you don't need an $unwind which might cause you performance problems if you have large arrays.
db.test.aggregate([
{ $match: {
shapes: { $elemMatch: {color: "red"} }
}},
{ $redact : {
$cond: {
if: { $or : [{ $eq: ["$color","red"] }, { $not : "$color" }]},
then: "$$DESCEND",
else: "$$PRUNE"
}
}}]);
$redact
"restricts the contents of the documents based on information stored in the documents themselves". So it will run only inside of the document. It basically scans your document top to the bottom, and checks if it matches with your if
condition which is in $cond
, if there is match it will either keep the content($$DESCEND
) or remove($$PRUNE
).
In the example above, first $match
returns the whole shapes
array, and $redact strips it down to the expected result.
Note that {$not:"$color"}
is necessary, because it will scan the top document as well, and if $redact
does not find a color
field on the top level this will return false
that might strip the whole document which we don't want.
mongo-db
is likely not a great choice for new developers.
On the other hand mongoose
as an ORM (Object Relational Mapping) can be a better choice for the new-bies.
Here's another solution using a single document for the current version and all old versions:
{
_id: ObjectId("..."),
data: [
{ vid: 1, content: "foo" },
{ vid: 2, content: "bar" }
]
}
data
contains all versions. The data
array is ordered, new versions will only get $push
ed to the end of the array. data.vid
is the version id, which is an incrementing number.
Get the most recent version:
find(
{ "_id":ObjectId("...") },
{ "data":{ $slice:-1 } }
)
Get a specific version by vid
:
find(
{ "_id":ObjectId("...") },
{ "data":{ $elemMatch:{ "vid":1 } } }
)
Return only specified fields:
find(
{ "_id":ObjectId("...") },
{ "data":{ $elemMatch:{ "vid":1 } }, "data.content":1 }
)
Insert new version: (and prevent concurrent insert/update)
update(
{
"_id":ObjectId("..."),
$and:[
{ "data.vid":{ $not:{ $gt:2 } } },
{ "data.vid":2 }
]
},
{ $push:{ "data":{ "vid":3, "content":"baz" } } }
)
2
is the vid
of the current most recent version and 3
is the new version getting inserted. Because you need the most recent version's vid
, it's easy to do get the next version's vid
: nextVID = oldVID + 1
.
The $and
condition will ensure, that 2
is the latest vid
.
This way there's no need for a unique index, but the application logic has to take care of incrementing the vid
on insert.
Remove a specific version:
update(
{ "_id":ObjectId("...") },
{ $pull:{ "data":{ "vid":2 } } }
)
That's it!
(remember the 16MB per document limit)
This is one of the most commonly asked question to obtain the paginated result and the total number of results simultaneously in single query. I can't explain how I felt when I finally achieved it LOL.
$result = $collection->aggregate(array(
array('$match' => $document),
array('$group' => array('_id' => '$book_id', 'date' => array('$max' => '$book_viewed'), 'views' => array('$sum' => 1))),
array('$sort' => $sort),
// get total, AND preserve the results
array('$group' => array('_id' => null, 'total' => array( '$sum' => 1 ), 'results' => array( '$push' => '$$ROOT' ) ),
// apply limit and offset
array('$project' => array( 'total' => 1, 'results' => array( '$slice' => array( '$results', $skip, $length ) ) ) )
))
Result will look something like this:
[
{
"_id": null,
"total": ...,
"results": [
{...},
{...},
{...},
]
}
]
https://github.com/reoxey/benchmark
benchmark
speed comparison of MySQL & MongoDB in GOLANG1.6 & PHP5
system used for benchmark: DELL cpu i5 4th gen 1.70Ghz * 4 ram 4GB GPU ram 2GB
Speed comparison of RDBMS vs NoSQL for INSERT, SELECT, UPDATE, DELETE executing different number of rows 10,100,1000,10000,100000,1000000
Language used to execute is: PHP5 & Google fastest language GO 1.6
________________________________________________
GOLANG with MySQL (engine = MyISAM)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
INSERT
------------------------------------------------
num of rows time taken
------------------------------------------------
10 1.195444ms
100 6.075053ms
1000 47.439699ms
10000 483.999809ms
100000 4.707089053s
1000000 49.067407174s
SELECT
------------------------------------------------
num of rows time taken
------------------------------------------------
1000000 872.709µs
SELECT & DISPLAY
------------------------------------------------
num of rows time taken
------------------------------------------------
1000000 20.717354746s
UPDATE
------------------------------------------------
num of rows time taken
------------------------------------------------
1000000 2.309209968s
100000 257.411502ms
10000 26.73954ms
1000 3.483926ms
100 915.17µs
10 650.166µs
DELETE
------------------------------------------------
num of rows time taken
------------------------------------------------
1000000 6.065949ms
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
________________________________________________
GOLANG with MongoDB
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
INSERT
------------------------------------------------
num of rows time taken
------------------------------------------------
10 2.067094ms
100 8.841597ms
1000 106.491732ms
10000 998.225023ms
100000 8.98172825s
1000000 1m 29.63203158s
SELECT
------------------------------------------------
num of rows time taken
------------------------------------------------
1000000 5.251337439s
FIND & DISPLAY (with index declared)
------------------------------------------------
num of rows time taken
------------------------------------------------
1000000 21.540603252s
UPDATE
------------------------------------------------
num of rows time taken
------------------------------------------------
1 1.330954ms
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
________________________________________________
PHP5 with MySQL (engine = MyISAM)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
INSERT
------------------------------------------------
num of rows time taken
------------------------------------------------
10 0.0040680000000001s
100 0.011595s
1000 0.049718s
10000 0.457164s
100000 4s
1000000 42s
SELECT
------------------------------------------------
num of rows time taken
------------------------------------------------
1000000 <1s
SELECT & DISPLAY
------------------------------------------------
num of rows time taken
------------------------------------------------
1000000 20s
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
________________________________________________
PHP5 with MongoDB
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
INSERT
------------------------------------------------
num of rows time taken
------------------------------------------------
10 0.065744s
100 0.190966s
1000 0.2163s
10000 1s
100000 8s
1000000 78s
FIND
------------------------------------------------
num of rows time taken
------------------------------------------------
1000000 <1s
FIND & DISPLAY
------------------------------------------------
num of rows time taken
------------------------------------------------
1000000 7s
UPDATE
------------------------------------------------
num of rows time taken
------------------------------------------------
1000000 9s
A slightly simpler syntax (in Robomongo at least) worked for me:
db.database.save({ Year : NumberInt(2015) });
You cannot straightly query mongodb collections by date components like day or month. But its possible by using the special $where javascript expression
db.mydatabase.mycollection.find({$where : function() { return this.date.getMonth() == 11} })
or simply
db.mydatabase.mycollection.find({$where : 'return this.date.getMonth() == 11'})
(But i prefer the first one)
Check out the below shell commands to get the parts of date
>date = ISODate("2011-09-25T10:12:34Z")
> date.getYear()
111
> date.getMonth()
8
> date.getdate()
25
EDIT:
Use $where only if you have no other choice. It comes with the performance problems. Please check out the below comments by @kamaradclimber and @dcrosta. I will let this post open so the other folks get the facts about it.
and check out the link $where Clauses and Functions in Queries for more info
With ES6 syntax
import mongoose from "mongoose";
// Generate a new new ObjectId
const newId2 = new mongoose.Types.ObjectId();
// Convert string to ObjectId
const newId = new mongoose.Types.ObjectId('56cb91bdc3464f14678934ca');
After several attempts this works for me on Windows 7 env.:
Initially directory to which you have copied all MongDB sources has such view:
bsondump.exe
mongo.exe
mongod.exe
mongod.pdb
mongodump.exe
mongoexport.exe
mongofiles.exe
mongoimport.exe
mongooplog.exe
mongoperf.exe
mongorestore.exe
mongos.exe
mongos.pdb
mongostat.exe
mongotop.exe
All you need is to add data directory and db directory nested( data/db ) Final view should look like this:
data
bsondump.exe
mongo.exe
mongod.exe
mongod.pdb
mongodump.exe
mongoexport.exe
mongofiles.exe
mongoimport.exe
mongooplog.exe
mongoperf.exe
mongorestore.exe
mongos.exe
mongos.pdb
mongostat.exe
mongotop.exe
Than simply type in directory where MongoDB sources and data/db dirs exist this command:
C:\my_mongo_dir\bin>mongod --dbpath .\data\db
Mongoose uses the mongodb-native driver, which uses the custom ObjectID type. You can compare ObjectIDs with the .equals()
method. With your example, results.userId.equals(AnotherMongoDocument._id)
. The ObjectID type also has a toString()
method, if you wish to store a stringified version of the ObjectID in JSON format, or a cookie.
If you use ObjectID = require("mongodb").ObjectID
(requires the mongodb-native library) you can check if results.userId
is a valid identifier with results.userId instanceof ObjectID
.
Etc.
Could always do:
db.foo.find().forEach(function(f){print(tojson(f, '', true));});
To get that compact view.
Also, I find it very useful to limit the fields returned by the find so:
db.foo.find({},{name:1}).forEach(function(f){print(tojson(f, '', true));});
which would return only the _id and name field from foo.
Since it is basically a javascript shell, you can also use toArray()
:
db.collection.find().toArray()
However, this will print all the documents of the collection unlike pretty()
that will allow you to iterate.
Refer: http://docs.mongodb.org/manual/reference/method/cursor.toArray/
Add the --fields
parameter as comma separated field names enclosed in double inverted quotes:
--fields "<FIELD 1>,<FIELD 2>..."
This is complete example:
mongoexport --host Cluster0-shard-0/shard1URL.mongodb.net:27017,shard2URL.mongodb.net:27017,shard3URL.mongodb.net:27017 --ssl --username <USERNAME> --password <PASSWORD> --authenticationDatabase admin --db <DB NAME> --collection <COLLECTION NAME> --type <OUTPUT FILE TYPE> --out <OUTPUT FILE NAME> --fields "<FIELD 1>,<FIELD 2>..."
I know this topic is old, but for future people who could wonder the same question, another incredibly inefficient solution could be to do:
PersonModel.find({$where : 'this.favouriteFoods.indexOf("sushi") != -1'});
This avoids all optimisations by MongoDB so do not use in production code.
Thanks @Mark, I keep forgetting this again and again. After installing MongoDB with Homebrew:
I've used MongoDB extensively (for the past 6 months), building a hierarchical data management system, and I can vouch for both the ease of setup (install it, run it, use it!) and the speed. As long as you think about indexes carefully, it can absolutely scream along, speed-wise.
I gather that Cassandra, due to its use with large-scale projects like Twitter, has better scaling functionality, although the MongoDB team is working on parity there. I should point out that I've not used Cassandra beyond the trial-run stage, so I can't speak for the detail.
The real swinger for me, when we were assessing NoSQL databases, was the querying - Cassandra is basically just a giant key/value store, and querying is a bit fiddly (at least compared to MongoDB), so for performance you'd have to duplicate quite a lot of data as a sort of manual index. MongoDB, on the other hand, uses a "query by example" model.
For example, say you've got a Collection (MongoDB parlance for the equivalent to a RDMS table) containing Users. MongoDB stores records as Documents, which are basically binary JSON objects. e.g:
{
FirstName: "John",
LastName: "Smith",
Email: "[email protected]",
Groups: ["Admin", "User", "SuperUser"]
}
If you wanted to find all of the users called Smith who have Admin rights, you'd just create a new document (at the admin console using Javascript, or in production using the language of your choice):
{
LastName: "Smith",
Groups: "Admin"
}
...and then run the query. That's it. There are added operators for comparisons, RegEx filtering etc, but it's all pretty simple, and the Wiki-based documentation is pretty good.
Distinct and the aggregation framework are not inter-operable.
Instead you just want:
db.zips.aggregate([
{$group:{_id:{city:'$city', state:'$state'}, numberOfzipcodes:{$sum:1}}},
{$sort:{numberOfzipcodes:-1}},
{$group:{_id:'$_id.state', city:{$first:'$_id.city'},
numberOfzipcode:{$first:'$numberOfzipcodes'}}}
]);
I was having the same problem.Turns out my Node.js was outdated. After upgrading it's working.
The only way to change the $type
of the data is to perform an update on the data where the data has the correct type.
In this case, it looks like you're trying to change the $type
from 1 (double) to 2 (string).
So simply load the document from the DB, perform the cast (new String(x)
) and then save the document again.
If you need to do this programmatically and entirely from the shell, you can use the find(...).forEach(function(x) {})
syntax.
In response to the second comment below. Change the field bad
from a number to a string in collection foo
.
db.foo.find( { 'bad' : { $type : 1 } } ).forEach( function (x) {
x.bad = new String(x.bad); // convert field to string
db.foo.save(x);
});
There is no way to do this in single query. You have to search the document in first query:
If document exists:
db.bar.update( {user_id : 123456 , "items.item_name" : "my_item_two" } ,
{$inc : {"items.$.price" : 1} } ,
false ,
true);
Else
db.bar.update( {user_id : 123456 } ,
{$addToSet : {"items" : {'item_name' : "my_item_two" , 'price' : 1 }} } ,
false ,
true);
No need to add condition {$ne : "my_item_two" }
.
Also in multithreaded enviourment you have to be careful that only one thread can execute the second (insert case, if document did not found) at a time, otherwise duplicate embed documents will be inserted.
I know, I am already late but let me add my simple and working answer here
const query = {} //your query here
const update = {} //your update in json here
const option = {new: true} //will return updated document
const user = await User.findOneAndUpdate(query , update, option)
This will give you one last document for a collection
db.collectionName.findOne({}, {sort:{$natural:-1}})
$natural:-1
means order opposite of the one that records are inserted in.
Edit: For all the downvoters, above is a Mongoose syntax,
mongo CLI syntax is: db.collectionName.find({}).sort({$natural:-1}).limit(1)
I just burned a solid 3 hours trying to solve the same problem. Specifically, I wanted to "replace" the entire document if it exists, or insert it otherwise. Here's the solution:
var contact = new Contact({
phone: request.phone,
status: request.status
});
// Convert the Model instance to a simple object using Model's 'toObject' function
// to prevent weirdness like infinite looping...
var upsertData = contact.toObject();
// Delete the _id property, otherwise Mongo will return a "Mod on _id not allowed" error
delete upsertData._id;
// Do the upsert, which works like this: If no Contact document exists with
// _id = contact.id, then create a new doc using upsertData.
// Otherwise, update the existing doc with upsertData
Contact.update({_id: contact.id}, upsertData, {upsert: true}, function(err{...});
I created an issue on the Mongoose project page requesting that info about this be added to the docs.
@jbochniak: Thanks, although at first read I thought I've already discovered all of this, it turned out that your example (esp. the version of the Mongo Docker image) helped me out!
That version (v3.4.2) and the v3.4 (currently corresponding to v3.4.3) still support 'MONGO_INITDB_ROOT' specified through those variables, as of v3.5 (at least tags '3' and 'latest') DON'T work as described in your answer and in the docs.
I quickly had a look at the code on GitHub, but saw similar usage of these variables and couldn't find the bug immediately, should do so before filing this as a bug...
This is an old question, but I stumbled onto this when looking for the answer so I wanted to give the update to the answer for reference.
The methods save
and update
are deprecated.
save(to_save, manipulate=True, check_keys=True, **kwargs)¶ Save a document in this collection.
DEPRECATED - Use insert_one() or replace_one() instead.
Changed in version 3.0: Removed the safe parameter. Pass w=0 for unacknowledged write operations.
update(spec, document, upsert=False, manipulate=False, multi=False, check_keys=True, **kwargs) Update a document(s) in this collection.
DEPRECATED - Use replace_one(), update_one(), or update_many() instead.
Changed in version 3.0: Removed the safe parameter. Pass w=0 for unacknowledged write operations.
in the OPs particular case, it's better to use replace_one
.
Check host file which like this
##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting. Do not change this entry.
##
127.0.0.1 localhost
255.255.255.255 broadcasthost
When executing a script in a remote server. Mongo will add its own logging output, which we might want to omit from our file.
--quiet
option will only disable connection related logs. Not all mongo logs. In such case we might need to filter out unneeded lines manually. A Windows based example:
mongo dbname --username userName --password password --host replicaset/ip:port --quiet printDataToCsv.js | findstr /v "NETWORK" > data.csv
This will pipe the script output and use findstr
to filter out any lines, which have NETWORK string in them. More information on findstr: https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/findstr
A Linux version of this would use grep
.
Delete the .lock file from the C:\mongodb\data\ path and then restart the mongodb service.
With MongoDb 3.4.4 and newer, you can leverage the use of $arrayToObject
operator and a $replaceRoot
pipeline to get the counts.
For example, suppose you have a collection of users with different roles and you would like to calculate the distinct counts of the roles. You would need to run the following aggregate pipeline:
db.users.aggregate([
{ "$group": {
"_id": { "$toLower": "$role" },
"count": { "$sum": 1 }
} },
{ "$group": {
"_id": null,
"counts": {
"$push": { "k": "$_id", "v": "$count" }
}
} },
{ "$replaceRoot": {
"newRoot": { "$arrayToObject": "$counts" }
} }
])
Example Output
{
"user" : 67,
"superuser" : 5,
"admin" : 4,
"moderator" : 12
}
We can use versionKey: false in Schema definition
'use strict';
const mongoose = require('mongoose');
export class Account extends mongoose.Schema {
constructor(manager) {
var trans = {
tran_date: Date,
particulars: String,
debit: Number,
credit: Number,
balance: Number
}
super({
account_number: Number,
account_name: String,
ifsc_code: String,
password: String,
currency: String,
balance: Number,
beneficiaries: Array,
transaction: [trans]
}, {
versionKey: false // set to false then it wont create in mongodb
});
this.pre('remove', function(next) {
manager
.getModel(BENEFICIARY_MODEL)
.remove({
_id: {
$in: this.beneficiaries
}
})
.exec();
next();
});
}
}
I was also faced the same issue with mongodb 2.6.
What solved my problem was I just run mongod --repair
command
and then start mongod.exe
It's worked for me
If your query consists only of the $where
operator, you can pass in just the JavaScript expression:
db.T.find("this.Grade1 > this.Grade2");
For greater performance, run an aggregate operation that has a $redact
pipeline to filter the documents which satisfy the given condition.
The $redact
pipeline incorporates the functionality of $project
and $match
to implement field level redaction where it will return all documents matching the condition using $$KEEP
and removes from the pipeline results those that don't match using the $$PRUNE
variable.
Running the following aggregate operation filter the documents more efficiently than using $where
for large collections as this uses a single pipeline and native MongoDB operators, rather than JavaScript evaluations with $where
, which can slow down the query:
db.T.aggregate([
{
"$redact": {
"$cond": [
{ "$gt": [ "$Grade1", "$Grade2" ] },
"$$KEEP",
"$$PRUNE"
]
}
}
])
which is a more simplified version of incorporating the two pipelines $project
and $match
:
db.T.aggregate([
{
"$project": {
"isGrade1Greater": { "$cmp": [ "$Grade1", "$Grade2" ] },
"Grade1": 1,
"Grade2": 1,
"OtherFields": 1,
...
}
},
{ "$match": { "isGrade1Greater": 1 } }
])
With MongoDB 3.4 and newer:
db.T.aggregate([
{
"$addFields": {
"isGrade1Greater": { "$cmp": [ "$Grade1", "$Grade2" ] }
}
},
{ "$match": { "isGrade1Greater": 1 } }
])
These lines did the trick for all other deprecation warnings too:
const db = await mongoose.createConnection(url, { useNewUrlParser: true });
mongoose.set('useCreateIndex', true);
mongoose.set('useFindAndModify', false);
this worked for me on an AWS instance, to at least clear the cached memory mongo was using. after this you can see how your settings have had effect.
ubuntu@hongse:~$ free -m
total used free shared buffers cached
Mem: 3952 3667 284 0 617 514
-/+ buffers/cache: 2535 1416
Swap: 0 0 0
ubuntu@hongse:~$ sudo su
root@hongse:/home/ubuntu# sync; echo 3 > /proc/sys/vm/drop_caches
root@hongse:/home/ubuntu# free -m
total used free shared buffers cached
Mem: 3952 2269 1682 0 1 42
-/+ buffers/cache: 2225 1726
Swap: 0 0 0
With recent builds of mongodb community edition, this is straightforward.
When you install via brew, it tells you what exactly to do. There is no need to create a new launch control file.
$ brew install mongodb
==> Downloading https://homebrew.bintray.com/bottles/mongodb-3.0.6.yosemite.bottle.tar.gz ### 100.0%
==> Pouring mongodb-3.0.6.yosemite.bottle.tar.gz
==> Caveats
To have launchd start mongodb at login:
ln -sfv /usr/local/opt/mongodb/*.plist ~/Library/LaunchAgents
Then to load mongodb now:
launchctl load ~/Library/LaunchAgents/homebrew.mxcl.mongodb.plist
Or, if you don't want/need launchctl, you can just run:
mongod --config /usr/local/etc/mongod.conf
==> Summary
/usr/local/Cellar/mongodb/3.0.6: 17 files, 159M
This code will be helpful for you
Model.update({
'type': "newuser"
}, {
$set: {
email: "[email protected]",
phoneNumber:"0123456789"
}
}, {
multi: true
},
function(err, result) {
console.log(result);
console.log(err);
})
In this situation, log in to Mongo find the index that you are not using anymore (in OP's case 'email'). Then select Drop Index
Use data URL scheme: https://en.wikipedia.org/wiki/Data_URI_scheme
In this case you use that string directly in html : <img src="data:image/png;base64,iVBOR....">
You need to start mongod
with the --auth
option after setting up the user.
From the MongoDB Site:
Run the database (mongod process) with the
--auth
option to enable security. You must either have added a user to the admin db before starting the server with--auth
, or add the first user from the localhost interface.
In my case mongodb
packages are named mongodb-org
and mongodb-org-*
So when I type sudo apt purge mongo
then tab
(for auto-completion) I can see all installed packages that start with mongo
.
Another option is to run the following command (which will list all packages that contain mongo
in their names or their descriptions):
dpkg -l | grep mongo
In summary, I would do (to purge all packages that start with mongo
):
sudo apt purge mongo*
and then (to make sure that no mongo packages are left):
dpkg -l | grep mongo
Of course, as mentioned by @alicanozkara, you will need to manually remove some directories like /var/log/mongodb
and /var/lib/mongodb
Running the following find
commands:
sudo find /etc/ -name "*mongo*"
and sudo find /var/ -name "*mongo*"
may also show some files that you may want to remove, like:
/etc/systemd/system/mongodb.service
/etc/apt/sources.list.d/mongodb-org-3.2.list
and:
/var/lib/apt/lists/repo.mongodb.*
You may also want to remove user and group mongodb
, to do so you need to run:
sudo userdel -r mongodb
sudo groupdel mongodb
To check whether mongodb
user/group exists or not, try:
cut -d: -f1 /etc/passwd | grep mongo
cut -d: -f1 /etc/group | grep mongo
If you are getting these type of errors when running mongod from command line or running mongodb server,
then follow these steps,
db.messages.find( { headers : { From: "[email protected]" } } )
This queries for documents where headers
equals { From: ... }
, i.e. contains no other fields.
db.messages.find( { 'headers.From': "[email protected]" } )
This only looks at the headers.From
field, not affected by other fields contained in, or missing from, headers
.
findById
is a convenience method on the model that's provided by Mongoose to find a document by its _id. The documentation for it can be found here.
Example:
// Search by ObjectId
var id = "56e6dd2eb4494ed008d595bd";
UserModel.findById(id, function (err, user) { ... } );
Functionally, it's the same as calling:
UserModel.findOne({_id: id}, function (err, user) { ... });
Note that Mongoose will cast the provided id
value to the type of _id
as defined in the schema (defaulting to ObjectId).
You can also achieve this through aggregate pipeline.
db.collection.aggregate([{$sort:{age:-1}}, {$limit:1}])
By default mongodb has no enabled access control, so there is no default user or password.
To enable access control, use either the command line option --auth
or security.authorization configuration file setting.
You can use the following procedure or refer to Enabling Auth in the MongoDB docs.
Start MongoDB without access control.
mongod --port 27017 --dbpath /data/db1
Connect to the instance.
mongo --port 27017
Create the user administrator.
use admin
db.createUser(
{
user: "myUserAdmin",
pwd: "abc123",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
Re-start the MongoDB instance with access control.
mongod --auth --port 27017 --dbpath /data/db1
Authenticate as the user administrator.
mongo --port 27017 -u "myUserAdmin" -p "abc123" \
--authenticationDatabase "admin"
I faced the same problem,but after hours of efforts i find the solution.It can be without using any external plugin:)
applicantListToExport: function (query, callback) {
this
.find(query).select({'advtId': 0})
.populate({
path: 'influId',
model: 'influencer',
select: { '_id': 1,'user':1},
populate: {
path: 'userid',
model: 'User'
}
})
.populate('campaignId',{'campaignTitle':1})
.exec(callback);
}
For those that could be facing the same problem and the solutions suggested above aren't working, for example in my case, I had installed mongodb-community, so you might wanna run the command below to restart your mongo server.
For those that installed mongodb-community using brew
brew services start mongodb-community
This worked for me, just try this:
const id = req.params.id;
YourSchema
.remove({_id: id})
.exec()
.then(result => {
res.status(200).json({
message: 'deleted',
request: {
type: 'POST',
url: 'http://localhost:3000/yourroutes/'
}
})
})
.catch(err => {
res.status(500).json({
error: err
})
});
"userAdmin is effectively the superuser role for a specific database. Users with userAdmin can grant themselves all privileges. However, userAdmin does not explicitly authorize a user for any privileges beyond user administration." from the link you posted
While connected to a wifi network, mongodb://localhost/db_name
worked as expected.
When I wasn't connected to any wifi network, this couldn't work. Instead I used,
mongodb://127.0.0.1/db_name
and it worked.
Probably a problem to do with ip configurations.
I know it is old, but wanna add my 5 cents.
I used .service
and .service.impl
in a folder structure to separate the service with it's implementation. Forget to implement the ServiceImplementation piece.
The best solution is to extract properties from object and make them flat dot-notation key-value pairs. You could use for example this library:
https://www.npmjs.com/package/mongo-dot-notation
It has .flatten
function that allows you to change object into flat set of properties that could be then given to $set modifier, without worries that any property of your existing DB object will be deleted/overwritten without need.
Taken from mongo-dot-notation
docs:
var person = {
firstName: 'John',
lastName: 'Doe',
address: {
city: 'NY',
street: 'Eighth Avenu',
number: 123
}
};
var instructions = dot.flatten(person)
console.log(instructions);
/*
{
$set: {
'firstName': 'John',
'lastName': 'Doe',
'address.city': 'NY',
'address.street': 'Eighth Avenu',
'address.number': 123
}
}
*/
And then it forms perfect selector - it will update ONLY given properties. EDIT: I like to be archeologist some times ;)
Sort by _id
descending:
collection.find(filter={"keyword": keyword}, sort=[( "_id", -1 )])
Sort by _id
ascending:
collection.find(filter={"keyword": keyword}, sort=[( "_id", 1 )])
Here how to do this on mongodb 3.0. I used this nice blog
$ mkdir RANDOM_PATH/node1 $ mkdir RANDOM_PATH/node2> $ mkdir RANDOM_PATH/node3
$ mongod --replSet test --port 27021 --dbpath node1 $ mongod --replSet test --port 27022 --dbpath node2 $ mongod --replSet test --port 27023 --dbpath node3
$ mongo config = {_id: 'test', members: [ {_id: 0, host: 'localhost:27021'}, {_id: 1, host: 'localhost:27022'}]}; rs.initiate(config);
a. Download and unzip the [latest Elasticsearch][2] distribution b. Run bin/elasticsearch to start the es server. c. Run curl -XGET http://localhost:9200/ to confirm it is working.
$ bin/plugin --install com.github.richardwilly98.elasticsearch/elasticsearch-river-mongodb
$ bin/plugin --install elasticsearch/elasticsearch-mapper-attachments
curl -XPUT 'http://localhost:8080/_river/mongodb/_meta' -d '{ "type": "mongodb", "mongodb": { "db": "mydb", "collection": "foo" }, "index": { "name": "name", "type": "random" } }'
Test on browser:
For quickly checking if mongodb is running, this quick nc trick will let you know.
nc -zvv localhost 27017
The above command assumes that you are running it on the default port on localhost.
For auto-starting it, you might want to look at this thread.
Using Mongoose this worked for me:
var find = function(username, next){
User.find({'username': {$regex: new RegExp('^' + username, 'i')}}, function(err, res){
if(err) throw err;
next(null, res);
});
}
try below:
var temp_datetime_obj = new Date();
collection.find({
start_date:{
$gte: new Date(temp_datetime_obj.toISOString())
}
}).toArray(function(err, items) {
/* you can console.log here */
});
Backup/Restore Mongodb with timing.
Backup:
sudo mongodump --db db_name --out /path_of_your_backup/`date +"%m-%d-%y"`
--db
argument for databse name
--out
argument for path of output
Restore:
sudo mongorestore --db db_name --drop /path_of_your_backup/01-01-19/db_name/
--drop
argument for drop databse before restore
Timing:
You can use crontab for timing backup:
sudo crontab -e
It opens with editor(e.g. nano)
3 3 * * * mongodump --out /path_of_your_backup/`date +"%m-%d-%y"`
backup every day at 03:03 AM
Depending on your MongoDB database sizes you may soon run out of disk space with too many backups. That's why it's also recommended to clean the old backups regularly or to compress them. For example, to delete all the backups older than 7 days you can use the following bash command:
3 1 * * * find /path_of_your_backup/ -mtime +7 -exec rm -rf {} \;
delete all the backups older than 7 days
Good Luck.
I know this answer is coming really late on in this thread but I hope you check it out.
The reason you get that error is based on the specific role that you granted to the user, which you have gathered by now, and yes giving that user the role root
will solve your problem but you must first understand what these roles do exactly before granting them to users.
In tutorial you granted the user the userAdminAnyDatabase
role which basically give the user the ability to manage users of all your databases.
What you were trying to do with your user was outside its role definition.
The root
role has this role included in it definition as well as the readWriteAnyDatabase
, dbAdminAnyDatabase
and other roles making it a superuser (basically because you can do anything with it).
You can check out the role definitions to see which roles you will need to give you users to complete certain tasks. https://docs.mongodb.com/manual/reference/built-in-roles/ Its not advisable to make all your users super ones :)
If it is exactly null
(as opposed to not set):
db.states.find({"cities.name": null})
(but as javierfp points out, it also matches documents that have no cities array at all, I'm assuming that they do).
If it's the case that the property is not set:
db.states.find({"cities.name": {"$exists": false}})
I've tested the above with a collection created with these two inserts:
db.states.insert({"cities": [{name: "New York"}, {name: null}]})
db.states.insert({"cities": [{name: "Austin"}, {color: "blue"}]})
The first query finds the first state, the second query finds the second. If you want to find them both with one query you can make an $or
query:
db.states.find({"$or": [
{"cities.name": null},
{"cities.name": {"$exists": false}}
]})
In mongodb _id field is reserved for primary key. Mongodb use an internal ObjectId value if you don't define it in your object and also create an index to ensure performance.
But you can put your own unique value for _id and Mongodb will use it instead of making one for you. And even if you want to use multiple field as primary key you can use an object:
{ _id : { a : 1, b: 1} }
Just be careful when creating these ids that the order of keys (a and b in the example) matters, if you swap them around, it is considered a different object.
Do not remove your db if you already have some data you found useful. Just run the command below and you're good.
sudo systemctl restart mongodb.service
This will do:
db.getCollectionNames().forEach(c => {
db[c].find().forEach(d => {
print(c);
printjson(d)
})
})
Nested Depth for BSON Documents: MongoDB supports no more than 100 levels of nesting for BSON documents.
Why not use the html5 date control as it is, with other attributes that allows it work ok on browsers that support date type and still works on other browsers like firefox that is yet to support date type
<input type="date" name="input1" placeholder="YYYY-MM-DD" required pattern="[0-9]{4}-[0-9]{2}-[0-9]{2}" title="Enter a date in this formart YYYY-MM-DD"/>
What's wrong with your code? Wrapped in a neat utility method it's fine.
What's more important is what to use as separator — the first or last dot. The first is bad for file names like "setup-2.5.1.exe", the last is bad for file names with multiple extensions like "mybundle.tar.gz".
Here's a great method I recently found on a different stack overflow post regarding multi-dimensional arrays, but the answer works beautifully for single dimensional arrays as well:
# Create an 8 x 5 matrix of 0's:
w, h = 8, 5;
MyMatrix = [ [0 for x in range( w )] for y in range( h ) ]
# Create an array of objects:
MyList = [ {} for x in range( n ) ]
I love this because you can specify the contents and size dynamically, in one line!
One more for the road:
# Dynamic content initialization:
MyFunkyArray = [ x * a + b for x in range ( n ) ]
In addition to @BradB Answer :
That is so true... It's strange that it is the only answer who mention that. When beginners discover enums, they quickly take that as a magic-trick for valid identifier checking for the compiler. And when the code is intended to be use on distributed systems, they cry... some month later. Maintain backward compatibility with enums that contains non static list of values is a real concern, and pain. This is because when you add a value to an existing enum, its type change (despite the name does not).
"Ho, wait, it may look like the same type, right? After all, they’re enums with the same name – and aren’t enums just integers under the hood?" And for these reasons, your compiler will likely not flag the use of one definition of the type itself where it was expecting the other. But in fact, they are (in most important ways) different types. Most importantly, they have different data domains – values that are acceptable given the type. By adding a value, we’ve effectively changed the type of the enum and therefore break backward compatibility.
In conclusion : Use it when you want, but, please, check that the data domain used is a finite, already known, fixed set.
you can use delete operator to delete property by it's name
delete objectExpression.property
or iterate through the object and find the value you need and delete it:
for(prop in Obj){
if(Obj.hasOwnProperty(prop)){
if(Obj[prop] === 'myValue'){
delete Obj[prop];
}
}
}
Try getting hold of a URL for your classpath resource:
URL url = this.getClass().getResource("/com/path/to/file.txt")
Then create a file using the constructor that accepts a URI:
File file = new File(url.toURI());
Working example. Notes below.
class Animal {
constructor(public name) {
}
move(meters) {
alert(this.name + " moved " + meters + "m.");
}
}
class Snake extends Animal {
move() {
alert(this.name + " is Slithering...");
super.move(5);
}
}
class Horse extends Animal {
move() {
alert(this.name + " is Galloping...");
super.move(45);
}
}
var sam = new Snake("Sammy the Python");
var tom: Animal = new Horse("Tommy the Palomino");
sam.move();
tom.move(34);
You don't need to manually assign the name to a public variable. Using public name
in the constructor definition does this for you.
You don't need to call super(name)
from the specialised classes.
Using this.name
works.
Notes on use of super
.
This is covered in more detail in section 4.9.2 of the language specification.
The behaviour of the classes inheriting from Animal
is not dissimilar to the behaviour in other languages. You need to specify the super
keyword in order to avoid confusion between a specialised function and the base class function. For example, if you called move()
or this.move()
you would be dealing with the specialised Snake
or Horse
function, so using super.move()
explicitly calls the base class function.
There is no confusion of properties, as they are the properties of the instance. There is no difference between super.name
and this.name
- there is simply this.name
. Otherwise you could create a Horse that had different names depending on whether you were in the specialized class or the base class.
Convert Numpy to PIL
image and PIL to Numpy
import numpy as np
from PIL import Image
def pilToNumpy(img):
return np.array(img)
def NumpyToPil(img):
return Image.fromarray(img)
Use any()
.
if any(t < 0 for t in x):
# do something
Here is a slightly improved version of sonjz's answer,it adds an overwrite option.
function Zip-Files(
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$false)]
[string] $zipfilename,
[Parameter(Position=1, Mandatory=$true, ValueFromPipeline=$false)]
[string] $sourcedir,
[Parameter(Position=2, Mandatory=$false, ValueFromPipeline=$false)]
[bool] $overwrite)
{
Add-Type -Assembly System.IO.Compression.FileSystem
$compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
if ($overwrite -eq $true )
{
if (Test-Path $zipfilename)
{
Remove-Item $zipfilename
}
}
[System.IO.Compression.ZipFile]::CreateFromDirectory($sourcedir, $zipfilename, $compressionLevel, $false)
}
Daniel is right: http://ideone.com/kgbo1C#view_edit_box
Change
test=substring(i,j,*s);
to
test=substring(i,j,s);
Also, you need to forward declare substring:
char *substring(int i,int j,char *ch);
int main // ...
You do this via attributes on the properties, like this:
[Description("Test text displayed in the textbox"),Category("Data")]
public string Text {
get => myInnerTextBox.Text;
set => myInnerTextBox.Text = value;
}
The category is the heading under which the property will appear in the Visual Studio Properties box. Here's a more complete MSDN reference, including a list of categories.
Depends, where you want to have the vertical line, but if you want a vertical border for example, you can have the parent view have a background a custom drawable. And you can then define the drawable like this:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape
android:shape="rectangle">
<stroke android:width="1dp" android:color="#000000" />
<solid android:color="#00ffffff" />
</shape>
</item>
<item android:right="1dp">
<shape android:shape="rectangle">
<solid android:color="#00ffffff" />
</shape>
</item>
</layer-list>
This example will create a 1dp thin black line on the right side of the view, that will have this drawable as an background.
Maybe you can try this:
void foo(const char* str)
{
// Do something
}
foo("Hello")
It works for me
you can chain more than 2 conditions too :
if [ \( "$1" = '--usage' \) -o \( "$1" = '' \) -o \( "$1" = '--help' \) ]
then
printf "\033[2J";printf "\033[0;0H"
cat << EOF_PRINT_USAGE
$0 - Purpose: upsert qto http json data to postgres db
USAGE EXAMPLE:
$0 -a foo -a bar
EOF_PRINT_USAGE
exit 1
fi
With Git 2.23 onwards, one can use git switch <branch name>
to switch branches.
Use os.environ[str(DEBUSSY)]
for both reading and writing (http://docs.python.org/library/os.html#os.environ).
As for reading, you have to parse the number from the string yourself of course.
Anti-aliasing cannot be turned on or off, and is controlled by the browser.
I would suggest TARGET_FILE_DIR
if you want the file to be copied to the same folder as your .exe file.
$ Directory of main file (.exe, .so.1.2, .a).
add_custom_command(
TARGET ${PROJECT_NAME} POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy
${CMAKE_CURRENT_SOURCE_DIR}/input.txt
$<TARGET_FILE_DIR:${PROJECT_NAME}>)
In VS, this cmake script will copy input.txt to the same file as your final exe, no matter it's debug or release.
#import <Foundation/Foundation.h>
// clang -framework Foundation Siegfried.m
int
main() {
NSArray *arr = @[
@{@"1" : @"Fafner"},
@{@"1" : @"Fasolt"}
];
NSPredicate *p = [NSPredicate predicateWithFormat:
@"SELF['1'] CONTAINS 'e'"];
NSArray *res = [arr filteredArrayUsingPredicate:p];
NSLog(@"Siegfried %@", res);
return 0;
}
str_replace('"', "", $string);
str_replace("'", "", $string);
I assume you mean quotation marks?
Otherwise, go for some regex, this will work for html quotes for example:
preg_replace("/<!--.*?-->/", "", $string);
C-style quotes:
preg_replace("/\/\/.*?\n/", "\n", $string);
CSS-style quotes:
preg_replace("/\/*.*?\*\//", "", $string);
bash-style quotes:
preg-replace("/#.*?\n/", "\n", $string);
Etc etc...
This will ensure you get a two-digit day and month.
function formattedDate(d = new Date) {
let month = String(d.getMonth() + 1);
let day = String(d.getDate());
const year = String(d.getFullYear());
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
return `${day}/${month}/${year}`;
}
Or terser:
function formattedDate(d = new Date) {
return [d.getDate(), d.getMonth()+1, d.getFullYear()]
.map(n => n < 10 ? `0${n}` : `${n}`).join('/');
}
find()
takes a selector, not a value. This means you need to use it in the same way you would use the regular jQuery function ($('selector')
).
Therefore you need to do something like this:
$(this).find('[value="X"]').remove();
See the jQuery find docs.
CSS does not have this ability. You would need to use client-side scripting.
Here is the simplest way I found,
num <- c(5665,1615,5154,65564,69895646)
num <- sort(num, decreasing = F)
tail(num, 1) # Highest number
head(tail(num, 2),1) # Second Highest number
head(tail(num, 3),1) # Third Highest number
head(tail(num, n),1) # Generl equation for finding nth Highest number
I found this also works...
var select = document.getElementById("selectNumber");
var options = ["1", "2", "3", "4", "5"];
// Optional: Clear all existing options first:
select.innerHTML = "";
// Populate list with options:
for(var i = 0; i < options.length; i++) {
var opt = options[i];
select.innerHTML += "<option value=\"" + opt + "\">" + opt + "</option>";
}
Well, me also I was struggling with this issue: this is how I solved it: apply table-layout: auto;
to the <table>
element.
I get the same exception for .xls
file, but after I open the file and save it as xlsx
file , the below code works:
try(InputStream is =file.getInputStream()){
XSSFWorkbook workbook = new XSSFWorkbook(is);
...
}
No need for a library. jQuery used this script for a while, btw.
http://dean.edwards.name/weblog/2006/06/again/
// Dean Edwards/Matthias Miller/John Resig
function init() {
// quit if this function has already been called
if (arguments.callee.done) return;
// flag this function so we don't do the same thing twice
arguments.callee.done = true;
// kill the timer
if (_timer) clearInterval(_timer);
// do stuff
};
/* for Mozilla/Opera9 */
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", init, false);
}
/* for Internet Explorer */
/*@cc_on @*/
/*@if (@_win32)
document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
var script = document.getElementById("__ie_onload");
script.onreadystatechange = function() {
if (this.readyState == "complete") {
init(); // call the onload handler
}
};
/*@end @*/
/* for Safari */
if (/WebKit/i.test(navigator.userAgent)) { // sniff
var _timer = setInterval(function() {
if (/loaded|complete/.test(document.readyState)) {
init(); // call the onload handler
}
}, 10);
}
/* for other browsers */
window.onload = init;
There's also the %n
modifier which can help in certain circumstances. It returns the column on which the string was so far. Example: you want to write several rows that are within the width of the first row like a table.
int width1, width2;
int values[6][2];
printf("|%s%n|%s%n|\n", header1, &width1, header2, &width2);
for(i=0; i<6; i++)
printf("|%*d|%*d|\n", width1, values[i][0], width2, values[i][1]);
will print two columns of the same width of whatever length the two strings header1
and header2
may have.
I don't know if all implementations have the %n
, but Solaris and Linux do.
#include<stdio.h>
struct examp{
int number;
};
struct examp a,*b=&a;`enter code here`
main()
{
a.number=5;
/* a.number,b->number,(*b).number produces same output. b->number is mostly used in linked list*/
printf("%d \n %d \n %d",a.number,b->number,(*b).number);
}
output is 5 5 5
It means the SSMS login user does not have permission on the .mdf file. This is how it has worked for me:
I had opened the SSMS (Run as administrator) and login as an administrator user, database right-click attach, click add, select the .mdf file, click Ok. Done.
Please check if you got the x64 edition of eclipse. Someone answered this just a few hours ago.
Bind the button, this is done with jQuery:
$("#my-table input[type='button']").click(function(){
var parameter = $(this).val();
window.location = "http://yoursite.com/page?variable=" + parameter;
});
Sets toast to a specific period in milli-seconds:
public void toast(int millisec, String msg) {
Handler handler = null;
final Toast[] toasts = new Toast[1];
for(int i = 0; i < millisec; i+=2000) {
toasts[0] = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
toasts[0].show();
if(handler == null) {
handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
toasts[0].cancel();
}
}, millisec);
}
}
}
Set the GET query parameters as managed properties in faces-config.xml
so that you don't need to gather them manually:
<managed-bean>
<managed-bean-name>forward</managed-bean-name>
<managed-bean-class>com.example.ForwardBean</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
<managed-property>
<property-name>action</property-name>
<value>#{param.action}</value>
</managed-property>
<managed-property>
<property-name>actionParam</property-name>
<value>#{param.actionParam}</value>
</managed-property>
</managed-bean>
This way the request forward.jsf?action=outcome1&actionParam=123
will let JSF set the action
and actionParam
parameters as action
and actionParam
properties of the ForwardBean
.
Create a small view forward.xhtml
(so small that it fits in default response buffer (often 2KB) so that it can be resetted by the navigationhandler, otherwise you've to increase the response buffer in the servletcontainer's configuration), which invokes a bean method on beforePhase
of the f:view
:
<!DOCTYPE html>
<html xmlns:f="http://java.sun.com/jsf/core">
<f:view beforePhase="#{forward.navigate}" />
</html>
The ForwardBean
can look like this:
public class ForwardBean {
private String action;
private String actionParam;
public void navigate(PhaseEvent event) {
FacesContext facesContext = FacesContext.getCurrentInstance();
String outcome = action; // Do your thing?
facesContext.getApplication().getNavigationHandler().handleNavigation(facesContext, null, outcome);
}
// Add/generate the usual boilerplate.
}
The navigation-rule
speaks for itself (note the <redirect />
entries which would do ExternalContext#redirect()
instead of ExternalContext#dispatch()
under the covers):
<navigation-rule>
<navigation-case>
<from-outcome>outcome1</from-outcome>
<to-view-id>/outcome1.xhtml</to-view-id>
<redirect />
</navigation-case>
<navigation-case>
<from-outcome>outcome2</from-outcome>
<to-view-id>/outcome2.xhtml</to-view-id>
<redirect />
</navigation-case>
</navigation-rule>
An alternative is to use forward.xhtml
as
<!DOCTYPE html>
<html>#{forward}</html>
and update the navigate()
method to be invoked on @PostConstruct
(which will be invoked after bean's construction and all managed property setting):
@PostConstruct
public void navigate() {
// ...
}
It has the same effect, however the view side is not really self-documenting. All it basically does is printing ForwardBean#toString()
(and hereby implicitly constructing the bean if not present yet).
Note for the JSF2 users, there is a cleaner way of passing parameters with <f:viewParam>
and more robust way of handling the redirect/navigation by <f:event type="preRenderView">
. See also among others:
You are not refering to the temporary location where the file is saved.
Use tmp_name
to access the file.
You can always see what's getting posted using :
echo "<pre>";
print_r($_FILES);
If you see this files array you will have an better understanding and idea of what's going on.
Windows SendMessage API with send WM_KEYDOWN.
If you are intending to make a single switch take multiple parameters, then you use nargs='+'
. If your example '-l' is actually taking integers:
a = argparse.ArgumentParser()
a.add_argument(
'-l', '--list', # either of this switches
nargs='+', # one or more parameters to this switch
type=int, # /parameters/ are ints
dest='list', # store in 'list'.
default=[], # since we're not specifying required.
)
print a.parse_args("-l 123 234 345 456".split(' '))
print a.parse_args("-l 123 -l=234 -l345 --list 456".split(' '))
Produces
Namespace(list=[123, 234, 345, 456])
Namespace(list=[456]) # Attention!
If you specify the same argument multiple times, the default action ('store'
) replaces the existing data.
The alternative is to use the append
action:
a = argparse.ArgumentParser()
a.add_argument(
'-l', '--list', # either of this switches
type=int, # /parameters/ are ints
dest='list', # store in 'list'.
default=[], # since we're not specifying required.
action='append', # add to the list instead of replacing it
)
print a.parse_args("-l 123 -l=234 -l345 --list 456".split(' '))
Which produces
Namespace(list=[123, 234, 345, 456])
Or you can write a custom handler/action to parse comma-separated values so that you could do
-l 123,234,345 -l 456
You can use transitions instead:
.successfully-saved.hide-opacity{
opacity: 0;
}
.successfully-saved {
color: #FFFFFF;
text-align: center;
-webkit-transition: opacity 3s ease-in-out;
-moz-transition: opacity 3s ease-in-out;
-ms-transition: opacity 3s ease-in-out;
-o-transition: opacity 3s ease-in-out;
opacity: 1;
}
$SQL_Part="("
$i=0;
while ($i<length($cat)-1)
{
$SQL_Part+=$cat[i]+",";
}
$SQL_Part=$SQL_Part+$cat[$i+1]+")"
$SQL="SELECT * FROM products WHERE catid IN "+$SQL_Part;
It's more generic and will fit for any array!!
Change the button to :
<button onclick="getElementById('hidden-div').style.display = 'block'; this.style.display = 'none'">Check Availability</button>
Or even better, use a proper event handler by identifying the button :
<button id="show_button">Check Availability</button>
and a script
<script type="text/javascript">
var button = document.getElementById('show_button')
button.addEventListener('click',hideshow,false);
function hideshow() {
document.getElementById('hidden-div').style.display = 'block';
this.style.display = 'none'
}
</script>
Here:
public class Tree<T> {
private Node<T> root;
public Tree(T rootData) {
root = new Node<T>();
root.data = rootData;
root.children = new ArrayList<Node<T>>();
}
public static class Node<T> {
private T data;
private Node<T> parent;
private List<Node<T>> children;
}
}
That is a basic tree structure that can be used for String
or any other object. It is fairly easy to implement simple trees to do what you need.
All you need to add are methods for add to, removing from, traversing, and constructors. The Node
is the basic building block of the Tree
.
This works with multiple statements:
if condition1 Then stmt1:stmt2 Else if condition2 Then stmt3:stmt4 Else stmt5:stmt6
Or you can split it over multiple lines:
if condition1 Then stmt1:stmt2
Else if condition2 Then stmt3:stmt4
Else stmt5:stmt6
@Oriol has an excellent answer, sadly as of October 2017, neither display:contents
, neither page-break-after
is widely supported, better said it's about Firefox which supports this but not the other players, I have come up with the following "hack" which I consider better than hard coding in a break after every 3rd element, because that will make it very difficult to make the page mobile friendly.
As said it's a hack and the drawback is that you need to add quite a lot of extra elements for nothing, but it does the trick and works cross browser even on the dated IE11.
The "hack" is to simply add an additional element after each div, which is set to display:none
and then used the css nth-child
to decide which one of this should be actually made visible forcing a line brake like this:
.container {
background: tomato;
display: flex;
flex-flow: row wrap;
justify-content: space-between;
}
.item {
width: 100px;
background: gold;
height: 100px;
border: 1px solid black;
font-size: 30px;
line-height: 100px;
text-align: center;
margin: 10px
}
.item:nth-child(3n-1) {
background: silver;
}
.breaker {
display: none;
}
.breaker:nth-child(3n) {
display: block;
width: 100%;
height: 0;
}
_x000D_
<div class="container">
<div class="item">1</div>
<p class="breaker"></p>
<div class="item">2</div>
<p class="breaker"></p>
<div class="item">3</div>
<p class="breaker"></p>
<div class="item">4</div>
<p class="breaker"></p>
<div class="item">5</div>
<p class="breaker"></p>
<div class="item">6</div>
<p class="breaker"></p>
<div class="item">7</div>
<p class="breaker"></p>
<div class="item">8</div>
<p class="breaker"></p>
<div class="item">9</div>
<p class="breaker"></p>
<div class="item">10</div>
<p class="breaker"></p>
</div>
_x000D_
This uses twitter bootstrap 3.x with one css class to get labels to sit on top of the inputs. Here's a fiddle link, make sure to expand results panel wide enough to see effect.
HTML:
<div class="row myform">
<div class="col-md-12">
<form name="myform" role="form" novalidate>
<div class="form-group">
<label class="control-label" for="fullName">Address Line</label>
<input required type="text" name="addr" id="addr" class="form-control" placeholder="Address"/>
</div>
<div class="form-inline">
<div class="form-group">
<label>State</label>
<input required type="text" name="state" id="state" class="form-control" placeholder="State"/>
</div>
<div class="form-group">
<label>ZIP</label>
<input required type="text" name="zip" id="zip" class="form-control" placeholder="Zip"/>
</div>
</div>
<div class="form-group">
<label class="control-label" for="country">Country</label>
<input required type="text" name="country" id="country" class="form-control" placeholder="country"/>
</div>
</form>
</div>
</div>
CSS:
.myform input.form-control {
display: block; /* allows labels to sit on input when inline */
margin-bottom: 15px; /* gives padding to bottom of inline inputs */
}
It's very easy to get memory leaks in a PHP script - especially if you use abstraction, such as an ORM. Try using Xdebug to profile your script and find out where all that memory went.
You can use shorthand technique to check whether it is undefined or null
function A(val)
{
if(val || "")
//do this
else
//do this
}
hope this will help you
To me a simple
sudo apt-get update
solved the issue. It was a clock issue and with this command it resets to the current date/time and everything worked
You could get a JavaScript object containing the parameters with something like this:
var regex = /[?&]([^=#]+)=([^&#]*)/g,
url = window.location.href,
params = {},
match;
while(match = regex.exec(url)) {
params[match[1]] = match[2];
}
The regular expression could quite likely be improved. It simply looks for name-value pairs, separated by =
characters, and pairs themselves separated by &
characters (or an =
character for the first one). For your example, the above would result in:
{v: "123", p: "hello"}
Here's a working example.
I'd prefer using Pathname:
require 'pathname' # pathname is in stdlib
Pathname(ROOT_DIR) + project + 'App.config'
about <<
and +
from ruby docs:
+
: Returns a new String containing other_str concatenated to str
<<
: Concatenates the given object to str. If the object is a Fixnum between 0 and 255, it is converted to a character before concatenation.
so difference is in what becomes to first operand (<<
makes changes in place, +
returns new string so it is memory heavier) and what will be if first operand is Fixnum (<<
will add as if it was character with code equal to that number, +
will raise error)
All of the grouped objects, or all of the types? It sounds like you may just want:
var query = types.GroupBy(t => t.Type)
.Select(g => new { Type = g.Key, Count = g.Count() });
foreach (var result in query)
{
Console.WriteLine("{0}, {1}", result.Type, result.Count);
}
EDIT: If you want it in a dictionary, you can just use:
var query = types.GroupBy(t => t.Type)
.ToDictionary(g => g.Key, g => g.Count());
There's no need to select into pairs and then build the dictionary.
For CPU details use psutil library
For RAM Frequency (in MHz) use the built in Linux library dmidecode and manipulate the output a bit ;). this command needs root permission hence supply your password too. just copy the following commend replacing mypass with your password
import os
os.system("echo mypass | sudo -S dmidecode -t memory | grep 'Clock Speed' | cut -d ':' -f2")
------------------- Output ---------------------------
1600 MT/s
Unknown
1600 MT/s
Unknown 0
[i for i in os.popen("echo mypass | sudo -S dmidecode -t memory | grep 'Clock Speed' | cut -d ':' -f2").read().split(' ') if i.isdigit()]
-------------------------- output -------------------------
['1600', '1600']
The ideal way would be to add CORS support to your server.
You could also try using a separate jsonp module. As far as I know axios does not support jsonp. So I am not sure if the method you are using would qualify as a valid jsonp request.
There is another hackish work around for the CORS problem. You will have to deploy your code with an nginx server serving as a proxy for both your server and your client.
The thing that will do the trick us the proxy_pass
directive. Configure your nginx server in such a way that the location block handling your particular request will proxy_pass
or redirect your request to your actual server.
CORS problems usually occur because of change in the website domain.
When you have a singly proxy serving as the face of you client and you server, the browser is fooled into thinking that the server and client reside in the same domain. Ergo no CORS.
Consider this example.
Your server is my-server.com
and your client is my-client.com
Configure nginx as follows:
// nginx.conf
upstream server {
server my-server.com;
}
upstream client {
server my-client.com;
}
server {
listen 80;
server_name my-website.com;
access_log /path/to/access/log/access.log;
error_log /path/to/error/log/error.log;
location / {
proxy_pass http://client;
}
location ~ /server/(?<section>.*) {
rewrite ^/server/(.*)$ /$1 break;
proxy_pass http://server;
}
}
Here my-website.com
will be the resultant name of the website where the code will be accessible (name of the proxy website).
Once nginx is configured this way. You will need to modify the requests such that:
my-server.com/<API-path>
to my-website.com/server/<API-path>
In case you are not familiar with nginx I would advise you to go through the documentation.
To explain what is happening in the configuration above in brief:
upstream
s define the actual servers to whom the requests will be redirectedserver
block is used to define the actual behaviour of the nginx server.server_name
is used to identify the block which will be used to handle the current request. error_log
and access_log
directives are used to define the locations of the log files (used for debugging)location
blocks define the handling of different types of requests:
/
all these requests are redirected to the client/server/<API-path>
. We will be redirecting all such requests to the server.Note: /server
here is being used to distinguish the client side requests from the server side requests. Since the domain is the same there is no other way of distinguishing requests. Keep in mind there is no such convention that compels you to add /server
in all such use cases. It can be changed to any other string eg. /my-server/<API-path>
, /abc/<API-path>
, etc.
Even though this technique should do the trick, I would highly advise you to add CORS support to the server as this is the ideal way situations like these should be handled.
If you wish to avoid doing all this while developing you could for this chrome extension. It should allow you to perform cross domain requests during development.
There is not a built-in number formatter for JavaScript, but there are some libraries that accomplish this:
It is also possible to set the error action preference on individual cmdlets, not just for the whole script. This is done using the parameter ErrorAction (alisa EA) which is available on all cmdlets.
Example
try
{
Write-Host $ErrorActionPreference; #Check setting for ErrorAction - the default is normally Continue
get-item filethatdoesntexist; # Normally generates non-terminating exception so not caught
write-host "You will hit me as exception from line above is non-terminating";
get-item filethatdoesntexist -ErrorAction Stop; #Now ErrorAction parameter with value Stop causes exception to be caught
write-host "you won't reach me as exception is now caught";
}
catch
{
Write-Host "Caught the exception";
Write-Host $Error[0].Exception;
}
In the solution it is mentioned - "One final thing to check is to make sure that you are not loading any plugins before you load jQuery. Plugins extend the "$" object, so if you load a plugin before loading jQuery core, then you'll get the error you described."
For avoiding this -
Many JavaScript libraries use $ as a function or variable name, just as jQuery does. In jQuery's case, $ is just an alias for jQuery, so all functionality is available without using $. If we need to use another JavaScript library alongside jQuery, we can return control of $ back to the other library with a call to $.noConflict():
You mean something like IPhone checkboxes? Try Thomas Reynolds' iOS Checkboxes script:
Once the files are available to your site, activating the script is very easy:
...
$(document).ready(function() { $(':checkbox').iphoneStyle(); });
Results:
When using numbers as the key, I suppose you could also try this:
Map<Long, String> map = new HashMap<>();
map.put(4L, "The First");
map.put(6L, "The Second");
map.put(11L, "The Last");
long lastKey = 0;
//you entered Map<Long, String> entry
for (Map.Entry<Long, String> entry : map.entrySet()) {
lastKey = entry.getKey();
}
System.out.println(lastKey); // 11
With msvc extension:
#define Y_TUPLE_SIZE(...) Y_TUPLE_SIZE_II((Y_TUPLE_SIZE_PREFIX_ ## __VA_ARGS__ ## _Y_TUPLE_SIZE_POSTFIX,32,31,30,29,28,27,26,25,24,23,22,21,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0))
#define Y_TUPLE_SIZE_II(__args) Y_TUPLE_SIZE_I __args
#define Y_TUPLE_SIZE_PREFIX__Y_TUPLE_SIZE_POSTFIX ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,0
#define Y_TUPLE_SIZE_I(__p0,__p1,__p2,__p3,__p4,__p5,__p6,__p7,__p8,__p9,__p10,__p11,__p12,__p13,__p14,__p15,__p16,__p17,__p18,__p19,__p20,__p21,__p22,__p23,__p24,__p25,__p26,__p27,__p28,__p29,__p30,__p31,__n,...) __n
Works for 0 - 32 arguments. This limit can be easily extended.
EDIT: Simplified version (works in VS2015 14.0.25431.01 Update 3 & gcc 7.4.0) up to 100 arguments to copy & paste:
#define COUNTOF(...) _COUNTOF_CAT( _COUNTOF_A, ( 0, ##__VA_ARGS__, 100,\
99, 98, 97, 96, 95, 94, 93, 92, 91, 90,\
89, 88, 87, 86, 85, 84, 83, 82, 81, 80,\
79, 78, 77, 76, 75, 74, 73, 72, 71, 70,\
69, 68, 67, 66, 65, 64, 63, 62, 61, 60,\
59, 58, 57, 56, 55, 54, 53, 52, 51, 50,\
49, 48, 47, 46, 45, 44, 43, 42, 41, 40,\
39, 38, 37, 36, 35, 34, 33, 32, 31, 30,\
29, 28, 27, 26, 25, 24, 23, 22, 21, 20,\
19, 18, 17, 16, 15, 14, 13, 12, 11, 10,\
9, 8, 7, 6, 5, 4, 3, 2, 1, 0 ) )
#define _COUNTOF_CAT( a, b ) a b
#define _COUNTOF_A( a0, a1, a2, a3, a4, a5, a6, a7, a8, a9,\
a10, a11, a12, a13, a14, a15, a16, a17, a18, a19,\
a20, a21, a22, a23, a24, a25, a26, a27, a28, a29,\
a30, a31, a32, a33, a34, a35, a36, a37, a38, a39,\
a40, a41, a42, a43, a44, a45, a46, a47, a48, a49,\
a50, a51, a52, a53, a54, a55, a56, a57, a58, a59,\
a60, a61, a62, a63, a64, a65, a66, a67, a68, a69,\
a70, a71, a72, a73, a74, a75, a76, a77, a78, a79,\
a80, a81, a82, a83, a84, a85, a86, a87, a88, a89,\
a90, a91, a92, a93, a94, a95, a96, a97, a98, a99,\
a100, n, ... ) n
If you want all the units, not just the biggest one, use one of these 2 methods (based on @Ankish's answer):
Example output: 28 D | 23 H | 59 M | 59 S
+ (NSString *) remaningTime:(NSDate *)startDate endDate:(NSDate *)endDate
{
NSCalendarUnit units = NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
NSDateComponents *components = [[NSCalendar currentCalendar] components:units fromDate: startDate toDate: endDate options: 0];
return [NSString stringWithFormat:@"%ti D | %ti H | %ti M | %ti S", [components day], [components hour], [components minute], [components second]];
}
+ (NSString *) timeFromNowUntil:(NSDate *)endDate
{
return [self remaningTime:[NSDate date] endDate:endDate];
}
I just release my latest library for Google Maps Direction API on Android https://github.com/akexorcist/Android-GoogleDirectionLibrary
(Good intro article part 1, part 2, part 3. As for compelling reasons, that depends on what you are using SQL server for. Do you need hierarchical data types? Do you currently store files in the database and want to switch over to SQL Server's new filestream feature? Could you use more disk space by turning on data compression?
And let's not forget the ability to MERGE data.
I would do it this way:
(function($) {
jQuery.fn.doSomething = function() {
return this.each(function() {
var $this = $(this);
$this.click(function(event) {
event.preventDefault();
// Your function goes here
});
});
};
})(jQuery);
Then on document ready you can do stuff like this:
$(document).ready(function() {
$('#div1').doSomething();
$('#div2').doSomething();
});
I came across this post in search for the dockerhub repo URL when creating a dockerhub kubernetes secret.. figured id share the URL is used with success, hope that's ok.
Live Current: https://index.docker.io/v2/
Dead Orginal: https://index.docker.io/v1/
Use online service http://www.extractpdf.com. No need to install anything.
Adding on to Adrian Gallero's answer:
Calling a generic method from type info involves three steps.
((Action)GenericMethod<object>)
.Method
.GetGenericMethodDefinition()
.MakeGenericMethod(typeof(string))
.Invoke(this, null);
where GenericMethod<object>
is the method name to call and any type that satisfies the generic constraints.
(Action) matches the signature of the method to be called i.e. (Func<string,string,int>
or Action<bool>
)
MethodInfo method = typeof(Sample).GetMethod("GenericMethod");
From inside the class that contains the methods:
MethodInfo method = ((Action)GenericMethod<object>)
.Method
.GetGenericMethodDefinition();
MethodInfo method = ((Action)StaticMethod<object>)
.Method
.GetGenericMethodDefinition();
From outside of the class that contains the methods:
MethodInfo method = ((Action)(new Sample())
.GenericMethod<object>)
.Method
.GetGenericMethodDefinition();
MethodInfo method = ((Action)Sample.StaticMethod<object>)
.Method
.GetGenericMethodDefinition();
In C#, the name of a method, i.e. "ToString" or "GenericMethod" actually refers to a group of methods that may contain one or more methods. Until you provide the types of the method parameters, it is not known which method you are referring to.
((Action)GenericMethod<object>)
refers to the delegate for a specific method. ((Func<string, int>)GenericMethod<object>)
refers to a different overload of GenericMethod
MethodInfo method = ((MethodCallExpression)((Expression<Action<Sample>>)(
(Sample v) => v.GenericMethod<object>()
)).Body).Method.GetGenericMethodDefinition();
This breaks down to
Create a lambda expression where the body is a call to your desired method.
Expression<Action<Sample>> expr = (Sample v) => v.GenericMethod<object>();
Extract the body and cast to MethodCallExpression
MethodCallExpression methodCallExpr = (MethodCallExpression)expr.Body;
Get the generic method definition from the method
MethodInfo methodA = methodCallExpr.Method.GetGenericMethodDefinition();
MethodInfo generic = method.MakeGenericMethod(myType);
generic.Invoke(this, null);
Database client tools (like DBeaver or phpMyAdmin) often support means of fulltext search through entire database.
Whenever I have had odd issues like this, I usually sit down with a tool like WireShark and look at the raw data being passed back and forth. You might be surprised where things are being disconnected, and you are only being notified when you try and read.
To get the entire request URL string:
HttpContext.Current.Request.Url
To get the www.foo.com portion of the request:
HttpContext.Current.Request.Url.Host
Note that you are, to some degree, at the mercy of factors outside your ASP.NET application. If IIS is configured to accept multiple or any host header for your application, then any of those domains which resolved to your application via DNS may show up as the Request Url, depending on which one the user entered.
The formats and codecs supported by your build of ffmpeg
can vary due the version, how it was compiled, and if any external libraries, such as libx264, were supported during compilation.
List all formats:
ffmpeg -formats
Display options specific to, and information about, a particular muxer:
ffmpeg -h muxer=matroska
Display options specific to, and information about, a particular demuxer:
ffmpeg -h demuxer=gif
List all codecs:
ffmpeg -codecs
List all encoders:
ffmpeg -encoders
List all decoders:
ffmpeg -decoders
Display options specific to, and information about, a particular encoder:
ffmpeg -h encoder=mpeg4
Display options specific to, and information about, a particular decoder:
ffmpeg -h decoder=aac
There is a key near the top of the output that describes each letter that precedes the name of the format, encoder, decoder, or codec:
$ ffmpeg -encoders
[…]
Encoders:
V..... = Video
A..... = Audio
S..... = Subtitle
.F.... = Frame-level multithreading
..S... = Slice-level multithreading
...X.. = Codec is experimental
....B. = Supports draw_horiz_band
.....D = Supports direct rendering method 1
------
[…]
V.S... mpeg4 MPEG-4 part 2
In this example V.S...
indicates that the encoder mpeg4
is a V
ideo encoder and supports S
lice-level multithreading.
The Best and easy way to load Image via Url is by this Code:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData *data =[NSData dataWithContentsOfURL:[NSURL URLWithString:imgUrl]];
dispatch_async(dispatch_get_main_queue(), ^{
imgView.image= [UIImage imageWithData:data];
});
});
Replace imgUrl
by your ImageURL
Replace imgView
by your UIImageView
.
It will load the Image in another Thread, so It will not slow down your App load.
This is pretty must just a copy of that projects demo page and shows uploading a single file on form submit with upload progress.
(function (angular) {
'use strict';
angular.module('uploadModule', [])
.controller('uploadCtrl', [
'$scope',
'$upload',
function ($scope, $upload) {
$scope.model = {};
$scope.selectedFile = [];
$scope.uploadProgress = 0;
$scope.uploadFile = function () {
var file = $scope.selectedFile[0];
$scope.upload = $upload.upload({
url: 'api/upload',
method: 'POST',
data: angular.toJson($scope.model),
file: file
}).progress(function (evt) {
$scope.uploadProgress = parseInt(100.0 * evt.loaded / evt.total, 10);
}).success(function (data) {
//do something
});
};
$scope.onFileSelect = function ($files) {
$scope.uploadProgress = 0;
$scope.selectedFile = $files;
};
}
])
.directive('progressBar', [
function () {
return {
link: function ($scope, el, attrs) {
$scope.$watch(attrs.progressBar, function (newValue) {
el.css('width', newValue.toString() + '%');
});
}
};
}
]);
}(angular));
HTML
<form ng-submit="uploadFile()">
<div class="row">
<div class="col-md-12">
<input type="text" ng-model="model.fileDescription" />
<input type="number" ng-model="model.rating" />
<input type="checkbox" ng-model="model.isAGoodFile" />
<input type="file" ng-file-select="onFileSelect($files)">
<div class="progress" style="margin-top: 20px;">
<div class="progress-bar" progress-bar="uploadProgress" role="progressbar">
<span ng-bind="uploadProgress"></span>
<span>%</span>
</div>
</div>
<button button type="submit" class="btn btn-default btn-lg">
<i class="fa fa-cloud-upload"></i>
<span>Upload File</span>
</button>
</div>
</div>
</form>
EDIT: Added passing a model up to the server in the file post.
The form data in the input elements would be sent in the data property of the post and be available as normal form values.
Use the Figure.savefig()
method, like so:
ax = s.hist() # s is an instance of Series
fig = ax.get_figure()
fig.savefig('/path/to/figure.pdf')
It doesn't have to end in pdf
, there are many options. Check out the documentation.
Alternatively, you can use the pyplot
interface and just call the savefig
as a function to save the most recently created figure:
import matplotlib.pyplot as plt
s.hist()
plt.savefig('path/to/figure.pdf') # saves the current figure
s3_sync:
bucket: ansible-harshika
file_root: "{{ pathoftsfiles }}"
validate_certs: false
mode: push
key_prefix: "{{ folder }}"
here the variables are being used named as 'pathoftsfiles' and 'folder'. Now the value to this variable can be given by the below command
sudo ansible-playbook multiadd.yml --extra-vars "pathoftsfiles=/opt/lampp/htdocs/video/uploads/tsfiles/$2 folder=nitesh"
Note: Don't use the inverted commas while passing the values to the variable in the shell command
<system.webServer>
<httpErrors errorMode="DetailedLocalOnly">
<remove statusCode="404" subStatusCode="-1" />
<error statusCode="404" prefixLanguageFilePath="" path="your page" responseMode="Redirect" />
</httpErrors>
</system.webServer>
Here is PySpark version to create Hive table from parquet file. You may have generated Parquet files using inferred schema and now want to push definition to Hive metastore. You can also push definition to the system like AWS Glue or AWS Athena and not just to Hive metastore. Here I am using spark.sql to push/create permanent table.
# Location where my parquet files are present.
df = spark.read.parquet("s3://my-location/data/")
cols = df.dtypes
buf = []
buf.append('CREATE EXTERNAL TABLE test123 (')
keyanddatatypes = df.dtypes
sizeof = len(df.dtypes)
print ("size----------",sizeof)
count=1;
for eachvalue in keyanddatatypes:
print count,sizeof,eachvalue
if count == sizeof:
total = str(eachvalue[0])+str(' ')+str(eachvalue[1])
else:
total = str(eachvalue[0]) + str(' ') + str(eachvalue[1]) + str(',')
buf.append(total)
count = count + 1
buf.append(' )')
buf.append(' STORED as parquet ')
buf.append("LOCATION")
buf.append("'")
buf.append('s3://my-location/data/')
buf.append("'")
buf.append("'")
##partition by pt
tabledef = ''.join(buf)
print "---------print definition ---------"
print tabledef
## create a table using spark.sql. Assuming you are using spark 2.1+
spark.sql(tabledef);
it is possible to remove leading and trailing zeros in TSQL
Convert it to string using STR TSQL function if not string, Then
Remove both leading & trailing zeros
SELECT REPLACE(RTRIM(LTRIM(REPLACE(AccNo,'0',' '))),' ','0') AccNo FROM @BankAccount
More info on forum.
This doesn't seem to be a problem on a Core 2 Duo running Windows XP and JRE 1.5.0_06.
In a test with three threads I don't see System.nanoTime() going backwards. The processors are both busy, and threads go to sleep occasionally to provoke moving threads around.
[EDIT] I would guess that it only happens on physically separate processors, i.e. that the counters are synchronized for multiple cores on the same die.
I suggest split (not saying that the other answers are invalid, this is just another way to do it):
def findreplace(char, string):
return ''.join(string.split(char))
Splitting by a character removes all the characters and turns it into a list. Then we join the list with the join function. You can see the ipython console test below
In[112]: findreplace('i', 'it is icy')
Out[112]: 't s cy'
And the speed...
In[114]: timeit("findreplace('it is icy','i')", "from __main__ import findreplace")
Out[114]: 0.9927914671134204
Not as fast as replace or translate, but ok.
If you use the subprocess
python module, you are able to handle the STDOUT, STDERR and return code of command separately. You can see an example for the complete command caller implementation. Of course you can extend it with try..except
if you want.
The below function returns the STDOUT, STDERR and Return code so you can handle them in the other script.
import subprocess
def command_caller(command=None)
sp = subprocess.Popen(command, stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=False)
out, err = sp.communicate()
if sp.returncode:
print(
"Return code: %(ret_code)s Error message: %(err_msg)s"
% {"ret_code": sp.returncode, "err_msg": err}
)
return sp.returncode, out, err
I don't know any native cmdlet in powershell but you can use com object instead:
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut("$Home\Desktop\ColorPix.lnk")
$Shortcut.TargetPath = "C:\Program Files (x86)\ColorPix\ColorPix.exe"
$Shortcut.Save()
you can create a powershell script save as set-shortcut.ps1 in your $pwd
param ( [string]$SourceExe, [string]$DestinationPath )
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut($DestinationPath)
$Shortcut.TargetPath = $SourceExe
$Shortcut.Save()
and call it like this
Set-ShortCut "C:\Program Files (x86)\ColorPix\ColorPix.exe" "$Home\Desktop\ColorPix.lnk"
If you want to pass arguments to the target exe, it can be done by:
#Set the additional parameters for the shortcut
$Shortcut.Arguments = "/argument=value"
before $Shortcut.Save().
For convenience, here is a modified version of set-shortcut.ps1. It accepts arguments as its second parameter.
param ( [string]$SourceExe, [string]$ArgumentsToSourceExe, [string]$DestinationPath )
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut($DestinationPath)
$Shortcut.TargetPath = $SourceExe
$Shortcut.Arguments = $ArgumentsToSourceExe
$Shortcut.Save()
Add your new class "tableresp" with table-responisve class and then add below code in your js file
$(".tableresp").on('click', '.dropdown-toggle', function(event) {
if ($('.dropdown-menu').length) {
var elm = $('.dropdown-menu'),
docHeight = $(document).height(),
docWidth = $(document).width(),
btn_offset = $(this).offset(),
btn_width = $(this).outerWidth(),
btn_height = $(this).outerHeight(),
elm_width = elm.outerWidth(),
elm_height = elm.outerHeight(),
table_offset = $(".tableresp").offset(),
table_width = $(".tableresp").width(),
table_height = $(".tableresp").height(),
tableoffright = table_width + table_offset.left,
tableoffbottom = table_height + table_offset.top,
rem_tablewidth = docWidth - tableoffright,
rem_tableheight = docHeight - tableoffbottom,
elm_offsetleft = btn_offset.left,
elm_offsetright = btn_offset.left + btn_width,
elm_offsettop = btn_offset.top + btn_height,
btn_offsetbottom = elm_offsettop,
left_edge = (elm_offsetleft - table_offset.left) < elm_width,
top_edge = btn_offset.top < elm_height,
right_edge = (table_width - elm_offsetleft) < elm_width,
bottom_edge = (tableoffbottom - btn_offsetbottom) < elm_height;
console.log(tableoffbottom);
console.log(btn_offsetbottom);
console.log(bottom_edge);
console.log((tableoffbottom - btn_offsetbottom) + "|| " + elm_height);
var table_offset_bottom = docHeight - (table_offset.top + table_height);
var touchTableBottom = (btn_offset.top + btn_height + (elm_height * 2)) - table_offset.top;
var bottomedge = touchTableBottom > table_offset_bottom;
if (left_edge) {
$(this).addClass('left-edge');
} else {
$('.dropdown-menu').removeClass('left-edge');
}
if (bottom_edge) {
$(this).parent().addClass('dropup');
} else {
$(this).parent().removeClass('dropup');
}
}
});
var table_smallheight = $('.tableresp'),
positioning = table_smallheight.parent();
if (table_smallheight.height() < 320) {
positioning.addClass('positioning');
$('.tableresp .dropdown,.tableresp .adropup').css('position', 'static');
} else {
positioning.removeClass('positioning');
$('.tableresp .dropdown,.tableresp .dropup').css('position', 'relative');
}
Maybe use LaTeX and try something like this
\documentclass[a4paper]{article}
\usepackage[3D]{movie15}
\usepackage{hyperref}
\begin{document}
\includemovie[
poster,
toolbar,
3Daac=60.000000, 3Droll=0.000000, 3Dc2c=0.000000 2.483000 0.000000, 3Droo=2.483000, 3Dcoo=0.000000 0.000000 0.000000,
3Dlights=CAD,
]{\linewidth}{\linewidth}{Bob.u3d}
\end{document}
where Bob3d.u3d is a sample virtual reality file I had. This works (or did) for movies, and I expect it might work for gifs too.
It is because there is no package cache in the image, you need to run:
apt-get update
before installing packages, and if your command is in a Dockerfile, you'll then need:
apt-get -y install curl
To suppress the standard output from a command use -qq
. E.g.
apt-get -qq -y install curl
For having a trasition effect like a highlighter just to highlight the text and fade off the bg color, we used the following:
.field-error {_x000D_
color: #f44336;_x000D_
padding: 2px 5px;_x000D_
position: absolute;_x000D_
font-size: small;_x000D_
background-color: white;_x000D_
}_x000D_
_x000D_
.highlighter {_x000D_
animation: fadeoutBg 3s; /***Transition delay 3s fadeout is class***/_x000D_
-moz-animation: fadeoutBg 3s; /* Firefox */_x000D_
-webkit-animation: fadeoutBg 3s; /* Safari and Chrome */_x000D_
-o-animation: fadeoutBg 3s; /* Opera */_x000D_
}_x000D_
_x000D_
@keyframes fadeoutBg {_x000D_
from { background-color: lightgreen; } /** from color **/_x000D_
to { background-color: white; } /** to color **/_x000D_
}_x000D_
_x000D_
@-moz-keyframes fadeoutBg { /* Firefox */_x000D_
from { background-color: lightgreen; }_x000D_
to { background-color: white; }_x000D_
}_x000D_
_x000D_
@-webkit-keyframes fadeoutBg { /* Safari and Chrome */_x000D_
from { background-color: lightgreen; }_x000D_
to { background-color: white; }_x000D_
}_x000D_
_x000D_
@-o-keyframes fadeoutBg { /* Opera */_x000D_
from { background-color: lightgreen; }_x000D_
to { background-color: white; }_x000D_
}
_x000D_
<div class="field-error highlighter">File name already exists.</div>
_x000D_
This how I check php version
PS C:\Windows\system32> php -version
Result:
PHP 7.2.7 (cli) (built: Jun 19 2018 23:44:15) ( NTS MSVC15 (Visual C++ 2017) x86 )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies
PS C:\Windows\system32>
Solution for ajax pages that continuously load data. The previews methods stated do not work. What we can do instead is grab the page dom and hash it and compare old and new hash values together over a delta time.
import time
from selenium import webdriver
def page_has_loaded(driver, sleep_time = 2):
'''
Waits for page to completely load by comparing current page hash values.
'''
def get_page_hash(driver):
'''
Returns html dom hash
'''
# can find element by either 'html' tag or by the html 'root' id
dom = driver.find_element_by_tag_name('html').get_attribute('innerHTML')
# dom = driver.find_element_by_id('root').get_attribute('innerHTML')
dom_hash = hash(dom.encode('utf-8'))
return dom_hash
page_hash = 'empty'
page_hash_new = ''
# comparing old and new page DOM hash together to verify the page is fully loaded
while page_hash != page_hash_new:
page_hash = get_page_hash(driver)
time.sleep(sleep_time)
page_hash_new = get_page_hash(driver)
print('<page_has_loaded> - page not loaded')
print('<page_has_loaded> - page loaded: {}'.format(driver.current_url))
Grokking lookaround rapidly.
How to distinguish lookahead and lookbehind?
Take 2 minutes tour with me:
(?=) - positive lookahead
(?<=) - positive lookbehind
Suppose
A B C #in a line
Now, we ask B, Where are you?
B has two solutions to declare it location:
One, B has A ahead and has C bebind
Two, B is ahead(lookahead) of C and behind (lookhehind) A.
As we can see, the behind and ahead are opposite in the two solutions.
Regex is solution Two.
Try this
$('#add_here').text('new-dynamic-text');
Run in background and add logs to log file using the following:
nohup java -jar /web/server.jar > log.log 2>&1 &
Try:
jQuery("#availability option:selected").val();
Or to get the text of the option, use text()
:
jQuery("#availability option:selected").text();
More Info:
I tried several of the options posted in this article, but it worked for me using this option in eclipse.ini:
-Dorg.eclipse.swt.browser.DefaultType=mozilla
If you are running the program with python, try running it with python3.
Your can use your tokenizer and pad sequencing for a new piece of text. This is followed by model prediction. This will return the prediction as a numpy array plus the label itself.
For example:
new_complaint = ['Your service is not good']
seq = tokenizer.texts_to_sequences(new_complaint)
padded = pad_sequences(seq, maxlen=maxlen)
pred = model.predict(padded)
print(pred, labels[np.argmax(pred)])
So one does not have to find and replace the Object.keys method, another approach would be this code early in the execution of the script:
if(!Object.keys)
{
Object.keys = function(obj)
{
return $.map(obj, function(v, k)
{
return k;
});
};
}
It just happened here to me as well. Thanks to a great partner we found the answer. Your Xcode may be pointing to the simulator ..change it to a IOS device instead ..built smooth after ....
//disable future dates
$('#datetimepicker1').datetimepicker({
format: 'DD-MM-YYYY',
maxDate: new Date
});
//disable past dates
$('#datetimepicker2').datetimepicker({
format: 'DD-MM-YYYY',
minDate: new Date
});
Natively the only way is by creating an <input type="file">
element and then simulating a click, unfortunately.
There's a tiny plugin (shameless plug) which will take the pain away of having to do this all the time: file-dialog
fileDialog()
.then(file => {
const data = new FormData()
data.append('file', file[0])
data.append('imageName', 'flower')
// Post to server
fetch('/uploadImage', {
method: 'POST',
body: data
})
})
Based on Git Tip: Deleting Old Local Branches, which looks similar to jason.rickman's solution I implemented a custom command for this purpose called git gone using Bash:
$ git gone
usage: git gone [-pndD] [<branch>=origin]
OPTIONS
-p prune remote branch
-n dry run: list the gone branches
-d delete the gone branches
-D delete the gone branches forcefully
EXAMPLES
git gone -pn prune and dry run
git gone -d delete the gone branches
git gone -pn
combines the pruning and listing the "gone" branches:
$ git gone -pn
bport/fix-server-broadcast b472d5d2b [origin/bport/fix-server-broadcast: gone] Bump modules
fport/rangepos 45c857d15 [origin/fport/rangepos: gone] Bump modules
Then you can pull the trigger using git gone -d
or git gone -D
.
"$BRANCH/.*: gone]"
where $BRANCH
would normally be origin
. This probably won't work if your Git output is localized to French etc.The other answers normalize an image based on the entire image. But if your image has a predominant color (such as black), it will mask out the features that you're trying to enhance since it will not be as pronounced. To get around this limitation, we can normalize the image based on a subsection region of interest (ROI). Essentially we will normalize based on the section of the image that we want to enhance instead of equally treating each pixel with the same weight. Take for instance this earth image:
Input image ->
Normalization based on entire image
If we want to enhance the clouds by normalizing based on the entire image, the result will not be very sharp and will be over saturated due to the black background. The features to enhance are lost. So to obtain a better result we can crop a ROI, normalize based on the ROI, and then apply the normalization back onto the original image. Say we crop the ROI highlighted in green:
This gives us this ROI
The idea is to calculate the mean and standard deviation of the ROI and then clip the frame based on the lower and upper range. In addition, we could use an offset to dynamically adjust the clip intensity. From here we normalize the original image to this new range. Here's the result:
Before ->
After
Code
import cv2
import numpy as np
# Load image as grayscale and crop ROI
image = cv2.imread('1.png', 0)
x, y, w, h = 364, 633, 791, 273
ROI = image[y:y+h, x:x+w]
# Calculate mean and STD
mean, STD = cv2.meanStdDev(ROI)
# Clip frame to lower and upper STD
offset = 0.2
clipped = np.clip(image, mean - offset*STD, mean + offset*STD).astype(np.uint8)
# Normalize to range
result = cv2.normalize(clipped, clipped, 0, 255, norm_type=cv2.NORM_MINMAX)
cv2.imshow('image', image)
cv2.imshow('ROI', ROI)
cv2.imshow('result', result)
cv2.waitKey()
The difference between normalizing based on the entire image vs a specific section of the ROI can be visualized by applying a heatmap to the result. Notice the difference on how the clouds are defined.
Input image ->
heatmap
Normalized on entire image ->
heatmap
Normalized on ROI ->
heatmap
Heatmap code
import matplotlib.pyplot as plt
import numpy as np
import cv2
image = cv2.imread('result.png', 0)
colormap = plt.get_cmap('inferno')
heatmap = (colormap(image) * 2**16).astype(np.uint16)[:,:,:3]
heatmap = cv2.cvtColor(heatmap, cv2.COLOR_RGB2BGR)
cv2.imshow('image', image)
cv2.imshow('heatmap', heatmap)
cv2.waitKey()
Note: The ROI bounding box coordinates were obtained using how to get ROI Bounding Box Coordinates without Guess & Check and heatmap code was from how to convert a grayscale image to heatmap image with Python OpenCV
OK, the first thing to note is that <i>
has been deprecated, and shouldn't be used<i>
has not been deprecated, but I still do not recommend using it—see the comments for details. This is because it goes entirely against keeping presentation in the presentation layer, which you've pointed out. Similarly, <span class="italic">
seems to break the mold too.
So now we have two real ways of doing things: <em>
and <span class="footnote">
. Remember that em
stands for emphasis. When you wish to apply emphasis to a word, phrase or sentence, stick it in <em>
tags regardless of whether you want italics or not. If you want to change the styling in some other way, use CSS: em { font-weight: bold; font-style: normal; }
. Of course, you can also apply a class to the <em>
tag: if you decide you want certain emphasised phrases to show up in red, give them a class and add it to the CSS:
Fancy some <em class="special">shiny</em> text?
em { font-weight: bold; font-style: normal; }
em.special { color: red; }
If you're applying italics for some other reason, go with the other method and give the section a class. That way, you can change its styling whenever you want without adjusting the HTML. In your example, footnotes should not be emphasised—in fact, they should be de-emphasised, as the point of a footnote is to show unimportant but interesting or useful information. In this case, you're much better off applying a class to the footnote and making it look like one in the presentation layer—the CSS.
As an alternative, you can use the environment variables LIBRARY_PATH
and CPLUS_INCLUDE_PATH
, which respectively indicate where to look for libraries and where to look for headers (CPATH
will also do the job), without specifying the -L and -I options.
Edit:
CPATH
includes header with -I
and CPLUS_INCLUDE_PATH
with -isystem
.
For bootstrap users, this fixed it for me:
$($.fn.dataTable.tables(true)).DataTable()
.columns.adjust()
.fixedColumns().relayout();
See article here
A good bet is to utilize Rails' Arel SQL manager, which explicitly supports case-insensitive ActiveRecord queries:
t = Guide.arel_table Guide.where(t[:title].matches('%attack'))
Here's an interesting blog post regarding the portability of case-insensitive queries using Arel. It's worth a read to understand the implications of utilizing Arel across databases.
Have you added the google maven endpoint?
Important: The support libraries are now available through Google's Maven repository. You do not need to download the support repository from the SDK Manager. For more information, see Support Library Setup.
Add the endpoint to your build.gradle file:
allprojects {
repositories {
jcenter()
maven {
url 'https://maven.google.com'
}
}
}
Which can be replaced by the shortcut google()
since Android Gradle v3:
allprojects {
repositories {
jcenter()
google()
}
}
If you already have any maven url inside repositories
, you can add the reference after them, i.e.:
allprojects {
repositories {
jcenter()
maven {
url 'https://jitpack.io'
}
maven {
url 'https://maven.google.com'
}
}
}
I use following approach to finding memory leaks in Java. I've used jProfiler with great success, but I believe that any specialized tool with graphing capabilities (diffs are easier to analyze in graphical form) will work.
Basically analysis should start from greatest positive diff by, say, object types and find what causes those extra objects to stick in memory.
For web applications that process requests in several threads analysis gets more complicated, but nevertheless general approach still applies.
I did quite a number of projects specifically aimed at reducing memory footprint of the applications and this general approach with some application specific tweaks and trick always worked well.
The Code is very Simple, Lets Put This Code
var name = $("#band_type_choices option:selected").text();
Here You don't want to use $(this).find().text()
, directly you can put your id name and add
option:selected
along with text()
.
This will return the result option name. Better Try this...
There isn't a built-in "PowerShell" way of running a SQL query. If you have the SQL Server tools installed, you'll get an Invoke-SqlCmd cmdlet.
Because PowerShell is built on .NET, you can use the ADO.NET API to run your queries.
%lu
for unsigned long%llu
for unsigned long longYou could use alias python="/usr/bin/python2.7"
:
bash-3.2$ alias
bash-3.2$ python
Python 2.7.6 (v2.7.6:3a1db0d2747e, Nov 10 2013, 00:42:54)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> ^D
bash-3.2$ alias python="/usr/bin/python3.3"
bash-3.2$ python
Python 3.3.3 (v3.3.3:c3896275c0f6, Nov 16 2013, 23:39:35)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
jQuery has a toggleClass function:
<button class="switch">Click me</button>
<div class="text-block collapsed pressed">some text</div>
<script>
$('.switch').on('click', function(e) {
$('.text-block').toggleClass("collapsed pressed"); //you can list several class names
e.preventDefault();
});
</script>
If you wanted to stay with a class level selector then you could do something like this (using the same jfiddle from Mahn)
$("div.fetch_results input:text").each(function() {
this.value = "testing";
})?
This will select only the text input boxes within the div with a fetch_results class.
As with any jQuery this is just one way to do it. Ask 10 jQuery people this question and you will get 12 answers.
You can try VbsEdit. Get the latest version from Adersoft's VbsEdit http://www.vbsedit.com its a small download but it is a powerful tool to create and edit vbs files and convert them into executables without unpacking to temporary folder. (unless you get an old version like version 4.x.x.x) I've been using this program since 2008, and it's free to evaluate forever but comes with a reminder to activate and each time you Start your script from the vbsedit window you will have to wait a few seconds, Or you could purchase it for $60 to remove those minor annoyances.
Unlike ScriptCryptor, the converted exe won't have any limitations if you are still evaluating, it will run without any unwanted additional windows.
Replace -ggdb with -g and make sure you aren't stripping the binary with the strip command.
string(byteslice) will convert byte slice to string, just know that it's not only simply type conversion, but also memory copy.
Use Array.prototype.map()
with an arrow function:
const arrayColumn = (arr, n) => arr.map(x => x[n]);_x000D_
_x000D_
const twoDimensionalArray = [_x000D_
[1, 2, 3],_x000D_
[4, 5, 6],_x000D_
[7, 8, 9],_x000D_
];_x000D_
_x000D_
console.log(arrayColumn(twoDimensionalArray, 0));
_x000D_
Note: Array.prototype.map()
and arrow functions are part of ECMAScript 6 and not supported everywhere, see ECMAScript 6 compatibility table.
As far as I know you can only join this way:
var query = from obj_i in set1
join obj_j in set2 on
new {
JoinProperty1 = obj_i.SomeField1,
JoinProperty2 = obj_i.SomeField2,
JoinProperty3 = obj_i.SomeField3,
JoinProperty4 = obj_i.SomeField4
}
equals
new {
JoinProperty1 = obj_j.SomeOtherField1,
JoinProperty2 = obj_j.SomeOtherField2,
JoinProperty3 = obj_j.SomeOtherField3,
JoinProperty4 = obj_j.SomeOtherField4
}
The main requirements are: Property names, types and order in the anonymous objects you're joining on must match.
You CAN'T use ANDs, ORs, etc. in joins. Just object1 equals object2.
More advanced stuff in this LinqPad example:
class c1
{
public int someIntField;
public string someStringField;
}
class c2
{
public Int64 someInt64Property {get;set;}
private object someField;
public string someStringFunction(){return someField.ToString();}
}
void Main()
{
var set1 = new List<c1>();
var set2 = new List<c2>();
var query = from obj_i in set1
join obj_j in set2 on
new {
JoinProperty1 = (Int64) obj_i.someIntField,
JoinProperty2 = obj_i.someStringField
}
equals
new {
JoinProperty1 = obj_j.someInt64Property,
JoinProperty2 = obj_j.someStringFunction()
}
select new {obj1 = obj_i, obj2 = obj_j};
}
Addressing names and property order is straightforward, addressing types can be achieved via casting/converting/parsing/calling methods etc. This might not always work with LINQ to EF or SQL or NHibernate, most method calls definitely won't work and will fail at run-time, so YMMV (Your Mileage May Vary). This is because they are copied to public read-only properties in the anonymous objects, so as long as your expression produces values of correct type the join property - you should be fine.
Here are the significant differences between lateinit var
and by lazy { ... }
delegated property:
lazy { ... }
delegate can only be used for val
properties, whereas lateinit
can only be applied to var
s, because it can't be compiled to a final
field, thus no immutability can be guaranteed;
lateinit var
has a backing field which stores the value, and by lazy { ... }
creates a delegate object in which the value is stored once calculated, stores the reference to the delegate instance in the class object and generates the getter for the property that works with the delegate instance. So if you need the backing field present in the class, use lateinit
;
In addition to val
s, lateinit
cannot be used for nullable properties or Java primitive types (this is because of null
used for uninitialized value);
lateinit var
can be initialized from anywhere the object is seen from, e.g. from inside a framework code, and multiple initialization scenarios are possible for different objects of a single class. by lazy { ... }
, in turn, defines the only initializer for the property, which can be altered only by overriding the property in a subclass. If you want your property to be initialized from outside in a way probably unknown beforehand, use lateinit
.
Initialization by lazy { ... }
is thread-safe by default and guarantees that the initializer is invoked at most once (but this can be altered by using another lazy
overload). In the case of lateinit var
, it's up to the user's code to initialize the property correctly in multi-threaded environments.
A Lazy
instance can be saved, passed around and even used for multiple properties. On contrary, lateinit var
s do not store any additional runtime state (only null
in the field for uninitialized value).
If you hold a reference to an instance of Lazy
, isInitialized()
allows you to check whether it has already been initialized (and you can obtain such instance with reflection from a delegated property). To check whether a lateinit property has been initialized, you can use property::isInitialized
since Kotlin 1.2.
A lambda passed to by lazy { ... }
may capture references from the context where it is used into its closure.. It will then store the references and release them only once the property has been initialized. This may lead to object hierarchies, such as Android activities, not being released for too long (or ever, if the property remains accessible and is never accessed), so you should be careful about what you use inside the initializer lambda.
Also, there's another way not mentioned in the question: Delegates.notNull()
, which is suitable for deferred initialization of non-null properties, including those of Java primitive types.
Just to add a very performant and handy numba alternative based on np.ndenumerate
to find the first index:
from numba import njit
import numpy as np
@njit
def index(array, item):
for idx, val in np.ndenumerate(array):
if val == item:
return idx
# If no item was found return None, other return types might be a problem due to
# numbas type inference.
This is pretty fast and deals naturally with multidimensional arrays:
>>> arr1 = np.ones((100, 100, 100))
>>> arr1[2, 2, 2] = 2
>>> index(arr1, 2)
(2, 2, 2)
>>> arr2 = np.ones(20)
>>> arr2[5] = 2
>>> index(arr2, 2)
(5,)
This can be much faster (because it's short-circuiting the operation) than any approach using np.where
or np.nonzero
.
However np.argwhere
could also deal gracefully with multidimensional arrays (you would need to manually cast it to a tuple and it's not short-circuited) but it would fail if no match is found:
>>> tuple(np.argwhere(arr1 == 2)[0])
(2, 2, 2)
>>> tuple(np.argwhere(arr2 == 2)[0])
(5,)
While we can't say if some tablets omit "mobile", many including the Samsung Galaxy Tab do have mobile in their user-agent, making it impossible to detect between an android tablet and android phone without resorting to checking model specifics. This IMHO is a waste of time unless you plan on updating and expanding your device list on a monthly basis.
Unfortunately the best solution here is to complain to Google about this and get them to fix Chrome for Android so it adds some text to identify between a mobile device and a tablet. Hell even a single letter M OR T in a specific place in the string would be enough, but I guess that makes too much sense.
A very simple example:
SET a=Hello
SET b=World
SET c=%a% %b%!
echo %c%
The result should be:
Hello World!
input[type=checkbox]
{
/* Double-sized Checkboxes */
-ms-transform: scale(2); /* IE */
-moz-transform: scale(2); /* FF */
-webkit-transform: scale(2); /* Safari and Chrome */
-o-transform: scale(2); /* Opera */
padding: 10px;
}
I didn't want to have so many lines of code just to play a simple damn sound. This can work if you have the JavaFX package (already included in my jdk 8).
private static void playSound(String sound){
// cl is the ClassLoader for the current class, ie. CurrentClass.class.getClassLoader();
URL file = cl.getResource(sound);
final Media media = new Media(file.toString());
final MediaPlayer mediaPlayer = new MediaPlayer(media);
mediaPlayer.play();
}
Notice : You need to initialize JavaFX. A quick way to do that, is to call the constructor of JFXPanel() once in your app :
static{
JFXPanel fxPanel = new JFXPanel();
}
There is jq
for parsing json on the command line:
jq '.Body'
Visit this for jq: https://stedolan.github.io/jq/
For those of you, who are still facing this. I got this problem after I upgraded to Android Studio to 2.1.2. I was stuck at this problem for about an hour, I tried these solutions:
I double checked the gradle scripts and found this:
compileSdkVersion 23
buildToolsVersion "24.0.0"
changed to:
compileSdkVersion 23
buildToolsVersion "23.0.3"
I don't know how this caused the error, but this did the trick for me. Please let me know how this worked if you know the answer. Thanks
You need to catch the return value.
The DateTime.AddDays method returns an object who's value is the sum of the date and time of the instance and the added value.
endDate = endDate.AddDays(addedDays);
With Hibernate you can create your own UserType. So thats what I did for this issue. Something as simple as this:
public class BytesType implements org.hibernate.usertype.UserType {
private final int[] SQL_TYPES = new int[] { java.sql.Types.VARBINARY };
//...
}
There of course is more to implement from extending your own UserType but I just wanted to throw that out there for anyone looking for other methods.
I felt like replying as well, explaining the same thing as the others a bit differently. I am sure you know most of this, but it might help someone else.
<a href="#" class="view">
The
href="#"
part is a commonly used way to make sure the link doesn't lead anywhere on it's own. the #-attribute is used to create a link to some other section in the same document. For example clicking a link of this kind:
<a href="#news">Go to news</a>
will take you to wherever you have the
<a name="news"></a>
code. So if you specify # without any name like in your case, the link leads nowhere.
The
class="view"
part gives it an identifier that CSS or javascript can use. Inside the CSS-files (if you have any) you will find specific styling procedures on all the elements tagged with the "view"-class.
To find out where the URL is specified I would look in the javascript code. It is either written directly in the same document or included from another file.
Search your source code for something like:
<script type="text/javascript"> bla bla bla </script>
or
<script> bla bla bla </script>
and then search for any reference to your "view"-class. An included javascript file can look something like this:
<script type="text/javascript" src="include/javascript.js"></script>
In that case, open javascript.js under the "include" folder and search in that file. Most commonly the includes are placed between <head>
and </head>
or close to the </body>
-tag.
A faster way to find the link is to search for the actual link it goes to. For example, if you are directed to http://www.google.com/search?q=html when you click it, search for "google.com" or something in all the files you have in your web project, just remember the included files.
In many text editors you can open all the files at once, and then search in them all for something.
Answear taken from Php manual strtotime function comments :
echo date( "Y-m-d", strtotime( "2009-01-31 -1 day"));
Or
$date = "2009-01-31";
echo date( "Y-m-d", strtotime( $date . "-1 day"));
Hi This is the way to solve CORS problem in node Just add these lines on server "api" side in Node.js(or what ever your server File), befor that make sure to install "cors"
const express = require('express');
const app = express();
app.use(express.json());
var cors = require('cors');
app.use(cors());
Don't forget the two (()) 'brackets' around columns names.Otherwise, it'll give you an error.
# here you can add below line and it should work
df = df[list(('Mid','Upper', 'Lower', 'Net','Zsore'))]
df
Mid Upper Lower Net Zsore
Answer option
More than once a day 2 0.22% -0.12% 0% 65
Once a day 3 0.32% -0.19% 0% 45
Several times a week 4 2.45% 1.10% 2% 78
Once a week 6 1.63% -0.40% 1% 65
You can cast it to
(<any>$('.selector') ).function();
Ex: date picker initialize using jquery
(<any>$('.datepicker') ).datepicker();
Try
var ts = TimeSpan.Parse(stringTime);
With a newer .NET you also have
TimeSpan ts;
if(!TimeSpan.TryParse(stringTime, out ts)){
// throw exception or whatnot
}
// ts now has a valid format
This is the general idiom for parsing strings in .NET with the first version handling erroneous string by throwing FormatException and the latter letting the Boolean TryParse give you the information directly.
Put and Patch method are similar . But in rails it has different metod If we want to update/replace whole record then we have to use Put method. If we want to update particular record use Patch method.
You should remove .Value
from all option buttons because option buttons don't hold the resultant value, the option group control does. If you omit .Value
then the default interface will report the option button status, as you are expecting. You should write all relevant code under commandbutton_click events because whenever the commandbutton is clicked the option button action will run.
If you want to run action code when the optionbutton is clicked then don't write an if loop for that.
EXAMPLE:
Sub CommandButton1_Click
If OptionButton1 = true then
(action code...)
End if
End sub
Sub OptionButton1_Click
(action code...)
End sub
Try git rebase -i master
on your feature branch. You can then change all but one 'pick' to 'squash' to combine the commits. See squashing commits with rebase
Finally, you can then do the merge from master branch.
Emulation is a multi-faceted area. Here are the basic ideas and functional components. I'm going to break it into pieces and then fill in the details via edits. Many of the things I'm going to describe will require knowledge of the inner workings of processors -- assembly knowledge is necessary. If I'm a bit too vague on certain things, please ask questions so I can continue to improve this answer.
Emulation works by handling the behavior of the processor and the individual components. You build each individual piece of the system and then connect the pieces much like wires do in hardware.
There are three ways of handling processor emulation:
With all of these paths, you have the same overall goal: execute a piece of code to modify processor state and interact with 'hardware'. Processor state is a conglomeration of the processor registers, interrupt handlers, etc for a given processor target. For the 6502, you'd have a number of 8-bit integers representing registers: A
, X
, Y
, P
, and S
; you'd also have a 16-bit PC
register.
With interpretation, you start at the IP
(instruction pointer -- also called PC
, program counter) and read the instruction from memory. Your code parses this instruction and uses this information to alter processor state as specified by your processor. The core problem with interpretation is that it's very slow; each time you handle a given instruction, you have to decode it and perform the requisite operation.
With dynamic recompilation, you iterate over the code much like interpretation, but instead of just executing opcodes, you build up a list of operations. Once you reach a branch instruction, you compile this list of operations to machine code for your host platform, then you cache this compiled code and execute it. Then when you hit a given instruction group again, you only have to execute the code from the cache. (BTW, most people don't actually make a list of instructions but compile them to machine code on the fly -- this makes it more difficult to optimize, but that's out of the scope of this answer, unless enough people are interested)
With static recompilation, you do the same as in dynamic recompilation, but you follow branches. You end up building a chunk of code that represents all of the code in the program, which can then be executed with no further interference. This would be a great mechanism if it weren't for the following problems:
These combine to make static recompilation completely infeasible in 99% of cases. For more information, Michael Steil has done some great research into static recompilation -- the best I've seen.
The other side to processor emulation is the way in which you interact with hardware. This really has two sides:
Certain platforms -- especially older consoles like the NES, SNES, etc -- require your emulator to have strict timing to be completely compatible. With the NES, you have the PPU (pixel processing unit) which requires that the CPU put pixels into its memory at precise moments. If you use interpretation, you can easily count cycles and emulate proper timing; with dynamic/static recompilation, things are a /lot/ more complex.
Interrupts are the primary mechanism that the CPU communicates with hardware. Generally, your hardware components will tell the CPU what interrupts it cares about. This is pretty straightforward -- when your code throws a given interrupt, you look at the interrupt handler table and call the proper callback.
There are two sides to emulating a given hardware device:
Take the case of a hard-drive. The functionality is emulated by creating the backing storage, read/write/format routines, etc. This part is generally very straightforward.
The actual interface of the device is a bit more complex. This is generally some combination of memory mapped registers (e.g. parts of memory that the device watches for changes to do signaling) and interrupts. For a hard-drive, you may have a memory mapped area where you place read commands, writes, etc, then read this data back.
I'd go into more detail, but there are a million ways you can go with it. If you have any specific questions here, feel free to ask and I'll add the info.
I think I've given a pretty good intro here, but there are a ton of additional areas. I'm more than happy to help with any questions; I've been very vague in most of this simply due to the immense complexity.
It's been well over a year since this answer was submitted and with all the attention it's been getting, I figured it's time to update some things.
Perhaps the most exciting thing in emulation right now is libcpu, started by the aforementioned Michael Steil. It's a library intended to support a large number of CPU cores, which use LLVM for recompilation (static and dynamic!). It's got huge potential, and I think it'll do great things for emulation.
emu-docs has also been brought to my attention, which houses a great repository of system documentation, which is very useful for emulation purposes. I haven't spent much time there, but it looks like they have a lot of great resources.
I'm glad this post has been helpful, and I'm hoping I can get off my arse and finish up my book on the subject by the end of the year/early next year.
My attempt:
using System.IO;
static class PathUtils
{
public static string IsValidFullPath([NotNull] string fullPath)
{
if (string.IsNullOrWhiteSpace(fullPath))
return "Path is null, empty or white space.";
bool pathContainsInvalidChars = fullPath.IndexOfAny(Path.GetInvalidPathChars()) != -1;
if (pathContainsInvalidChars)
return "Path contains invalid characters.";
string fileName = Path.GetFileName(fullPath);
if (fileName == "")
return "Path must contain a file name.";
bool fileNameContainsInvalidChars = fileName.IndexOfAny(Path.GetInvalidFileNameChars()) != -1;
if (fileNameContainsInvalidChars)
return "File name contains invalid characters.";
if (!Path.IsPathRooted(fullPath))
return "The path must be absolute.";
return "";
}
}
This is not perfect because Path.GetInvalidPathChars
does not return the complete set of characters that are invalid in file and directory names and of course there's plenty more subtleties.
So I use this method as a complement:
public static bool TestIfFileCanBeCreated([NotNull] string fullPath)
{
if (string.IsNullOrWhiteSpace(fullPath))
throw new ArgumentException("Value cannot be null or whitespace.", "fullPath");
string directoryName = Path.GetDirectoryName(fullPath);
if (directoryName != null) Directory.CreateDirectory(directoryName);
try
{
using (new FileStream(fullPath, FileMode.CreateNew)) { }
File.Delete(fullPath);
return true;
}
catch (IOException)
{
return false;
}
}
It tries to create the file and return false if there is an exception. Of course, I need to create the file but I think it's the safest way to do that. Please also note that I am not deleting directories that have been created.
You can also use the first method to do basic validation, and then handle carefully the exceptions when the path is used.
You must write schema name and table name in qutotation mark. As below:
select * from "schemaName"."tableName";
For other types, check out the types module:
>>> import types
>>> x = "mystring"
>>> isinstance(x, types.StringType)
True
>>> x = 5
>>> isinstance(x, types.IntType)
True
>>> x = None
>>> isinstance(x, types.NoneType)
True
P.S. Typechecking is a bad idea.
For python, there is PDFMiner and pyPDF2. For more information on these, see Python module for converting PDF to text.
Well if anyone is interresting on how to replace an object from its index in an array, here's a solution.
Find the index of the object by its id:
const index = items.map(item => item.id).indexOf(objectId)
Replace the object using Object.assign() method:
Object.assign(items[index], newValue)
You can put dimens.xml
in
1) values
2) values-hdpi
3) values-xhdpi
4) values-xxhdpi
And give different sizes in dimens.xml
within corresponding folders according to densities.
In SQL Server 2016 SSMS expand 'DATABASNAME' > expand 'SECURITY' > expand 'SCHEMA' ; right click 'SCHEMAS' from the popup left click 'NEW SCHEMAS...' add the name on the window that opens and add an owner i.e dbo click 'OK' button
You need to install the provisioning profile (drag and drop it into iTunes). Then drag and drop the .ipa. Ensure you device is set to sync apps, and try again.
You mention the certificate is self-signed (by you)? Then you have two choices:
cacert.pem
from cURL website won't do anything, since it's self-signed)Here's a list of SSL context options in PHP: https://secure.php.net/manual/en/context.ssl.php
Set allow_self_signed
if you import your certificate into your trust store, or set verify_peer
to false to skip verification.
The reason why we trust a specific certificate is because we trust its issuer. Since your certificate is self-signed, no client will trust the certificate as the signer (you) is not trusted. If you created your own CA when signing the certificate, you can add the CA to your trust store. If your certificate doesn't contain any CA, then you can't expect anyone to connect to your server.
If you just want to get the path to a certain action, use UrlHelper
:
UrlHelper u = new UrlHelper(this.ControllerContext.RequestContext);
string url = u.Action("About", "Home", null);
if you want to create a hyperlink:
string link = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, System.Web.Routing.RouteTable.Routes, "My link", "Root", "About", "Home", null, null);
Intellisense will give you the meaning of each of the parameters.
Update from comments: controller already has a UrlHelper
:
string url = this.Url.Action("About", "Home", null);
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
public class JavaYoutubeDownloader {
public static String newline = System.getProperty("line.separator");
private static final Logger log = Logger.getLogger(JavaYoutubeDownloader.class.getCanonicalName());
private static final Level defaultLogLevelSelf = Level.FINER;
private static final Level defaultLogLevel = Level.WARNING;
private static final Logger rootlog = Logger.getLogger("");
private static final String scheme = "http";
private static final String host = "www.youtube.com";
private static final Pattern commaPattern = Pattern.compile(",");
private static final Pattern pipePattern = Pattern.compile("\\|");
private static final char[] ILLEGAL_FILENAME_CHARACTERS = { '/', '\n', '\r', '\t', '\0', '\f', '`', '?', '*', '\\', '<', '>', '|', '\"', ':' };
private static void usage(String error) {
if (error != null) {
System.err.println("Error: " + error);
}
System.err.println("usage: JavaYoutubeDownload VIDEO_ID DESTINATION_DIRECTORY");
System.exit(-1);
}
public static void main(String[] args) {
if (args == null || args.length == 0) {
usage("Missing video id. Extract from http://www.youtube.com/watch?v=VIDEO_ID");
}
try {
setupLogging();
log.fine("Starting");
String videoId = null;
String outdir = ".";
// TODO Ghetto command line parsing
if (args.length == 1) {
videoId = args[0];
} else if (args.length == 2) {
videoId = args[0];
outdir = args[1];
}
int format = 18; // http://en.wikipedia.org/wiki/YouTube#Quality_and_codecs
String encoding = "UTF-8";
String userAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13";
File outputDir = new File(outdir);
String extension = getExtension(format);
play(videoId, format, encoding, userAgent, outputDir, extension);
} catch (Throwable t) {
t.printStackTrace();
}
log.fine("Finished");
}
private static String getExtension(int format) {
// TODO
return "mp4";
}
private static void play(String videoId, int format, String encoding, String userAgent, File outputdir, String extension) throws Throwable {
log.fine("Retrieving " + videoId);
List<NameValuePair> qparams = new ArrayList<NameValuePair>();
qparams.add(new BasicNameValuePair("video_id", videoId));
qparams.add(new BasicNameValuePair("fmt", "" + format));
URI uri = getUri("get_video_info", qparams);
CookieStore cookieStore = new BasicCookieStore();
HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(uri);
httpget.setHeader("User-Agent", userAgent);
log.finer("Executing " + uri);
HttpResponse response = httpclient.execute(httpget, localContext);
HttpEntity entity = response.getEntity();
if (entity != null && response.getStatusLine().getStatusCode() == 200) {
InputStream instream = entity.getContent();
String videoInfo = getStringFromInputStream(encoding, instream);
if (videoInfo != null && videoInfo.length() > 0) {
List<NameValuePair> infoMap = new ArrayList<NameValuePair>();
URLEncodedUtils.parse(infoMap, new Scanner(videoInfo), encoding);
String token = null;
String downloadUrl = null;
String filename = videoId;
for (NameValuePair pair : infoMap) {
String key = pair.getName();
String val = pair.getValue();
log.finest(key + "=" + val);
if (key.equals("token")) {
token = val;
} else if (key.equals("title")) {
filename = val;
} else if (key.equals("fmt_url_map")) {
String[] formats = commaPattern.split(val);
for (String fmt : formats) {
String[] fmtPieces = pipePattern.split(fmt);
if (fmtPieces.length == 2) {
// in the end, download somethin!
downloadUrl = fmtPieces[1];
int pieceFormat = Integer.parseInt(fmtPieces[0]);
if (pieceFormat == format) {
// found what we want
downloadUrl = fmtPieces[1];
break;
}
}
}
}
}
filename = cleanFilename(filename);
if (filename.length() == 0) {
filename = videoId;
} else {
filename += "_" + videoId;
}
filename += "." + extension;
File outputfile = new File(outputdir, filename);
if (downloadUrl != null) {
downloadWithHttpClient(userAgent, downloadUrl, outputfile);
}
}
}
}
private static void downloadWithHttpClient(String userAgent, String downloadUrl, File outputfile) throws Throwable {
HttpGet httpget2 = new HttpGet(downloadUrl);
httpget2.setHeader("User-Agent", userAgent);
log.finer("Executing " + httpget2.getURI());
HttpClient httpclient2 = new DefaultHttpClient();
HttpResponse response2 = httpclient2.execute(httpget2);
HttpEntity entity2 = response2.getEntity();
if (entity2 != null && response2.getStatusLine().getStatusCode() == 200) {
long length = entity2.getContentLength();
InputStream instream2 = entity2.getContent();
log.finer("Writing " + length + " bytes to " + outputfile);
if (outputfile.exists()) {
outputfile.delete();
}
FileOutputStream outstream = new FileOutputStream(outputfile);
try {
byte[] buffer = new byte[2048];
int count = -1;
while ((count = instream2.read(buffer)) != -1) {
outstream.write(buffer, 0, count);
}
outstream.flush();
} finally {
outstream.close();
}
}
}
private static String cleanFilename(String filename) {
for (char c : ILLEGAL_FILENAME_CHARACTERS) {
filename = filename.replace(c, '_');
}
return filename;
}
private static URI getUri(String path, List<NameValuePair> qparams) throws URISyntaxException {
URI uri = URIUtils.createURI(scheme, host, -1, "/" + path, URLEncodedUtils.format(qparams, "UTF-8"), null);
return uri;
}
private static void setupLogging() {
changeFormatter(new Formatter() {
@Override
public String format(LogRecord arg0) {
return arg0.getMessage() + newline;
}
});
explicitlySetAllLogging(Level.FINER);
}
private static void changeFormatter(Formatter formatter) {
Handler[] handlers = rootlog.getHandlers();
for (Handler handler : handlers) {
handler.setFormatter(formatter);
}
}
private static void explicitlySetAllLogging(Level level) {
rootlog.setLevel(Level.ALL);
for (Handler handler : rootlog.getHandlers()) {
handler.setLevel(defaultLogLevelSelf);
}
log.setLevel(level);
rootlog.setLevel(defaultLogLevel);
}
private static String getStringFromInputStream(String encoding, InputStream instream) throws UnsupportedEncodingException, IOException {
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(instream, encoding));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
instream.close();
}
String result = writer.toString();
return result;
}
}
/**
* <pre>
* Exploded results from get_video_info:
*
* fexp=90...
* allow_embed=1
* fmt_stream_map=35|http://v9.lscache8...
* fmt_url_map=35|http://v9.lscache8...
* allow_ratings=1
* keywords=Stefan Molyneux,Luke Bessey,anarchy,stateless society,giant stone cow,the story of our unenslavement,market anarchy,voluntaryism,anarcho capitalism
* track_embed=0
* fmt_list=35/854x480/9/0/115,34/640x360/9/0/115,18/640x360/9/0/115,5/320x240/7/0/0
* author=lukebessey
* muted=0
* length_seconds=390
* plid=AA...
* ftoken=null
* status=ok
* watermark=http://s.ytimg.com/yt/swf/logo-vfl_bP6ud.swf,http://s.ytimg.com/yt/swf/hdlogo-vfloR6wva.swf
* timestamp=12...
* has_cc=False
* fmt_map=35/854x480/9/0/115,34/640x360/9/0/115,18/640x360/9/0/115,5/320x240/7/0/0
* leanback_module=http://s.ytimg.com/yt/swfbin/leanback_module-vflJYyeZN.swf
* hl=en_US
* endscreen_module=http://s.ytimg.com/yt/swfbin/endscreen-vflk19iTq.swf
* vq=auto
* avg_rating=5.0
* video_id=S6IZP3yRJ9I
* token=vPpcFNh...
* thumbnail_url=http://i4.ytimg.com/vi/S6IZP3yRJ9I/default.jpg
* title=The Story of Our Unenslavement - Animated
* </pre>
*/
I solved this problem using the split npm module. Pipe your stream into split, and it will "Break up a stream and reassemble it so that each line is a chunk".
Sample code:
var fs = require('fs')
, split = require('split')
;
var stream = fs.createReadStream(filePath, {flags: 'r', encoding: 'utf-8'});
var lineStream = stream.pipe(split());
linestream.on('data', function(chunk) {
var json = JSON.parse(chunk);
// ...
});
I wanted to keep a few recent stashes, but delete everything else.
Because all stashes get renumbered when you drop one, this is actually easy to do with while. To delete all stashes older than stash@{19}:
while git stash drop 'stash@{20}'; do true; done
To use a specific key on the fly:
GIT_SSH_COMMAND='ssh -i $HOME/.ssh/id_ed25519 -o IdentitiesOnly=yes -F /dev/null' git push origin c13_training_network
Explanation:
-i
specifies key-F
forces an empty config so your global one doesn't overwrite this temporary commandExplanation with an example.
1. import java.io.Serializable
As for the Serialization, see the documentation.
2. private fields
Fields should be private for prevent outer classes to easily modify those fields. Instead of directly accesing to those fields, usuagly getter/setter methods are used.
3. Constructor
A public constructor without any argument.
4. getter/setter
Getter and setter methods for accessing and modifying private fields.
/** 1. import java.io.Serializable */
public class User implements java.io.Serializable {
/** 2. private fields */
private int id;
private String name;
/** 3. Constructor */
public User() {
}
public User(int id, String name) {
this.id = id;
this.name = name;
}
/** 4. getter/setter */
// getter
public int getId() {
return id;
}
public String getName() {
return name;
}
// setter
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
}
You still have access to StreamWriter
:
using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"\hereIam.txt"))
{
file.WriteLine(sb.ToString()); // "sb" is the StringBuilder
}
From the MSDN documentation: Writing to a Text File (Visual C#).
For newer versions of the .NET Framework (Version 2.0. onwards), this can be achieved with one line using the File.WriteAllText
method.
System.IO.File.WriteAllText(@"C:\TextFile.txt", stringBuilder.ToString());
Some things to check:
Can you change to unrestricted?
Set-ExecutionPolicy Unrestricted
Is the group policy set?
Computer Configuration\Administrative Templates\Windows Components\Windows PowerShell
User Configuration\Administrative Templates\Windows Components\Windows PowerShell
Also, how are you calling Script.ps1?
Does this allow it to run?
powershell.exe -executionpolicy bypass -file .\Script.ps1
switch(position) {
case 0:
...
break;
case 1:
...
break;
default:
...
}
Did you mean that?
This page has a very simple example of calling functions from a DLL file.
Paraphrasing the details here for completeness:
It's very easy to call a DLL function in Python. I have a self-made DLL file with two functions:
add
andsub
which take two arguments.
add(a, b)
returns addition of two numbers
sub(a, b)
returns substraction of two numbersThe name of the DLL file will be "demo.dll"
Program:
from ctypes import*
# give location of dll
mydll = cdll.LoadLibrary("C:\\demo.dll")
result1= mydll.add(10,1)
result2= mydll.sub(10,1)
print "Addition value:"+result1
print "Substraction:"+result2
Output:
Addition value:11
Substraction:9
little complete sample:
using System.ComponentModel;
private bool bShowGroup ;
[Description("Show the group table"), Category("Sea"),DefaultValue(true)]
public bool ShowGroup
{
get { return bShowGroup; }
set { bShowGroup = value; }
}
One advantage of FTP is that there is a standard way to list files using dir
or ls
. Because of this, ftp plays nice with tools such as rsync. Granted, rsync
is usually done over ssh
, but the option is there.
with express it's so easy. all what you need is to use the consolidate module on node so you need to install it :
npm install consolidate --save
then you should change the default engine to html template by this:
app.set('view engine', 'html');
register the underscore template engine for the html extension:
app.engine('html', require('consolidate').underscore);
it's done !
Now for load for example an template called 'index.html':
res.render('index', { title : 'my first page'});
maybe you will need to install the underscore module.
npm install underscore --save
I hope this helped you!
In addition to using pure threads or the Celery queue (note that flask-celery is no longer required), you could also have a look at flask-apscheduler:
https://github.com/viniciuschiele/flask-apscheduler
A simple example copied from https://github.com/viniciuschiele/flask-apscheduler/blob/master/examples/jobs.py:
from flask import Flask
from flask_apscheduler import APScheduler
class Config(object):
JOBS = [
{
'id': 'job1',
'func': 'jobs:job1',
'args': (1, 2),
'trigger': 'interval',
'seconds': 10
}
]
SCHEDULER_API_ENABLED = True
def job1(a, b):
print(str(a) + ' ' + str(b))
if __name__ == '__main__':
app = Flask(__name__)
app.config.from_object(Config())
scheduler = APScheduler()
# it is also possible to enable the API directly
# scheduler.api_enabled = True
scheduler.init_app(app)
scheduler.start()
app.run()
Tweaking MB's answer for windows, will get rid of the console window:
start javaw -jar squirrel-sql.jar
If you're in Windows & using MSVC, the MSDN library has sample code that does this.
And here's the code from that link:
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <strsafe.h>
void ErrorHandler(LPTSTR lpszFunction);
int _tmain(int argc, TCHAR *argv[])
{
WIN32_FIND_DATA ffd;
LARGE_INTEGER filesize;
TCHAR szDir[MAX_PATH];
size_t length_of_arg;
HANDLE hFind = INVALID_HANDLE_VALUE;
DWORD dwError=0;
// If the directory is not specified as a command-line argument,
// print usage.
if(argc != 2)
{
_tprintf(TEXT("\nUsage: %s <directory name>\n"), argv[0]);
return (-1);
}
// Check that the input path plus 2 is not longer than MAX_PATH.
StringCchLength(argv[1], MAX_PATH, &length_of_arg);
if (length_of_arg > (MAX_PATH - 2))
{
_tprintf(TEXT("\nDirectory path is too long.\n"));
return (-1);
}
_tprintf(TEXT("\nTarget directory is %s\n\n"), argv[1]);
// Prepare string for use with FindFile functions. First, copy the
// string to a buffer, then append '\*' to the directory name.
StringCchCopy(szDir, MAX_PATH, argv[1]);
StringCchCat(szDir, MAX_PATH, TEXT("\\*"));
// Find the first file in the directory.
hFind = FindFirstFile(szDir, &ffd);
if (INVALID_HANDLE_VALUE == hFind)
{
ErrorHandler(TEXT("FindFirstFile"));
return dwError;
}
// List all the files in the directory with some info about them.
do
{
if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
_tprintf(TEXT(" %s <DIR>\n"), ffd.cFileName);
}
else
{
filesize.LowPart = ffd.nFileSizeLow;
filesize.HighPart = ffd.nFileSizeHigh;
_tprintf(TEXT(" %s %ld bytes\n"), ffd.cFileName, filesize.QuadPart);
}
}
while (FindNextFile(hFind, &ffd) != 0);
dwError = GetLastError();
if (dwError != ERROR_NO_MORE_FILES)
{
ErrorHandler(TEXT("FindFirstFile"));
}
FindClose(hFind);
return dwError;
}
void ErrorHandler(LPTSTR lpszFunction)
{
// Retrieve the system error message for the last-error code
LPVOID lpMsgBuf;
LPVOID lpDisplayBuf;
DWORD dw = GetLastError();
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0, NULL );
// Display the error message and exit the process
lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT,
(lstrlen((LPCTSTR)lpMsgBuf)+lstrlen((LPCTSTR)lpszFunction)+40)*sizeof(TCHAR));
StringCchPrintf((LPTSTR)lpDisplayBuf,
LocalSize(lpDisplayBuf) / sizeof(TCHAR),
TEXT("%s failed with error %d: %s"),
lpszFunction, dw, lpMsgBuf);
MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Error"), MB_OK);
LocalFree(lpMsgBuf);
LocalFree(lpDisplayBuf);
}
There is a batch file called resetroot.bat
located in the xammp folders 'C:\xampp\mysql' run this and it will delete the phpmyadmin
passwords. Then all you need to do is start the MySQL
service in xamp
and click the admin button.
$(document).ready(function() {
$(".tab").click(function () {
if(!$(this).hasClass('active'))
{
$(".tab.active").removeClass("active");
$(this).addClass("active");
}
});
});
# Preface: File is json with contents: {'name': 'Android', 'status': 'ERROR'}
import boto3
import io
s3 = boto3.resource('s3')
obj = s3.Object('my-bucket', 'key-to-file.json')
data = io.BytesIO()
obj.download_fileobj(data)
# object is now a bytes string, Converting it to a dict:
new_dict = json.loads(data.getvalue().decode("utf-8"))
print(new_dict['status'])
# Should print "Error"
Can you provide an example, because put should work fine as well?
Documentation -
The type of request to make ("POST" or "GET"); the default is "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.
Have the example in fiddle and the form parameters are passed fine (as it is put it will not be appended to url
) -
$.ajax({
url: '/echo/html/',
type: 'PUT',
data: "name=John&location=Boston",
success: function(data) {
alert('Load was performed.');
}
});
Demo tested from jQuery 1.3.2 onwards on Chrome.
Though many of the above answers serve the purpose, there is one straight forward thing we can do in project itself.
In Eclipse, go to Window->Preferences, select "Android" from left side menu. On the right panel you will see "SDK Location". Provide the path here.
Good luck.
A popular Linux library which has similar functionality would be ncurses.
I'll never easily remember these cryptic command modifiers so I took the top answer and turned it into a function in my ~/.bashrc
file:
cgrep() {
# For files that are arrays 10's of thousands of characters print.
# Use cpgrep to print 30 characters before and after search patttern.
if [ $# -eq 2 ] ; then
# Format was 'cgrep "search string" /path/to/filename'
grep -o -P ".{0,30}$1.{0,30}" "$2"
else
# Format was 'cat /path/to/filename | cgrep "search string"
grep -o -P ".{0,30}$1.{0,30}"
fi
} # cgrep()
Here's what it looks like in action:
$ ll /tmp/rick/scp.Mf7UdS/Mf7UdS.Source
-rw-r--r-- 1 rick rick 25780 Jul 3 19:05 /tmp/rick/scp.Mf7UdS/Mf7UdS.Source
$ cat /tmp/rick/scp.Mf7UdS/Mf7UdS.Source | cgrep "Link to iconic"
1:43:30.3540244000 /mnt/e/bin/Link to iconic S -rwxrwxrwx 777 rick 1000 ri
$ cgrep "Link to iconic" /tmp/rick/scp.Mf7UdS/Mf7UdS.Source
1:43:30.3540244000 /mnt/e/bin/Link to iconic S -rwxrwxrwx 777 rick 1000 ri
The file in question is one continuous 25K line and it is hopeless to find what you are looking for using regular grep
.
Notice the two different ways you can call cgrep
that parallels grep
method.
There is a "niftier" way of creating the function where "$2" is only passed when set which would save 4 lines of code. I don't have it handy though. Something like ${parm2} $parm2
. If I find it I'll revise the function and this answer.
This link shows how to edit the eclipse workspace metadata to update the project's location manually, useful if the location has already changed or you have a lot of projects to move and don't want to do several clicks and waits for each one: https://web.archive.org/web/20160421171614/http://www.joeflash.ca/blog/2008/11/moving-a-fb-workspace-update.html
This builds on the answer by CMS by removing any non-alphabetic characters including underscores, which \w
does not remove.
function toLowerCamelCase(str) {
return str.replace(/[^A-Za-z0-9]/g, ' ').replace(/^\w|[A-Z]|\b\w|\s+/g, function (match, index) {
if (+match === 0 || match === '-' || match === '.' ) {
return ""; // or if (/\s+/.test(match)) for white spaces
}
return index === 0 ? match.toLowerCase() : match.toUpperCase();
});
}
toLowerCamelCase("EquipmentClass name");
toLowerCamelCase("Equipment className");
toLowerCamelCase("equipment class name");
toLowerCamelCase("Equipment Class Name");
toLowerCamelCase("Equipment-Class-Name");
toLowerCamelCase("Equipment_Class_Name");
toLowerCamelCase("Equipment.Class.Name");
toLowerCamelCase("Equipment/Class/Name");
// All output e
If you know the package name, then this works without using a try-catch block or iterating through a bunch of packages:
public static boolean isPackageInstalled(Context context, String packageName) {
final PackageManager packageManager = context.getPackageManager();
Intent intent = packageManager.getLaunchIntentForPackage(packageName);
if (intent == null) {
return false;
}
List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
return !list.isEmpty();
}
It is situational.
The Android documentation suggests that you should use AlarmManager to register an Intent that will fire at the specified time if your application may not be running.
Otherwise, you should use Handler.
Note: The Alarm Manager is intended for cases where you want to have your application code run at a specific time, even if your application is not currently running. For normal timing operations (ticks, timeouts, etc) it is easier and much more efficient to use Handler.
Include the content in {! <content> !}
.
As theon noted, REST is not a standard. However, if you are looking to implement a standards based URI convention, you might consider the oData URI convention. Ver 4 has been approved as an OASIS standard and libraries exists for oData for various languages including Java via Apache Olingo. Don't let the fact that it's a spawn from Microsoft put you off since it's gained support from other industry player's as well, which include Red Hat, Citrix, IBM, Blackberry, Drupal, Netflix Facebook and SAP
One use of reinterpret_cast is if you want to apply bitwise operations to (IEEE 754) floats. One example of this was the Fast Inverse Square-Root trick:
https://en.wikipedia.org/wiki/Fast_inverse_square_root#Overview_of_the_code
It treats the binary representation of the float as an integer, shifts it right and subtracts it from a constant, thereby halving and negating the exponent. After converting back to a float, it's subjected to a Newton-Raphson iteration to make this approximation more exact:
float Q_rsqrt( float number )
{
long i;
float x2, y;
const float threehalfs = 1.5F;
x2 = number * 0.5F;
y = number;
i = * ( long * ) &y; // evil floating point bit level hacking
i = 0x5f3759df - ( i >> 1 ); // what the deuce?
y = * ( float * ) &i;
y = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration
// y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed
return y;
}
This was originally written in C, so uses C casts, but the analogous C++ cast is the reinterpret_cast.
call your (windows-)git with cygpath
as parameter, in order to convert the "calling path". I m confused why that should be a problem.
Well, according to Google's lectures (maybe here, I don't remember) , you should consider using Fragments whenever it's possible, as it makes your code easier to maintain and control.
However, I think that on some cases it can get too complex, as the activity that hosts the fragments need to navigate/communicate between them.
I think you should decide by yourself what's best for you. It's usually not that hard to convert an activity to a fragment and vice versa.
I've created a post about this dillema here, if you wish to read some further.
Class.forName() gives you the class object, which is useful for reflection. The methods that this object has are defined by Java, not by the programmer writing the class. They are the same for every class. Calling newInstance() on that gives you an instance of that class (i.e. calling Class.forName("ExampleClass").newInstance()
it is equivalent to calling new ExampleClass()
), on which you can call the methods that the class defines, access the visible fields etc.
When I was managing a large multi-user planning system backed by Oracle, our DBA had a weekly job that gathered statistics. Also, when we rolled out a significant change that could affect or be affected by statistics, we would force the job to run out of cycle to get things caught up.
Set your Textbox value in a string like:
string MySTring = textBox1.Text;
Then replace your string. For example, replace "Text" with "Hex":
MyString = MyString.Replace("Text", "Hex");
Or for your problem (replace "," with ;) :
MyString = MyString.Replace(@""",""", ",");
Note: If you have "" in your string you have to use @ in the back of "", like:
@"","";
This can be done using ServerSocket, same as on JavaSE. This class is available on Android. android.permission.INTERNET
is required.
The only more tricky part, you need a separate thread wait on the ServerSocket, servicing sub-sockets that come from its accept
method. You also need to stop and resume this thread as needed. The simplest approach seems to kill the waiting thread by closing the ServerSocket.
If you only need a server while your activity is on the top, starting and stopping ServerSocket thread can be rather elegantly tied to the activity life cycle methods. Also, if the server has multiple users, it may be good to service requests in the forked threads. If there is only one user, this may not be necessary.
If you need to tell the user on which IP is the server listening,use NetworkInterface.getNetworkInterfaces(), this question may tell extra tricks.
Finally, here there is possibly the complete minimal Android server that is very short, simple and may be easier to understand than finished end user applications, recommended in other answers.
Based on Laravel docs for raw queries I was able to get count for a select field to work with this code in the product model.
public function scopeShowProductCount($query)
{
$query->select(DB::raw('DISTINCT pid, COUNT(*) AS count_pid'))
->groupBy('pid')
->orderBy('count_pid', 'desc');
}
This facade worked to get the same result in the controller:
$products = DB::table('products')->select(DB::raw('DISTINCT pid, COUNT(*) AS count_pid'))->groupBy('pid')->orderBy('count_pid', 'desc')->get();
The resulting dump for both queries was as follows:
#attributes: array:2 [
"pid" => "1271"
"count_pid" => 19
],
#attributes: array:2 [
"pid" => "1273"
"count_pid" => 12
],
#attributes: array:2 [
"pid" => "1275"
"count_pid" => 7
]
Personally I would like to use regular expression here. Bellow code perfectly worked for me.
$baseUrl = url('/'); // for my case https://www.xrepeater.com
$posted_url = "home";
// Test with one by one
/*$posted_url = "/home";
$posted_url = "xrepeater.com";
$posted_url = "www.xrepeater.com";
$posted_url = "http://www.xrepeater.com";
$posted_url = "https://www.xrepeater.com";
$posted_url = "https://xrepeater.com/services";
$posted_url = "xrepeater.dev/home/test";
$posted_url = "home/test";*/
$regularExpression = "((https?|ftp)\:\/\/)?"; // SCHEME Check
$regularExpression .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)?"; // User and Pass Check
$regularExpression .= "([a-z0-9-.]*)\.([a-z]{2,3})"; // Host or IP Check
$regularExpression .= "(\:[0-9]{2,5})?"; // Port Check
$regularExpression .= "(\/([a-z0-9+\$_-]\.?)+)*\/?"; // Path Check
$regularExpression .= "(\?[a-z+&\$_.-][a-z0-9;:@&%=+\/\$_.-]*)?"; // GET Query String Check
$regularExpression .= "(#[a-z_.-][a-z0-9+\$_.-]*)?"; // Anchor Check
if(preg_match("/^$regularExpression$/i", $posted_url)) {
if(preg_match("@^http|https://@i",$posted_url)) {
$final_url = preg_replace("@(http://)+@i",'http://',$posted_url);
// return "*** - ***Match : ".$final_url;
}
else {
$final_url = 'http://'.$posted_url;
// return "*** / ***Match : ".$final_url;
}
}
else {
if (substr($posted_url, 0, 1) === '/') {
// return "*** / ***Not Match :".$final_url."<br>".$baseUrl.$posted_url;
$final_url = $baseUrl.$posted_url;
}
else {
// return "*** - ***Not Match :".$posted_url."<br>".$baseUrl."/".$posted_url;
$final_url = $baseUrl."/".$final_url; }
}
You can do:
for(String key: hashMap.keySet()){
for(String value: hashMap.get(key)) {
// use the value here
}
}
This will iterate over every key, and then every value of the list associated with each key.
Second code example is much more proper way to do this because you are taking full control of data which are given to class
.
There are cases in which the __set
and __get
are useful but not in this case.
In my case, I recently changed my windows password and I have SSH key configured for git related actions (pull, push, fetch etc.,), after I encountered the "fatal: Authentication failed" error, I updated my password in the windows credential manager (Control Panel\User Accounts\Credential Manager)for all items starting with git:..., and tried again, worked this time!
The general approach to this is to:
main()
.main()
.A hint: look at System.nanoTime()
or System.currentTimeMillis()
.
Try This:
$(document).on('click', '#btnClick', function(){ _x000D_
alert("button is clicked");_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button id="btnClick">Click me</button>
_x000D_
Other posts here have made it clear that the result is an "empty" IQueryable, which ToList() will correctly change to be an empty list etc.
Do be careful with some of the operators, as they will throw if you send them an empty enumerable. This can happen when you chain them together.
You can use Microsoft.Extensions.Configuration API with any .NET Core app, not only with ASP.NET Core app. Look into sample provided in the link, that shows how to read configs in the console app.
In most cases, the JSON source (read as .json
file) is the most suitable config source.
Note: don't be confused when someone says that config file should be
appsettings.json
. You can use any file name, that is suitable for you and file location may be different - there are no specific rules.
But, as the real world is complicated, there are a lot of different configuration providers:
and so on. You even could use/write a custom provider.
Actually, app.config
configuration file was an XML file. So you can read settings from it using XML configuration provider (source on github, nuget link). But keep in mind, it will be used only as a configuration source - any logic how your app behaves should be implemented by you. Configuration Provider will not change 'settings' and set policies for your apps, but only read data from the file.
When working with bootsrap usually face three main problems:
To solve first two problems download this small plugin https://github.com/codekipple/conformity
The third problem is solved here http://www.minimit.com/articles/solutions-tutorials/bootstrap-3-responsive-centered-columns
<style>
[class*=col-] {position: relative}
.row-conformity .to-bottom {position:absolute; bottom:0; left:0; right:0}
.row-centered {text-align:center}
.row-centered [class*=col-] {display:inline-block; float:none; text-align:left; margin-right:-4px; vertical-align:top}
</style>
<script src="assets/conformity/conformity.js"></script>
<script>
$(document).ready(function () {
$('.row-conformity > [class*=col-]').conformity();
$(window).on('resize', function() {
$('.row-conformity > [class*=col-]').conformity();
});
});
</script>
<div class="row row-conformity">
<div class="col-sm-3">
I<br>create<br>highest<br>column
</div>
<div class="col-sm-3">
<div class="to-bottom">
I am on the bottom
</div>
</div>
</div>
<div class="row row-conformity">
<div class="col-sm-4">We all have equal height</div>
<div class="col-sm-4">...</div>
<div class="col-sm-4">...</div>
<div class="col-sm-4">...</div>
<div class="col-sm-4">...</div>
<div class="col-sm-4">...</div>
</div>
<div class="row row-centered">
<div class="col-sm-3">...</div>
<div class="col-sm-4">...</div>
</div>
<div class="row row-conformity row-centered">
...
</div>
I solved my problem of visual svn server rep-cache.db corruption.
Their are two solutions.
Stop the Visual SVN Server service.
Download sqllite3.exe shell from sqllite website and copy that into repo's db folder.
Type the following commands at command prompt in the repo's db folder.
-- First Solution --
sqlite3 rep-cache.db
.clone rep-cache-new.db
press ctrl+c to exit sqllite.
ren rep-cache.db rep-cache-old.db
ren re-cache-new.db rep-cache.db
-- 2nd Solution --
Delete The rep-cache.db
del rep-cache.db
it will be automatically created.
Try pass array to vector:
int arr[] = {2,5,8,11,14};
std::vector<int> TestVector(arr, arr+5);
You could always call std::vector::assign to assign array to vector, call std::vector::insert to add multiple arrays.
If you use C++11, you can try:
std::vector<int> v{2,5,8,11,14};
Or
std::vector<int> v = {2,5,8,11,14};