how to style opacity in addEventListner? - coding-style

const mainDiv = document.getElementsByClassName('home-bg-image');
const homeMainDiv = document.getElementsByClassName('home-bg');
const homeDiv = document.getElementById('home-1');
homeDiv.addEventListener('mouseenter', e => {
mainDiv.style.opacity = '0';
homeMainDiv.style.opacity = '1';
console.log('Working !!!')
});
I got this Error
Uncaught TypeError: Cannot set property 'opacity' of undefined at HTMLDivElement.

documents.getElementsByClassName returns an array.
You should access the element you want to style by using the brackets notation
mainDiv[0].style.opacity = '0';
homeMainDiv[0].style.opacity = '1';

Related

Google Script AddRecord Function and For Loops

I am trying to create a for loop using Google Script and having a hard time with adding records. When I add a record, I receive one's email and then 36 questions as such:
function AddRecord(email, q1, q2, q3, q4, q5, q6, q7, q8, q9, q10, q11, q12, q13, q14, q15, q16, q17, q18, q19, q20, q21, q22, q23, q24, q25, q26, q27, q28, q29, q30, q31, q32, q33, q34, q35, q36){
var url ="Name of Url";
var ss= SpreadsheetApp.openByUrl(url);
var ws = ss.getSheetByName("Sheet1");
ws.appendRow([email, q1, q2, q3, q4, q5, q6, q7, q8, q9, q10, q11, q12, q13, q14, q15, q16, q17, q18, q19, q20, q21, q22, q23, q24, q25, q26, q27, q28, q29, q30, q31, q32, q33, q34, q35, q36]);}
I would think the code below would allow me to pass this function correctly by the spread operator. I have tried different things but I am confused with how to proceed dealing with parameters/arrays/etc. How would I go about creating a for loop for this?
const questions = [];
for (let i = 1; i <= 36; i++) {
questions.push(`q${i}`);
}
function AddRecord(email, ... questions){
var url ="Name of Url";
var ss= SpreadsheetApp.openByUrl(url);
var ws = ss.getSheetByName("Sheet1");
ws.appendRow([email, ... questions]);}
Try this:
function AddRecord(email, questions) {
var url = "Name of Url";
var ss = SpreadsheetApp.openByUrl(url);
var ws = ss.getSheetByName("Sheet1");
questions.unshift(email)
ws.appendRow(questions);
}
I had to do this to test it.
function AddRecord() {
const email = 'email';
const questions = [];
for (let i = 1; i <= 36; i++) { questions.push(`q${i}`); }
var id = gobj.globals.testsourceid;//I have this id in globals
var ss = SpreadsheetApp.openById(id);//so I went with openById()
var ws = ss.getSheetByName("Sheet2");
questions.unshift(email)
ws.appendRow(questions);
}
Testing it this way is much better:
function testAddRecord() {
const email = 'email';
const questions = [];
for (let i = 1; i <= 36; i++) { questions.push(`q${i}`); }
AddRecord(email, questions);
}
function AddRecord(email, questions) {
var id = gobj.globals.testsourceid;
var ss = SpreadsheetApp.openById(id);
var ws = ss.getSheetByName("Sheet2");
questions.unshift(email)
ws.appendRow(questions);
}
output:
email
q1
q2
q3
q4
q5
q6
q7
q8
q9
q10
q11
q12
q13
q14
q15
q16
q17
q18
q19
q20
q21
q22
q23
q24
q25
q26
q27
q28
q29
q30
q31
q32
q33
q34
q35
q36

how to to convert for to foreach

