how to make Google search using c++ program - c++

I am wondering and almost searched everywhere on the web but couldn't find anything helpful. I am quite a beginner with c++. Is there any possible way to make a Web search when I type a word in console on program runtime, it should go to google.com and fetch the meaning of that word to my .txt file or directly on my console? Basically, I am trying to implement a dictionary (offline+Online) using c++ and linked lists/trees.
Any sort of help will be much appreciated.

There is a couple of steps to this that you may need to do before you even start writing the C++ code.
Note: C++ is probably not the easiest language to do this in.
You will need a google account.
Go to the website and sign up (free)
You will need to get an API Key
Go to the website and generate (free)
You will need to know the REST command to generate output.
Here the easiest thing to do is to use CURL to test your REST query (or use a tool like PostMan). Though their website provides a simple starting point to test parameters.
Once you have the rest command working on the command line. Convert this to C code using the libcurl API.
You will need to parse the returned value.
The returned value is JSON you will need to either parse this manually or use an existing library. There are several out there. I hear jsoncpp is good I prefer ThorsSerializer but I wrote that so I am biased.
Making a dictionary (non commercial).
Its probably simpler to use the MERRIAM-WEBSTER'S API rather than googles.
Step 1: Register to get an API Key
https://dictionaryapi.com/register/index
Step 2: Get The API Key
Once you have filled out the form.
And confirmed your e-mail
And Logged into dictionaryapi.com
Go to your keys page
Step 3: Verify you can get information from the command line
Documentation here
Note: My key is not going to work for you (I deleted it). You will have to create and use your own.
curl https://www.dictionaryapi.com/api/v3/references/collegiate/json/voluminous?key=568e93fa-c06f-4f96-bf12-948cf301a03f
Step 4: Convert the command line into C code.
#include <string>
#include <iostream>
#include <curl/curl.h>
extern "C" size_t write_callback(char *ptr, size_t size, size_t nmemb, void *dataFromServerVoid)
{
std::string& dataFromServer = *(reinterpret_cast<std::string*>(dataFromServerVoid));
dataFromServer.append(ptr, size * nmemb);
return size * nmemb;
}
int main(int argc, char* argv[])
{
if (argc < 2) {
std::cerr << "Fail: Read Instructions\n";
return -1;
}
std::cout << "Dictionary:\n"
<< " Getting: " << argv[1] << "\n";
CURL* curl = curl_easy_init();
if (curl)
{
static const std::string apiKey = "?key=568e93fa-c06f-4f96-bf12-948cf301a03f";
static const std::string urlBase = "https://www.dictionaryapi.com/api/v3/references/collegiate/json/";
const std::string url = urlBase + argv[1] + apiKey;
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
// The default action is to print any data returned
// to the standard output. But we are going to need to
// processes that data so adding some functions
// and data to capture the output.
std::string dataFromServer;
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &dataFromServer);
// Get the data from the server.
CURLcode res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
// If the call worked we can print out
// what we retrieved.
if (res == CURLE_OK) {
std::cout << " Got: >" << dataFromServer << "<\n";
}
}
}
Step 5: Build and verify it works.
> g++ -std=c++17 dict.cpp -lcurl
> ./a.out bootstrap
We get:
Dictionary:
Getting: bootstrap
Got: >[{"meta":{"id":"bootstrap:1","uuid":"9c960ec2-a3ce-4f09-a7ba-a4972036314a","sort":"020350800","src":"collegiate","section":"alpha","stems":["bootstrap","bootstraps"],"offensive":false},"hom":1,"hwi":{"hw":"boot*strap","prs":[{"mw":"\u02c8b\u00fct-\u02ccstrap","sound":{"audio":"bootst01","ref":"c","stat":"1"}}]},"fl":"noun","def":[{"sseq":[[["sense",{"sn":"1","dt":[["text","{bc}a looped strap sewed at the side or the rear top of a boot to help in pulling it on"]]}]],[["sense",{"sn":"2","ins":[{"if":"boot*straps","spl":"plural"}],"dt":[["text","{bc}unaided efforts "],["uns",[[["text","often used in the phrase {it}by one\u0027s own bootstraps{\/it}"]]]]]}]]]}],"date":"1875{ds||1||}","shortdef":["a looped strap sewed at the side or the rear top of a boot to help in pulling it on","unaided efforts \u2014often used in the phrase by one\u0027s own bootstraps"]},{"meta":{"id":"bootstrap:2","uuid":"59331df1-c1fd-44ff-bd8d-73d471ad6819","sort":"020350900","src":"collegiate","section":"alpha","stems":["bootstrap"],"offensive":false},"hom":2,"hwi":{"hw":"bootstrap"},"fl":"adjective","def":[{"sseq":[[["sense",{"sn":"1","dt":[["text","{bc}designed to function independently of outside direction {bc}capable of using one internal function or process to control another "],["vis",[{"t":"a {wi}bootstrap{\/wi} operation to load a computer"}]]]}]],[["sense",{"sn":"2","dt":[["text","{bc}carried out with minimum resources or advantages "],["vis",[{"t":"{wi}bootstrap{\/wi} efforts"}]]]}]]]}],"date":"1926{ds||1||}","shortdef":["designed to function independently of outside direction : capable of using one internal function or process to control another","carried out with minimum resources or advantages"]},{"meta":{"id":"bootstrap:3","uuid":"257edd7e-c31a-453a-a15b-e1d022c70d96","sort":"020351000","src":"collegiate","section":"alpha","stems":["bootstrap","bootstrapped","bootstrapper","bootstrappers","bootstrapping","bootstraps"],"offensive":false},"hom":3,"hwi":{"hw":"bootstrap"},"fl":"verb","ins":[{"if":"boot*strapped"},{"if":"boot*strap*ping"}],"def":[{"vd":"transitive verb","sseq":[[["sense",{"dt":[["text","{bc}to promote or develop by initiative and effort with little or no assistance "],["vis",[{"t":"{it}bootstrapped{\/it} herself to the top"},{"t":"\u2026 turns out to be pretty talented at identifying and {wi}bootstrapping{\/wi} promising creative endeavors.","aq":{"auth":"Harry McCracken"}}]]]}]]]}],"uros":[{"ure":"boot*strap*per","fl":"noun"}],"date":"1951","shortdef":["to promote or develop by initiative and effort with little or no assistance"]}]<
Step 6: Extract the data from the JSON
I am going to use ThorsSerializer to get the data. This allows de-serialization of JSON directly into C++ objects without having to parse and interpret any intermediate objects. This makes it really usefull for stable web interfaces (like most REST interfaces).
Step 6a: Install ThorsSerializer
> brew install thors-serializer
A useful tip here. To visualize and quickly see the JSON there is a great command line tool jq. if you stream JSON to this the default action is simply to prity print the JSON (though it has a lot more power)
> brew install jq
> echo "<JSON TEXT>" | jq
Step 6b: Build Definition of what you want:
Looking at the definition of JSON we only need one bit of data "shortdef" which is an array of strings inside a definition object.
// So simply declare an object like the JSON declaraition.
// You can ignore any parts of the JSON you don't want.
struct Definition
{
std::vector<std::string> shortdef;
};
// Now tell the ThorsSerializer the bits it needs to understand.
// The library already knows how to handle all the standard types.
// So no extra declarations needed for std::vector.
ThorsAnvil_MakeTrait(Definition, shortdef);
Step 6C: Write code to extract data from JSON.
using ThorsAnvil::Serialize::jsonImporter;
std::stringstream dataFromServerStream(dataFromServer);
std::vector<Definition> definition;
// ThorsSerializer works for any type of stream.
// Files are supported natively and its not hard
// to wrap sockets as a stream if you want to.
// In this case I have kept it simple.
dataFromServerStream >> jsonImporter(definition);
Step 6c: Put it all together:
#include <vector>
#include <string>
#include <iostream>
#include <curl/curl.h>
#include "ThorSerialize/Traits.h"
#include "ThorSerialize/JsonThor.h"
extern "C" size_t write_callback(char *ptr, size_t size, size_t nmemb, void *dataFromServerVoid)
{
std::string& dataFromServer = *(reinterpret_cast<std::string*>(dataFromServerVoid));
dataFromServer.append(ptr, size * nmemb);
return size * nmemb;
}
struct Definition
{
std::vector<std::string> shortdef;
};
ThorsAnvil_MakeTrait(Definition, shortdef);
int main(int argc, char* argv[])
{
if (argc < 2) {
std::cerr << "Fail: Read Instructions\n";
return -1;
}
std::cout << "Dictionary:\n"
<< "Getting: " << argv[1] << "\n";
CURL* curl = curl_easy_init();
if (curl)
{
static const std::string apiKey = "?key=568e93fa-c06f-4f96-bf12-948cf301a03f";
static const std::string urlBase = "https://www.dictionaryapi.com/api/v3/references/collegiate/json/";
const std::string url = urlBase + argv[1] + apiKey;
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
std::string dataFromServer;
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &dataFromServer);
CURLcode res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
if (res == CURLE_OK) {
using ThorsAnvil::Serialize::jsonImporter;
std::stringstream dataFromServerStream(dataFromServer);
std::vector<Definition> definition;
dataFromServerStream >> jsonImporter(std::move(definition));
for(auto def: definition[0].shortdef) {
std::cout << " " << def << "\n";
}
}
}
}
Step 7: Build
g++ -std=c++17 main2.cpp -lcurl -lThorSerialize17 -lThorsLogging17
> ./a.out bootstrap
We get:
Dictionary:
Getting: bootstrap
a looped strap sewed at the side or the rear top of a boot to help in pulling it on
unaided efforts —often used in the phrase by one's own bootstraps
Just as a comparison.
The same code in Javascript. Now my javascript is not good. But this code is still tighter and more readable. So this shows that C++ is not the best language to do this as a beginner.
const fetch = require('node-fetch');
const apiKey = "?key=568e93fa-c06f-4f96-bf12-948cf301a03f";
const urlBase = "https://www.dictionaryapi.com/api/v3/references/collegiate/json/";
const url = urlBase + process.argv[2] + apiKey;
fetch(url)
.then(res => res.json())
.then((definition) => {
for(var item in definition[0].shortdef) {
console.log(definition[0].shortdef[item]);
}
})
.catch(err => { throw err });
To run this:
> node dict.js bootstrap
But saying that. If you find an appropriate library this code can be just as concise as the Javascript. But you need an appropriate library (which may be difficult and hard to find/build and install). All of which are made easy with javascript.
Example of simple version:
#include <vector>
#include <string>
#include <iostream>
#include "ThorSerialize/Traits.h"
#include "ThorSerialize/JsonThor.h"
#include "ThorSocketStream/ThorsSimpleStream.h"
struct Definition
{
std::vector<std::string> shortdef;
};
ThorsAnvil_MakeTrait(Definition, date, shortdef);
int main(int argc, char* argv[])
{
using ThorsAnvil::Stream::IThorSimpleStream;
using ThorsAnvil::Serialize::jsonImporter;
static const std::string apiKey = "?key=key=568e93fa-c06f-4f96-bf12-948cf301a03f";
static const std::string urlBase = "https://www.dictionaryapi.com/api/v3/references/collegiate/json/";
const std::string url = urlBase + argv[1] + apiKey;
IThorSimpleStream stream(url);
std::vector<Definition> dataFromServer;
stream >> jsonImporter(dataFromServer)
for(auto const& def: dataFromServer[0].shortdef) {
std::cout << " " << data << "\n";
}
}
But getting the SimpleStream library may take some work to build.

