Flutter contacts_service package use - loops

I am using https://pub.dev/packages/contacts_service.
I am able to do:
contacts.forEach((contact){
print(contact.displayName);
});
How do I print items of contact.emails ?
They are defined as Iterable

Try this;
contacts.forEach((contact) {
print(contact.displayName);
contact.emails.forEach((item) {
print(item.value);
});
});

Emails are stored in a label: value format in that lib. This should work:
contacts.forEach((contact) {
print('Name: ${contact.displayName}');
for (var email in contact.emails) {
print('Email: ${email.label} => ${email.value}');
}
});

Related

NextJS Global Variable with Assignment

I'm new to NextJS, and trying to figure out, how to create a global variable that I could assign a different value anytime. Could someone give a simple example? (I know global might not be the best approach, but still I would like to know how to set up a global variable).
Let's say:
_app.js
NAME = "Ana" // GLOBAL VARIABLE
page_A.js
console.log(NAME) // "Ana"
NAME = "Ben"
page_B.js
console.log(NAME) // "Ben"
try using Environment Variables
/next.config.js
module.exports = {
env: {
customKey: 'my-value',
},
}
/pages/page_A.js
function Page() {
return <h1>The value of customKey is: {process.env.customKey}</h1>
}
export default Page
but you can not change its contents, except by changing it directly in next.config.js
Nextjs no special ways to provide global variables you want. You can achieve by:
Stateful management tool, like redux-react
Using Context
It's not like it's impossible,
I created a file called _customGlobals.jsx and put this as content
String.prototype.title = function () {
const sliced = this.slice(1);
return (
this.charAt(0).toUpperCase() +
(sliced.toUpperCase() === sliced ? sliced.toLowerCase() : sliced)
);
};
and imported it in _app.jsx like this:
import "./_customGlobals";
So now I can call this function on any string anywhere in my project like this:
"this is a title".title()
Database designed for this purpose. But for one var it's not wise to install whole db!
So, you can do it in a JSON file.
Add a var to a JSON file and use a function to update it.
this is a simple function for this usage:
const fs = require('fs');
function updateJSONFile(filePath, updates) {
fs.readFile(filePath, 'utf8', function (err, data) {
if (err) {
console.error(err);
return;
}
let json = JSON.parse(data);
for (let key in updates) {
json[key] = updates[key];
}
fs.writeFile(filePath, JSON.stringify(json, null, 2), 'utf8', function (err) {
if (err) {
console.error(err);
}
});
});
}
So, use it like this:
updateJSONFile('file.json', { name: 'John Doe', age: 30 });
You can create another function to read it dynamicly:
function readJSONFile(filePath) {
fs.readFile(filePath, 'utf8', function (err, data) {
if (err) {
return callback(err);
}
let json;
try {
json = JSON.parse(data);
} catch (error) {
return callback(error);
}
return callback(null, json);
});
}
and you can use it like this:
const readedFile = readJSONFile('file.json')
I deleted the callback function to have a simple code but you can add callback function to log error messages.

Cannot read property 'emit' of undefined when trying to emit a document

I am trying to create a design for tags of entities in PouchDB with ReactJS. I managed to save my design using the put function, but when I query my design, the response is just an empty array and I am getting following error in console:
TypeError: Cannot read property 'emit' of undefined
I think the problem is in my function that I later use as a map parameter to my design variable:
function emitTagsMap(doc)
{
if (doc !== undefined)
{
if (Array.isArray(doc.tags))
{
doc.tags.forEach(x =>
{
/* Here is probably the problem - this.db is undefined */
this.db.emit(x, null);
});
}
}
};
this.db is declared in constructor:
constructor(service, name)
{
if (!service || !name) throw new Error("PouchDatabase initialized incorrectly");
this.name = name;
this.db = new PouchDB(name);
this.service = service;
this.tagsView();
}
Please bare in mind that I am completely new to PouchDB.
Any ideas how can I initialize the emit function?
Thank you in advance.
I assume, that your function is a part of a JavaScript class (otherwise you have to explain the idea with this). In ES6, you have to bind this to your regular functions. You have two options:
First - bind it via constructor:
constructor() {
this.emitTagsMap = this.emitTagsMap.bind(this);
}
Second - declare the function as an arrow one. This way, react will bind it for you:
emitTagsMap = (doc) =>
{
if (doc !== undefined)
{
if (Array.isArray(doc.tags))
{
doc.tags.forEach(x =>
{
/* Here is probably the problem - this.db is undefined */
this.db.emit(x, null);
});
}
}
};
You don't need to call emit over the database object.
Try this:
function emitTagsMap(doc)
{
if (doc !== undefined)
{
if (Array.isArray(doc.tags))
{
doc.tags.forEach(x =>
{
emit(x, null);
});
}
}
};
According to the PouchDB docs a design document is formed like this:
// first create a new design doc and pass your map function as string into it
var ddoc = {
_id: "_design/my_index",
views: {
by_name: {
map: "function (doc) { if (doc !== undefined) { if (Array.isArray(doc.tags)) { doc.tags.forEach(x => { emit(x, null); }); } } }"
}
}
};
// save it
db.put(ddoc).then(function () {
// success!
}).catch(function (err) {
// some error (maybe a 409, because it already exists?)
});
//Then you actually query it, by using the name you gave the design document when you saved it:
db.query('my_index/by_name').then(function (res) {
// got the query results
}).catch(function (err) {
// some error
});
https://pouchdb.com/guides/queries.html