jslint tell Unexpected 'for'.
so i think that i must convert for with foreach
but how?
if someone can help
thanks
// Grab the original element
var original = document.getElementsByTagName("noscript")[0];
// Create a replacement tag of the desired type
var replacement = document.createElement("span");
var i;
// Grab all of the original's attributes, and pass them to the replacement
for(i = 0, l = original.attributes.length; i < l; ++i){
var nodeName = original.attributes.item(i).nodeName;
var nodeValue = original.attributes.item(i).nodeValue;
replacement.setAttribute(nodeName, nodeValue);
}
// Persist contents
replacement.innerHTML = original.innerHTML;
// Switch!
original.parentNode.replaceChild(replacement, original);
You have a comma after i = 0, <========
it should be semicolon.
Another issue is declaring l = original.attributes.length you don't need the variable l
just use it as for(i = 0; i < original.attributes.length; ++i){
if you still wanna use a forEach you can do it as:
original.attributes.forEach(element => {
var nodeName = element.nodeName;
var nodeValue = element.nodeValue;
replacement.setAttribute(nodeName, nodeValue);
});
thanks for your answer, i got Uncaught TypeError: original.attributes.forEach is not a function
function Switch() {
var original = document.getElementsByTagName("noscript")[0];
var replacement = document.createElement("span");
original.attributes.forEach(element => {
var nodeName = element.nodeName;
var nodeValue = element.nodeValue;
replacement.setAttribute(nodeName, nodeValue);
});
// Persist contents
replacement.innerHTML = original.innerHTML;
// Switch!
original.parentNode.replaceChild(replacement, original);
}

How to avoid Connection timed out after 10000 milliseconds?

I have a Laravel application in which I integrated PHP graph sdk to use Facebook graph API. I have a stats page, I display number of posts per type, top 3 posts, and some insights metric like "page_post_engagements" ... in moris charts.
this is my controller:
public function stats($id,Facebook $fb)
{
$page = Page::find($id);
$page_fb_id = $page->fb_id;
$page_access_token = $page->access_token;
$oAuth2Client = $fb->getOAuth2Client();
$fb->setDefaultAccessToken($oAuth2Client->getLongLivedAccessToken($page_access_token)->getValue());
$nb_photos = '0';
$nb_videos = '0';
$nb_links = '0';
$nb_likes = '0';
$nb_comments = '0';
$nb_shares = '0';
$count_posts = '0';
$startDate = Carbon::now()->subDays('29');
$endDate = Carbon::now();
$numberOfDays = $endDate->diffInDays($startDate);
$classement = array();
$posts = $fb->get('/'.$page_fb_id.'/posts?fields=type&since='.Carbon::parse($startDate).'&until='.Carbon::parse($endDate))->getGraphEdge();
if(empty($posts))
{
$classement = ['total'=>0,'likes'=>0,'comments'=>0,'shares'=>0];
}
else
{
foreach ($posts as $key => $post)
{
if($post['type'] == 'photo')
{
$nb_photos++;
}
else if($post['type'] == 'video')
{
$nb_videos++;
}
else if($post['type'] == 'link')
{
$nb_links++;
}
$count_posts++;
$impress = $fb->get('/'.$post['id'].'/insights?metric=post_impressions_unique')->getGraphEdge();
$engage = $fb->get('/'.$post['id'].'/insights?metric=post_engaged_users')->getGraphEdge();
$classement[] = ['total'=>($engage[0]['values'][0]['value']/$impress[0]['values'][0]['value'])*100,'id'=>$post['id'],'impressions'=>$impress[0]['values'][0]['value'],'engage'=>$engage[0]['values'][0]['value']];
}
if(is_array($classement))
{
asort($classement);
$tops = array_slice($classement, -3, 3);
$start_elem = array_slice($tops, 0, 1);
$mid_elem = array_slice($tops, 1, 1);
$end_elem = end($tops);
}
if($end_elem['id'])
{
$top1 = $fb->get('/'.$end_elem['id'].'/?fields=id,message,full_picture,source,type,created_time,from{name,picture}')->getGraphNode();
$likes1 = $fb->get('/'.$end_elem['id'].'/likes?limit=1000000')->getGraphEdge()->count();
$comments1 = $fb->get('/'.$end_elem['id'].'/comments?limit=1000000')->getGraphEdge()->count();
$shares1 = $fb->get('/'.$end_elem['id'].'/sharedposts?limit=1000000')->getGraphEdge()->count();
}
if($mid_elem[0]['id'])
{
$top2 = $fb->get('/'.$mid_elem[0]['id'].'/?fields=id,message,full_picture,source,type,created_time,from{name,picture}')->getGraphNode();
$likes2 = $fb->get('/'.$mid_elem[0]['id'].'/likes?limit=1000000')->getGraphEdge()->count();
$comments2 = $fb->get('/'.$mid_elem[0]['id'].'/comments?limit=1000000')->getGraphEdge()->count();
$shares2 = $fb->get('/'.$mid_elem[0]['id'].'/sharedposts?limit=1000000')->getGraphEdge()->count();
}
if($start_elem[0]['id'])
{
$top3 = $fb->get('/'.$start_elem[0]['id'].'/?fields=id,message,full_picture,source,type,created_time,from{name,picture}')->getGraphNode();
$likes3 = $fb->get('/'.$start_elem[0]['id'].'/likes?limit=1000000')->getGraphEdge()->count();
$comments3 = $fb->get('/'.$start_elem[0]['id'].'/comments?limit=1000000')->getGraphEdge()->count();
$shares3 = $fb->get('/'.$start_elem[0]['id'].'/sharedposts?limit=1000000')->getGraphEdge()->count();
}
}
foreach (range(0, $numberOfDays) as $day)
{
$a[] = ['year'=>$endDate->copy()->subDays($day)->format('Y-m-d')];
}
foreach (array_reverse($a) as $key => $value)
{
$page_fans = $fb->get('/'.$page_fb_id.'/insights?metric=page_fans&since='.Carbon::parse($value['year']).'&until='.Carbon::parse($value['year'])->addDays('2'))->getGraphEdge()[0]['values'][0]['value'];
$fans[] = ['year'=>$value['year'],'value'=>$page_fans];
$page_post_engagements = $fb->get('/'.$page_fb_id.'/insights?metric=page_post_engagements&since='.Carbon::parse($value['year']).'&until='.Carbon::parse($value['year'])->addDays('2'))->getGraphEdge()[0]['values'][0]['value'];
$post_engagements[] = ['year'=>$value['year'],'value'=>$page_post_engagements];
$page_impressions = $fb->get('/'.$page_fb_id.'/insights?metric=page_impressions&since='.Carbon::parse($value['year']).'&until='.Carbon::parse($value['year'])->addDays('2'))->getGraphEdge()[0]['values'][0]['value'];
$impressions[] = ['year'=>$value['year'],'value'=>$page_impressions];
$page_actions_post_reactions_like_total = $fb->get('/'.$page_fb_id.'/insights?metric=page_actions_post_reactions_like_total&since='.Carbon::parse($value['year']).'&until='.Carbon::parse($value['year'])->addDays('2'))->getGraphEdge()[0]['values'][0]['value'];
$post_reactions_like_total[] = ['year'=>$value['year'],'value'=>$page_actions_post_reactions_like_total];
/*$page_engaged_users = $fb->get('/'.$page_fb_id.'/insights?metric=page_engaged_users&since='.Carbon::parse($value['year']).'&until='.Carbon::parse($value['year'])->addDays('2'))->getGraphEdge()[0]['values'][0]['value'];
$engaged_users[] = ['year'=>$value['year'],'value'=>$page_engaged_users];
$page_views_total = $fb->get('/'.$page_fb_id.'/insights?metric=page_views_total&since='.Carbon::parse($value['year']).'&until='.Carbon::parse($value['year'])->addDays('2'))->getGraphEdge()[0]['values'][0]['value'];
$views_total[] = ['year'=>$value['year'],'value'=>$page_views_total];*/
}
/*$fans_total = end($fans)['value'];
$moyenne_interaction = array_sum(array_column($engaged_users,'value'))/count(array_column($engaged_users,'value'));
$average_interaction = array_sum(array_column($engaged_users,'value'))/count(array_column($engaged_users,'value'))/(end($fans)['value']);*/
$fans = json_encode($fans);
$post_engagements = json_encode($post_engagements);
$impressions = json_encode($impressions);
$post_reactions_like_total = json_encode($post_reactions_like_total);
/*$engaged_users = json_encode($engaged_users);
$views_total = json_encode($views_total);*/
return view('stats',with(compact('randon','id','tasks','page','fans','impressions','post_engagements','post_reactions_like_total','engaged_users','views_total','nb_photos','nb_videos','nb_links','count_posts','fans_total','top1','likes1','comments1','shares1','top2','likes2','comments2','shares2','top3','likes3','comments3','shares3')));
}
Is there a way to optimize my code so I can get a better response time and especially avoid the Connection timed out after 10000 milliseconds exception?
I'm assuming to get the API data and parse it... it is taking longer than 10 seconds?
You have 2 things to do to improve your system: 1) Use Cache 2) Use Queues.
Cache! (Save the API/parsed result for 15 minutes or so)
Queues! (API parsing is done in the server background)
Your system workflow will be:
User hits /stats
Is there a cache version? Use it. Response time ~ barely 500ms.
No/Expired cache? Fire a Queued Job to get the new API data.
Show the user 'Data is being refreshed!' and display the latest cache.