Related

Read text multiple times with Elementary access on native Tizen TV

Hello fellow programmers,
I am trying to use the Text To Speech functionality provided by the Elementary access library (from Enlightenment) in a native app for tizen TV.
So far I have been able to read text, but only once: when I call the API multiple times, only the first call is rendered to audio.
I have investigated the sources of elementary access, but can't really spot the problem.
Here is a sample of my app:
#include <app.h>
#include <Elementary.h>
#include <unistd.h>
#include <string>
using namespace std;
const char APP_PKG[] = "org.tizen.tts";
/// Struct to store application information and passed at start time to the efl framework
struct _appdata
{
const char *name;
Evas_Object *win;
};
static bool
_create(void *data)
{
elm_config_access_set(EINA_TRUE);
return true;
}
static bool
_control(app_control_h app_control, void *data)
{
for (int i = 1; i <= 2; i++) {
string text = to_string(i) + ". Read me please.";
elm_access_say(text.c_str());
// sleep(10);
}
return true;
}
int
main(int argc, char *argv[])
{
_appdata ad = {0,};
ad.name = APP_PKG;
ui_app_lifecycle_callback_s lifecycle_callback = {0,};
lifecycle_callback.create = _create;
lifecycle_callback.app_control = _control;
return ui_app_main(argc, argv, &lifecycle_callback, &ad);
}
I have tried using elm_access_force_say, also moving elm_config_access_set(EINA_TRUE) inside the loop, but everytime the sentence is only said once.
Here in the source is some code called by elm_access_say. It seems that the api makes a call to espeak executable, strangely I can't find any espeak executable on the device.
Tizen provides an API for using the TTS engine in native apps, but only for mobile and watches (at least in the documentation).
If someone ever tried to use the TTS engine on native TV, or have more experience with the Elementary access library, and would like to share some knowledge, I would be really thankful.
If you are using Tizen 4.0 or above and you want to read text multiple times using accessibility framework, please use the elm_atspi_bridge_utils_say. Below code snippet demonstrates how to read consecutive numbers.
statc void reade_n_times(int n) {
char buf[32];
for (int i=1;i<=n;++i){
snprintf(bug,sizesizeof(buf), "%d", i);
elm_atspi_bridge_utils_say(buf, EINA_FALSE, say_cb, NULL);
}
}
Full specification of elm_atspi_bridge_utils_say can be found here:
https://developer.tizen.org/dev-guide/tizen-iot-headed/4.0/group__Elm__Atspi__Bridge.html#gafde6945c1451cb8752c67f2aa871d12d "
Use this page for 4.0 Wearable API Reference. API Reference of tizen-iot-headed is not up-to-date.
https://docs.tizen.org/application/native/api/mobile/4.0/group__Elm__Atspi__Bridge.html