Cannot find function variable name in angularjs

I've created following AngularJS code, but I've found Error: Can't find variable: modifyCustomerAgent error when I render call modifyCustomer() my code. Please let me know what's wrong. Thanks.
function modifyCustomer() {
return modifyCustomerAgent(modifyCustomerData, true).then(function(data) {
console.log(JSON.stringify(data));
});
}
$scope.modifyCustomerAgent = (saveFormData, isUpgrade) => {
return {
property: 'value'
};
}
Try something like this
$scope.modifyCustomerAgent = (saveFormData, isUpgrade) => {
return Promise((resolve,reject)=>{
resolve ({
property: 'value'
});
})
}

how to form an object and push it into an array using http/https from the resultant of response

i am new to nodejs and i am trying to form an array of products which are having invalid imageUrls by using "http.get", I am querying my products from my mongodb collection, though i used "Promise" the array is printing first, i am not getting the result form the "hh.get"
here is my code in server side
var Promise = require('bluebird'),
hh = require('http-https')
mongoose = require('mongoose'),
collection = mongoose.model('Collection');
function getInValidImgUrl(prodObj){
return hh.get(prodObj.imageUrl,function(res){
if(res.statusCode == 404){
return {
name:prodObj.name,
imgUrl:prodObj.imageUrl
}
}
})
}
exports.sampleFunc=function(){
collection.find({category:"electronics"}).exec(function(err,products){
if(err){
console.log(err)
}else{
var imgArr=[];
//eg:products=[{name:"mobile",imageUrl:"http://somepic.jpg"}]
for(var i=0; i<products.length: i++){
imgArr.push(getInValidImgUrl(products(i)));
}
Promise.all(imgArr).then(results =>{
console.log("IAMGE ARRAY :"+JSON.stringify(results)); //here iam not getting array
})
}
});
}
thanks in advance.
You don't actually need to use bluebird for this, although you could use the npm package request-promise (https://www.npmjs.com/package/request-promise) I use that quite a lot. In the interests of not changeing what you have too much your issue is that you are making the return in the callback for the getInValidImgUrl function. You can change this to use the standard Promise class that comes for free with node (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
function getInValidImgUrl(prodObj){
return new Promise((resolve,reject) => {
hh.get(prodObj.imageUrl,function(res){
if(res.statusCode == 404){
resolve( {
name:prodObj.name,
imgUrl:prodObj.imageUrl
})
}
})
}
}

Adding glyphicon icons to form fields

I'm wanting to add icons to form fields like bootstrap has: http://getbootstrap.com/css/?#forms-control-validation
I was able to get the class to display properly on the form-group by adjusting the options:
successClass: 'has-success',
errorClass: 'has-error',
classHandler: function (_el) {
return _el.$element.closest('.form-group');
}
but i'm unable to figure out the best way to add the error or checkmark glyphicon. I assume it may have something to do with the errorWrapper / errorContainer but there isn't one for successWrapper/container
I ended up coming up with something else:
var bootstrapParsleyOptions = {
successClass: 'has-success has-feedback',
errorClass: 'has-error has-feedback',
classHandler: function (_el) {
return _el.$element.closest('.form-group');
}
};
$.extend(true, ParsleyUI, {
enableBootstrap: function () {
$(".form-control-feedback").removeClass('glyphicon-ok').removeClass('glyphicon-remove');
window.Parsley.on('form:init', function () {
$(this.$element).find(".form-control-feedback").removeClass('glyphicon-ok').removeClass('glyphicon-remove');
});
window.Parsley.on('field:validated', function () {
var element = this.$element;
if (this.validationResult == true) {
$(element).siblings(".form-control-feedback").removeClass('glyphicon-remove').addClass('glyphicon-ok');
$(element).siblings(".sr-only").text("(success)");
} else {
$(element).siblings(".form-control-feedback").removeClass('glyphicon-ok').addClass('glyphicon-remove');
$(element).siblings(".sr-only").text("(error)");
}
});
},
clearBootstrap: function () {
$(".form-control-feedback").removeClass('glyphicon-ok').removeClass('glyphicon-remove');
}
});
To enable it:
$("#form").parsley(bootstrapParsleyOptions);
ParsleyUI.enableBootstrap();
To reset it:
$("#form").parsley(bootstrapParsleyOptions).reset();
ParsleyUI.enableBootstrap();
I imagine that you can obtain what you want with CSS, something like
.parsley-success::before { content: '√'; }

Resources