Play and Pause interval rxjs

i'm trying to implement play and pause button using Rxjs library.
const play$ = fromEvent(playerImplementation, PLAYER_EVENTS.PLAY).pipe(mapTo(true));
const pause$ = fromEvent(playerImplementation, PLAYER_EVENTS.PAUSE).pipe(mapTo(false));
const waiting$ = fromEvent(playerImplementation, PLAYER_EVENTS.WAITING).pipe(mapTo(false));
let counterTime = 0;
const currentTime$ = interval(30).pipe(
map(()=>counterTime += 30));
const player$ = merge(play$, pause$, waiting$).pipe(
switchMap(value => (value ? currentTime$ : EMPTY)));
// DIFFERENCE IN RESULTS
currentTime$.subscribe((v)=> console.log("Regular Count " + v)); // get correctly 30,60,90,120...
player$.subscribe((v)=>console.log("Condition Count" + v)); // get wrongly 30,150,270, 390
can anyone help in understanding why there is a difference between the results?
It happened because I used several subscribers for one observable (player$ observable). I solve this by using ReplaySubject instead of Observable and by using multicasting in order to handle the event in several subscribers, without changing the value.
const play$ = fromEvent(playerImplementation, PLAYER_EVENTS.PLAY).pipe(mapTo(true));
const pause$ = fromEvent(playerImplementation, PLAYER_EVENTS.PAUSE).pipe(mapTo(false));
const waiting$ = fromEvent(playerImplementation, PLAYER_EVENTS.WAITING).pipe(mapTo(false));
let timeCounter = 0;
const source = Observable.create((obs : Observer<number>)=> {
interval(30).pipe(
map(() => timeCounter += 30)).subscribe(obs);
return () => {};
});
// Cast the observable to subject for distributing to several subscribers
const currentTime$ = source.pipe(multicast(()=> new ReplaySubject(5))).refCount();
const player$ = merge(play$, pause$, waiting$).pipe(
switchMap(value => value ? currentTime$ : EMPTY));