Nodejs: How to start a node application from a c++ program [duplicate]

I want to use Node.js scripts in my C/C++ applications. Some people suggested me to start with v8, libev and libeio; but it means rewriting Node.js from scratch.
So, is it possible to embed Node.js into C or C++?
You should first consider whether it would be sufficient to implement your application as a C++ module for Node and then glue the main part as a Node script.
Otherwise you may wish to "re-implement Node", by taking the core code as the example and
removing the parts which you don't need (e.g. HTTP module) and then putting your components
into it. The least painful way would be to do a sub-tree merge and ripping-out the build system, then adding prefixes in the build scripts to point to the directory where it lives.
Then you can stop certain parts from being built. However Node's build system contains several parts and it may be quite a difficult job to do.
You can also try re-packaging Node with your stuff loaded by default and changing the name of the executable. However, that is just a more complex way of taking the first approach I have described, you can just install a script in /usr/bin/ which will go as:
#!/usr/bin/node
var myAppMain = require('libmyApp');
myAppMain.withConfig(filename,
function(err, cnf) {
if (err) throw err; // parser or file access error
cnf.evalMe();
});
You can use a JSlint as your parser, then grep for dangerous calls and then eval(conf_script) or just use require(config.js), though you will need to add exports.someMethod = function (...) {...}. But require() is much safer in general, however you may wish to implement a pre-processor for your config which will substitute exports.someMethod = function (...) {...} instead of your functions and will append require('OnlyCallMySafeMethods') and reject any
attempts to require('fs') or other lib which you may be afraid of letting the someone to use.
This sort of safety is just an optional thing you may wish to have, it's all up to you really.
Though I suppose you might want to do the bit with exports.someMethod = .... substitution and have one require('myAppConfigLib) added on the top so the user will just use you API plus anything they may wish to put into their script/config!
UPDATE: There is a quite useful comment on line 66 of src/node.js:
// To allow people to extend Node in different ways, this hook allows
// one to drop a file lib/_third_party_main.js into the build
// directory which will be executed instead of Node's normal loading.
Please also note that the contents of src/ are being compiled to bytecode at build time.
Embedding Node.JS is now officially supported by a Node.JS fork JXcore. Embedding docs are available from this link.
I've build something close to what I think you're looking for:
https://github.com/ZECTBynmo/tacnode
It's a library that allows node.js to be linked statically into a C++ application. It's definitely not polished, but I've used it to launch simple node scripts.
The official documentation has a page explaining how how to embed Node.js into C++. This has been around since Node 12.x.
There is a full example in the Node repo. Reproduced below for convenience:
#ifdef NDEBUG
#undef NDEBUG
#endif
#include "node.h"
#include "uv.h"
#include <assert.h>
// Note: This file is being referred to from doc/api/embedding.md, and excerpts
// from it are included in the documentation. Try to keep these in sync.
// Snapshot support is not part of the embedder API docs yet due to its
// experimental nature, although it is of course documented in node.h.
using node::CommonEnvironmentSetup;
using node::Environment;
using node::MultiIsolatePlatform;
using v8::Context;
using v8::HandleScope;
using v8::Isolate;
using v8::Locker;
using v8::MaybeLocal;
using v8::V8;
using v8::Value;
static int RunNodeInstance(MultiIsolatePlatform* platform,
const std::vector<std::string>& args,
const std::vector<std::string>& exec_args);
int main(int argc, char** argv) {
argv = uv_setup_args(argc, argv);
std::vector<std::string> args(argv, argv + argc);
std::unique_ptr<node::InitializationResult> result =
node::InitializeOncePerProcess(
args,
{node::ProcessInitializationFlags::kNoInitializeV8,
node::ProcessInitializationFlags::kNoInitializeNodeV8Platform});
for (const std::string& error : result->errors())
fprintf(stderr, "%s: %s\n", args[0].c_str(), error.c_str());
if (result->early_return() != 0) {
return result->exit_code();
}
std::unique_ptr<MultiIsolatePlatform> platform =
MultiIsolatePlatform::Create(4);
V8::InitializePlatform(platform.get());
V8::Initialize();
int ret =
RunNodeInstance(platform.get(), result->args(), result->exec_args());
V8::Dispose();
V8::DisposePlatform();
node::TearDownOncePerProcess();
return ret;
}
int RunNodeInstance(MultiIsolatePlatform* platform,
const std::vector<std::string>& args,
const std::vector<std::string>& exec_args) {
int exit_code = 0;
node::EmbedderSnapshotData::Pointer snapshot;
auto snapshot_build_mode_it =
std::find(args.begin(), args.end(), "--embedder-snapshot-create");
auto snapshot_arg_it =
std::find(args.begin(), args.end(), "--embedder-snapshot-blob");
auto snapshot_as_file_it =
std::find(args.begin(), args.end(), "--embedder-snapshot-as-file");
if (snapshot_arg_it < args.end() - 1 &&
snapshot_build_mode_it == args.end()) {
const char* filename = (snapshot_arg_it + 1)->c_str();
FILE* fp = fopen(filename, "r");
assert(fp != nullptr);
if (snapshot_as_file_it != args.end()) {
snapshot = node::EmbedderSnapshotData::FromFile(fp);
} else {
uv_fs_t req;
int statret = uv_fs_stat(nullptr, &req, filename, nullptr);
assert(statret == 0);
size_t filesize = req.statbuf.st_size;
uv_fs_req_cleanup(&req);
std::vector<char> vec(filesize);
size_t read = fread(vec.data(), filesize, 1, fp);
assert(read == 1);
snapshot = node::EmbedderSnapshotData::FromBlob(vec);
}
assert(snapshot);
int ret = fclose(fp);
assert(ret == 0);
}
std::vector<std::string> errors;
std::unique_ptr<CommonEnvironmentSetup> setup =
snapshot ? CommonEnvironmentSetup::CreateFromSnapshot(
platform, &errors, snapshot.get(), args, exec_args)
: snapshot_build_mode_it != args.end()
? CommonEnvironmentSetup::CreateForSnapshotting(
platform, &errors, args, exec_args)
: CommonEnvironmentSetup::Create(platform, &errors, args, exec_args);
if (!setup) {
for (const std::string& err : errors)
fprintf(stderr, "%s: %s\n", args[0].c_str(), err.c_str());
return 1;
}
Isolate* isolate = setup->isolate();
Environment* env = setup->env();
{
Locker locker(isolate);
Isolate::Scope isolate_scope(isolate);
HandleScope handle_scope(isolate);
Context::Scope context_scope(setup->context());
MaybeLocal<Value> loadenv_ret;
if (snapshot) {
loadenv_ret = node::LoadEnvironment(env, node::StartExecutionCallback{});
} else {
loadenv_ret = node::LoadEnvironment(
env,
// Snapshots do not support userland require()s (yet)
"if (!require('v8').startupSnapshot.isBuildingSnapshot()) {"
" const publicRequire ="
" require('module').createRequire(process.cwd() + '/');"
" globalThis.require = publicRequire;"
"} else globalThis.require = require;"
"globalThis.embedVars = { nön_ascıı: '🏳️‍🌈' };"
"require('vm').runInThisContext(process.argv[1]);");
}
if (loadenv_ret.IsEmpty()) // There has been a JS exception.
return 1;
exit_code = node::SpinEventLoop(env).FromMaybe(1);
}
if (snapshot_arg_it < args.end() - 1 &&
snapshot_build_mode_it != args.end()) {
snapshot = setup->CreateSnapshot();
assert(snapshot);
FILE* fp = fopen((snapshot_arg_it + 1)->c_str(), "w");
assert(fp != nullptr);
if (snapshot_as_file_it != args.end()) {
snapshot->ToFile(fp);
} else {
const std::vector<char> vec = snapshot->ToBlob();
size_t written = fwrite(vec.data(), vec.size(), 1, fp);
assert(written == 1);
}
int ret = fclose(fp);
assert(ret == 0);
}
node::Stop(env);
return exit_code;
}
It probably is, V8 is written in C++, node.js can run on V8, but unless you have an extremely good reason why you would run javascript through C++ you are probably much better served finding an appropriate C++ library and implementing the needed functionality directly in C++. The task of integrating scripting languages and native code is usually not trivial. E.g. V8 documentation. Qt offers a pretty decent integration between c++ and javascript and it still not trivial to move objects back and forth between script and code.
I was just checking out js-git which is made for Node.js and also depends on a few other Node.js modules.
However, the same developer wrote a tool tim-task to wrap up some common Node.js functions, most importantly require, and to pack together some Node.js modules in such a way that it should not depend on Node.js anymore. He used it to make git-web-platform, i.e. js-git packed as a JS file which can be used in browsers. The resulted packed file looks like this. This can probably also be used with minor modifications just in pure V8.
This might be useful for you. Note however that this approach will be limited.
There are many good reasons to embed node, including the ability to leverage npm.
Unfortunately JXCore is dying.
this artice gives some alternatives.
http://www.goland.org/nodeapps/

Redirect output of curl library function to image file

I am doing rotate operation on camera using CURL library.
Here is what I've done so far:
#include <iostream> // For std::cerr
#include <string> // For std::string,getline(),c_str()
#include <curl/curl.h> // For curl library functions like curl_easy_setopt,curl_easy_perform etc.
class camera_image_rotate {
CURL *curl = curl_easy_init();
std::string ipaddress,username,password,url;
int rotation;
CURLcode res;
public:
camera_image_rotate(int x) : rotation(x) {
std::cout<<"Enter ip address: ";
getline(std::cin,ipaddress);
std::cout<<"Enter username: ";
getline(std::cin,username);
username+=":";
std::cout<<username<<'\n';
std::cout<<"Enter password: ";
getline(std::cin,password);
password+="#";
std::cout<<password<<'\n';
ipaddress+="/axis-cgi/jpg/image.cgi?rotation=";
ipaddress+=std::to_string(rotation);
std::cout<<ipaddress<<'\n';
url=username+password+ipaddress;
}
void rotate() {
if(curl) {
res=curl_easy_setopt(curl,CURLOPT_URL,url.c_str());
res=curl_easy_perform(curl);
if(res!=CURLE_OK)
std::cerr<<"Oops, Invalid IP";
}
else {
std::cerr<<"Something went wrong";
}
}
~camera_image_rotate() {
if(res==CURLE_OK)
curl_easy_cleanup(curl);
}
};
int main() {
camera_image_rotate s(90);
s.rotate();
}
Now, the problem I am facing is that when I execute this program it tries to print the rotated image on console so I am getting some completely
unreadable output. So, I want to redirect the output of this program to either *.jpg or *.png file. How do I achieve that ? I've referred documentation
about CURL on their official site but I didn't find anything useful.
I am using ubuntu OS & clang++ 3.8.0 compiler.
You're probably looking for the CURLOPT_WRITEFUNCTION callback that gets called with all the data from the download. (A little piece at a time.)
In simpler cases you may also get away with the default write function and simply set CURLOPT_WRITEDATA to a file.
You may also find some additional understanding for how the callback works by looking at the examples, like getinmemory.c - that uses the callback to receive the entire contents of a transfer into memory.

C++ Http Request with POCO

I'm wondering how I can do a request to a URL (e.g. download a picture and save it) with POCO in C++?
I got this little code so far
#include <iostream>
#include <string>
#include "multiplication.h"
#include <vector>
#include <HTTPRequest.h>
using std::cout;
using std::cin;
using std::getline;
using namespace Poco;
using namespace Net;
int main() {
HTTPRequest *test = new HTTPRequest("HTTP_GET", "http://www.example.com", "HTTP/1.1");
}
Normally POCO has a great advantage to be very simple even when you know nothing about it and you do not need middle/advance C++ knowledge like you need for boost/asio ( e.g what means enable_share_from_this ... )
Under the poco "installation directory" you find the sample directory, (in my case under poco\poco-1.4.6p4\Net\samples\httpget\src ).
On-line help browsing is also easy and fast (for example browsing classes).
If your understanding of C++ in not enough at the present time go to the university library and borrow Scott Meyers books (Effective C++ and after More effective C++ )
So we adapt the sample code httpget.cpp to the minimal required.
Inside the main:
URI uri("http://pocoproject.org/images/front_banner.jpg");
std::string path(uri.getPathAndQuery());
if (path.empty()) path = "/";
HTTPClientSession session(uri.getHost(), uri.getPort());
HTTPRequest request(HTTPRequest::HTTP_GET, path, HTTPMessage::HTTP_1_1);
HTTPResponse response;
if (!doRequest(session, request, response))
{
std::cerr << "Invalid username or password" << std::endl;
return 1;
}
and the function almost untouched:
bool doRequest(Poco::Net::HTTPClientSession& session,
Poco::Net::HTTPRequest& request,
Poco::Net::HTTPResponse& response)
{
session.sendRequest(request);
std::istream& rs = session.receiveResponse(response);
std::cout << response.getStatus() << " " << response.getReason() << std::endl;
if (response.getStatus() != Poco::Net::HTTPResponse::HTTP_UNAUTHORIZED)
{
std::ofstream ofs("Poco_banner.jpg",std::fstream::binary);
StreamCopier::copyStream(rs, ofs);
return true;
}
else
{
//it went wrong ?
return false;
}
}
I let you arrange things for you and see where the image lands on your disk.
Hope it will help

How to embed Node.js interpreter into C/C++?

I want to use Node.js scripts in my C/C++ applications. Some people suggested me to start with v8, libev and libeio; but it means rewriting Node.js from scratch.
So, is it possible to embed Node.js into C or C++?
You should first consider whether it would be sufficient to implement your application as a C++ module for Node and then glue the main part as a Node script.
Otherwise you may wish to "re-implement Node", by taking the core code as the example and
removing the parts which you don't need (e.g. HTTP module) and then putting your components
into it. The least painful way would be to do a sub-tree merge and ripping-out the build system, then adding prefixes in the build scripts to point to the directory where it lives.
Then you can stop certain parts from being built. However Node's build system contains several parts and it may be quite a difficult job to do.
You can also try re-packaging Node with your stuff loaded by default and changing the name of the executable. However, that is just a more complex way of taking the first approach I have described, you can just install a script in /usr/bin/ which will go as:
#!/usr/bin/node
var myAppMain = require('libmyApp');
myAppMain.withConfig(filename,
function(err, cnf) {
if (err) throw err; // parser or file access error
cnf.evalMe();
});
You can use a JSlint as your parser, then grep for dangerous calls and then eval(conf_script) or just use require(config.js), though you will need to add exports.someMethod = function (...) {...}. But require() is much safer in general, however you may wish to implement a pre-processor for your config which will substitute exports.someMethod = function (...) {...} instead of your functions and will append require('OnlyCallMySafeMethods') and reject any
attempts to require('fs') or other lib which you may be afraid of letting the someone to use.
This sort of safety is just an optional thing you may wish to have, it's all up to you really.
Though I suppose you might want to do the bit with exports.someMethod = .... substitution and have one require('myAppConfigLib) added on the top so the user will just use you API plus anything they may wish to put into their script/config!
UPDATE: There is a quite useful comment on line 66 of src/node.js:
// To allow people to extend Node in different ways, this hook allows
// one to drop a file lib/_third_party_main.js into the build
// directory which will be executed instead of Node's normal loading.
Please also note that the contents of src/ are being compiled to bytecode at build time.
Embedding Node.JS is now officially supported by a Node.JS fork JXcore. Embedding docs are available from this link.
I've build something close to what I think you're looking for:
https://github.com/ZECTBynmo/tacnode
It's a library that allows node.js to be linked statically into a C++ application. It's definitely not polished, but I've used it to launch simple node scripts.
The official documentation has a page explaining how how to embed Node.js into C++. This has been around since Node 12.x.
There is a full example in the Node repo. Reproduced below for convenience:
#ifdef NDEBUG
#undef NDEBUG
#endif
#include "node.h"
#include "uv.h"
#include <assert.h>
// Note: This file is being referred to from doc/api/embedding.md, and excerpts
// from it are included in the documentation. Try to keep these in sync.
// Snapshot support is not part of the embedder API docs yet due to its
// experimental nature, although it is of course documented in node.h.
using node::CommonEnvironmentSetup;
using node::Environment;
using node::MultiIsolatePlatform;
using v8::Context;
using v8::HandleScope;
using v8::Isolate;
using v8::Locker;
using v8::MaybeLocal;
using v8::V8;
using v8::Value;
static int RunNodeInstance(MultiIsolatePlatform* platform,
const std::vector<std::string>& args,
const std::vector<std::string>& exec_args);
int main(int argc, char** argv) {
argv = uv_setup_args(argc, argv);
std::vector<std::string> args(argv, argv + argc);
std::unique_ptr<node::InitializationResult> result =
node::InitializeOncePerProcess(
args,
{node::ProcessInitializationFlags::kNoInitializeV8,
node::ProcessInitializationFlags::kNoInitializeNodeV8Platform});
for (const std::string& error : result->errors())
fprintf(stderr, "%s: %s\n", args[0].c_str(), error.c_str());
if (result->early_return() != 0) {
return result->exit_code();
}
std::unique_ptr<MultiIsolatePlatform> platform =
MultiIsolatePlatform::Create(4);
V8::InitializePlatform(platform.get());
V8::Initialize();
int ret =
RunNodeInstance(platform.get(), result->args(), result->exec_args());
V8::Dispose();
V8::DisposePlatform();
node::TearDownOncePerProcess();
return ret;
}
int RunNodeInstance(MultiIsolatePlatform* platform,
const std::vector<std::string>& args,
const std::vector<std::string>& exec_args) {
int exit_code = 0;
node::EmbedderSnapshotData::Pointer snapshot;
auto snapshot_build_mode_it =
std::find(args.begin(), args.end(), "--embedder-snapshot-create");
auto snapshot_arg_it =
std::find(args.begin(), args.end(), "--embedder-snapshot-blob");
auto snapshot_as_file_it =
std::find(args.begin(), args.end(), "--embedder-snapshot-as-file");
if (snapshot_arg_it < args.end() - 1 &&
snapshot_build_mode_it == args.end()) {
const char* filename = (snapshot_arg_it + 1)->c_str();
FILE* fp = fopen(filename, "r");
assert(fp != nullptr);
if (snapshot_as_file_it != args.end()) {
snapshot = node::EmbedderSnapshotData::FromFile(fp);
} else {
uv_fs_t req;
int statret = uv_fs_stat(nullptr, &req, filename, nullptr);
assert(statret == 0);
size_t filesize = req.statbuf.st_size;
uv_fs_req_cleanup(&req);
std::vector<char> vec(filesize);
size_t read = fread(vec.data(), filesize, 1, fp);
assert(read == 1);
snapshot = node::EmbedderSnapshotData::FromBlob(vec);
}
assert(snapshot);
int ret = fclose(fp);
assert(ret == 0);
}
std::vector<std::string> errors;
std::unique_ptr<CommonEnvironmentSetup> setup =
snapshot ? CommonEnvironmentSetup::CreateFromSnapshot(
platform, &errors, snapshot.get(), args, exec_args)
: snapshot_build_mode_it != args.end()
? CommonEnvironmentSetup::CreateForSnapshotting(
platform, &errors, args, exec_args)
: CommonEnvironmentSetup::Create(platform, &errors, args, exec_args);
if (!setup) {
for (const std::string& err : errors)
fprintf(stderr, "%s: %s\n", args[0].c_str(), err.c_str());
return 1;
}
Isolate* isolate = setup->isolate();
Environment* env = setup->env();
{
Locker locker(isolate);
Isolate::Scope isolate_scope(isolate);
HandleScope handle_scope(isolate);
Context::Scope context_scope(setup->context());
MaybeLocal<Value> loadenv_ret;
if (snapshot) {
loadenv_ret = node::LoadEnvironment(env, node::StartExecutionCallback{});
} else {
loadenv_ret = node::LoadEnvironment(
env,
// Snapshots do not support userland require()s (yet)
"if (!require('v8').startupSnapshot.isBuildingSnapshot()) {"
" const publicRequire ="
" require('module').createRequire(process.cwd() + '/');"
" globalThis.require = publicRequire;"
"} else globalThis.require = require;"
"globalThis.embedVars = { nön_ascıı: '🏳️‍🌈' };"
"require('vm').runInThisContext(process.argv[1]);");
}
if (loadenv_ret.IsEmpty()) // There has been a JS exception.
return 1;
exit_code = node::SpinEventLoop(env).FromMaybe(1);
}
if (snapshot_arg_it < args.end() - 1 &&
snapshot_build_mode_it != args.end()) {
snapshot = setup->CreateSnapshot();
assert(snapshot);
FILE* fp = fopen((snapshot_arg_it + 1)->c_str(), "w");
assert(fp != nullptr);
if (snapshot_as_file_it != args.end()) {
snapshot->ToFile(fp);
} else {
const std::vector<char> vec = snapshot->ToBlob();
size_t written = fwrite(vec.data(), vec.size(), 1, fp);
assert(written == 1);
}
int ret = fclose(fp);
assert(ret == 0);
}
node::Stop(env);
return exit_code;
}
It probably is, V8 is written in C++, node.js can run on V8, but unless you have an extremely good reason why you would run javascript through C++ you are probably much better served finding an appropriate C++ library and implementing the needed functionality directly in C++. The task of integrating scripting languages and native code is usually not trivial. E.g. V8 documentation. Qt offers a pretty decent integration between c++ and javascript and it still not trivial to move objects back and forth between script and code.
I was just checking out js-git which is made for Node.js and also depends on a few other Node.js modules.
However, the same developer wrote a tool tim-task to wrap up some common Node.js functions, most importantly require, and to pack together some Node.js modules in such a way that it should not depend on Node.js anymore. He used it to make git-web-platform, i.e. js-git packed as a JS file which can be used in browsers. The resulted packed file looks like this. This can probably also be used with minor modifications just in pure V8.
This might be useful for you. Note however that this approach will be limited.
There are many good reasons to embed node, including the ability to leverage npm.
Unfortunately JXCore is dying.
this artice gives some alternatives.
http://www.goland.org/nodeapps/