After casting PushPin , get this Possible unitended reference comparison underline message

I Have this error message :
Possible unitended reference comparison; to get a value coparison, cast the left hand side to type string
problem :
((Pushpin)p).Tag == "locationPushpin"));
============================
double Dlat = Convert.ToDouble(g_strLat);
double Dlon = Convert.ToDouble(g_strLon);
this.map1.Center = new GeoCoordinate(Dlat, Dlon);
if (this.map1.Children.Count != 0)
{
var pushpin = map1.Children.FirstOrDefault(p => (p.GetType() == typeof(Pushpin) && ((Pushpin)p).Tag == "locationPushpin"));
if (pushpin != null)
{
this.map1.Children.Remove(pushpin);
}
}
Pushpin locationPushpin = new Pushpin();
//---set the location for the pushpin---
locationPushpin.Tag = "locationPushpin";
locationPushpin.Location = new GeoCoordinate(Dlat, Dlon);
locationPushpin.Content = new Ellipse()
{
Fill = new SolidColorBrush(Colors.Orange),
//Opacity = .8,
Height = 40,
Width = 30
};
locationPushpin.Width = 60;
locationPushpin.Height = 100;
this.map1.Center = new GeoCoordinate(Dlat, Dlon);
this.map1.Children.Add(locationPushpin);
this.map1.ZoomLevel = 13;
Would appreciate your help. Thanks
Firstly, your query would only find exact objects of type Pushpin. This is cleaner:
var pushpin = map1.Children.OfType<Pushpin>()
.FirstOrDefault(p => p.Tag == "locationPushpin");
The next problem is that Tag is of type object. So you really want:
var pushpin = map1.Children.OfType<Pushpin>()
.FirstOrDefault(p => "locationPushpin".Equals(p.Tag));
Otherwise you'll be doing a reference comparison between the Tag value and the string. So you could have equal but distinct strings, and the pushpin wouldn't be found.

Resources