Lunch Count Daily Save and Wipe Script - string

I work for a school system looking to have their lunch numbers for the day saved each night and then the numbers wiped. We have tried to find someone to write us a script with triggers but no one has been able to figure it out thus far. Any help would be highly appreciated. This is our last hope. https://docs.google.com/a/bradleyschools.org/spreadsheets/d/1KZ8LuABtUE1I4jFKVzroXKaJVOcD9LArewRl5wRFRbA/edit?usp=sharing

Lunch Counter WebApp
I took a stab at the problem and here it is. I have it working as a webapp contained in a spreadsheet and the lunchcount gets posted and reset every night around 10:00 PM. Every time you do a get on the url it checks to see if the trigger is set and if it's not then it creates a new one. But it won't create more than one. I checked it last night and the trigger is working fine. Don't forget to put in the SpreadSheetID for the postLunchCount and also run setupNightlyTrigger() once to get the trigger installed. It run's by itself after that.
LunchCounter.html
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function() {
google.script.run
.withSuccessHandler(displayCount)
.getCount();
});
function incrementCount()
{
google.script.run
.withSuccessHandler(displayCount)
.lunchCounter();
}
function displayCount(n)
{
$('#cnt').text(n);
}
console.log('My Code');
</script>
</head>
<body>
<div id="cnt"></div>
<input type="button" id="btn1" value="Increment" onClick="incrementCount();" style="width:200px;height:200px;"/>
</body>
</html>
Code.gs
function onOpen()
{
SpreadsheetApp.getUi().createMenu('My Tools')
.addItem('Lunch Counter','lunchCounter')
.addItem('Load SideBar', 'loadSideBar')
.addItem('Reset Lunch Count','resetLunchCount')
.addItem('Post Lunch','postLunchCount')
.addToUi();
}
function lunchCounter()
{
var prop=PropertiesService.getScriptProperties();
var count=Number(prop.getProperty('LunchCount'));
count++;
prop.setProperty('LunchCount', count);
return(count);
}
function getCount()
{
var prop=PropertiesService.getScriptProperties();
var count=Number(prop.getProperty('LunchCount'));
return(count);
}
function resetLunchCount()
{
postLunchCount();
PropertiesService.getScriptProperties().setProperty('LunchCount', '0');
}
function postLunchCount()
{
var ss=SpreadsheetApp.openById('SpreadSheetID');
var sht=ss.getSheetByName('DailyLunchCount');
var dt=Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "yyyy-MM-dd");
var cnt=getCount();
var row=[dt,cnt];
sht.appendRow(row);
}
function setupNightlyTrigger()
{
if(!isTrigger('resetLunchCount'))
{
ScriptApp.newTrigger('resetLunchCount').timeBased().atHour(22).everyDays(1).create();
}
}
function loadSideBar()
{
var html = HtmlService.createHtmlOutputFromFile('LunchCounter');
SpreadsheetApp.getUi().showSidebar(html);
}
function doGet()
{
setupNightlyTrigger();
var html = HtmlService.createHtmlOutputFromFile('LunchCounter');
html.addMetaTag('viewport', 'width=device-width, initial-scale=1');
return html.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL)
}
function isTrigger(handlerName)
{
var r=false;
var triggers = ScriptApp.getProjectTriggers();
for (var i=0;i<triggers.length;i++)
{
if (handlerName==triggers[i].getHandlerFunction())
{
r=true;
break;
}
}
return r;
}
This is what the webapp looks like on an Iphone:
It's really not that big. I did it as a screen shot. On my iphone the button size is about 3/4" and the lunch count is diplayed above it. I'm don't really know what you wanted but I figured a single button is simple User Interface.
Spreadsheet Looks Like this:

Related

handling JSOM clientcontext properly

I am trying out JSOM in Sharepoint 2016. I have made a WebPart containing the following code -
<div id="user-output"></div>
Movie Title: <input type="text" id="movie-title" /><br />
Description: <input type="text" id="movie-description" /><br />
<button type="button" id="submit-button">Add Movie</button>
<div id="movies-output"></div>
<script type="text/javascript" src="/SiteAssets/jquery-3.2.1.min.js"></script>
<script type="text/ecmascript" src="../_layouts/15/SP.UserProfiles.js"></script>
<script type="text/javascript">
$(function () {
$('#submit-button').on('click', function () {
var context = SP.ClientContext.get_current();
var movies = context.get_web().get_lists().getByTitle('Movies');
var movieCreationInfo = new SP.ListItemCreationInformation();
var movie = movies.addItem(movieCreationInfo);
movie.set_item("Title", $('#movie-title').val());
movie.set_item("MovieDescription", $('#movie-description').val());
movie.update();
context.load(movie);
context.executeQueryAsync(success, failure);
});
function success() {
$('#movies-output').text('Created movie!');
}
function failure() {
$('#movies-output').text('Something went wrong');
}
var upp;
// Ensure that the SP.UserProfiles.js file is loaded before the custom code runs.
//SP.SOD.executeOrDelayUntilScriptLoaded(getUserProperties, 'SP.UserProfiles.js');
SP.SOD.executeFunc('userprofile', 'SP.UserProfiles.PeopleManager', getUserProperties);
//SP.SOD.executeFunc('SP.UserProfiles.js', getUserProperties);
function getUserProperties() {
// Get the current client context and PeopleManager instance.
var clientContext = new SP.ClientContext.get_current();
var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
upp = peopleManager.getMyProperties();
clientContext.load(upp, 'UserProfileProperties');
clientContext.executeQueryAsync(onRequestSuccess, onRequestFail);
}
// This function runs if the executeQueryAsync call succeeds.
function onRequestSuccess() {
$('#user-output').html('User Name: ' + upp.get_userProfileProperties()['PreferredName'] +
'<br/>Department: ' + upp.get_userProfileProperties()['Department'] +
'<br/>Designation: ' + upp.get_userProfileProperties()['Title'] +
'<br/>Employee ID: ' + upp.get_userProfileProperties()['EmployeeID'] +
'<br/>Branch Code: ' + upp.get_userProfileProperties()['branchCode']
);
}
// This function runs if the executeQueryAsync call fails.
function onRequestFail(sender, args) {
$('#user-output').text("Error: " + args.get_message());
}
});
What this code does is -
Show user information in user-output div at document load ready
Saves a movie record when Add Movie button is clicked
However, for some reason, when Add Movie button is clicked, the code adds two movies instead of one. I think it has something to do with the ClientContext. But I am not sure why, or how to solve it. Can anyone help?
I am not sure how it happened, or if it's a bug, but while fiddling with the page source to find out why double posting was occurring, I saw that my web part code was being rendered twice in the page. One part was visible, and another was under a hidden div. However, when I went to edit page to delete the hidden web part, I couldn't. So I restored my page to the template version and re-added the web part. After that the web part was working correctly. There were no problems with the code.

RealTime Collaborative Text-Editor in Nodejs & Socket.io

I am developing a real-time text editor with paragraph locking property similar to https://quip.com/. in socket.io and nodejs.
It means when you write onto a given paragraph, other collaborators cant edit it.
Moment you hit enter or move cursor to a new line that paragraph becomes Editable for other Collaborators.
I am quite stuck after this. I am thinking a nice approach to move further. Suggestions please.
Below is my code which works perfectly. Till now i can get list of all collaborators and broadcast the content of editor to other collaborators.
index.html
<!DOCTYPE html>
<html>
<head>
<title>Connected Clients</title>
<!--<meta charset="UTF-8"> -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<!--<script type="text/javascript" src="jquery.js"></script> -->
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<textarea id="editor" style="height:200px;width:300px">
Thinknest Pragraph locking Test sample !
</textarea>
<script>
function msgReceived(msg){
//clientCounter.html(msg.clients);
document.getElementById('people').innerHTML=msg.uid;
//console.log(msg.id);
}
var clientCounter;
$(document).ready(function () {
clientCounter = $("#client_count");
var socket = io.connect(
'http://localhost:5000',
{'sync disconnect on unload':true}
);
var uId=prompt("enter your userId",'');
socket.emit('collabrator',uId);
socket.on('message', function(msg){
msgReceived(msg);
});
socket.on('online_collabs',function(data){
$('#online_ppl').html(data);
clientCounter.html(data.length);
});
socket.on('remained_collabs',function(data){
$('#online_ppl').html(data);
clientCounter.html(data.length);
});
socket.on('note_collabs',function(data){
$('#note_colabs').html(data);
});
socket.on('updated_para',function(data){
//$('#editor').append(data);
document.getElementById('editor').innerHTML=data;
});
$('#editor').on('keydown',function(){
//var para=$('#editor').value;
var para= $('#editor').val();
//var para=document.querySelector('[contenteditable]');
// var text=para.textContent;
socket.emit('para',{paragraph:para});
});
});
</script>
<p><span id="client_count">0</span> connected clients</p><br/>
<ul id="people"></ul>
<h3>Online Collaborators</h3>
<span id="online_ppl"></span> <br>
<h3>Note Collaborators</h3>
<span id="note_colabs"></span>
</body>
</html>
server.js
var app = require('express')()
, server = require('http').createServer(app)
, io = require('socket.io').listen(server);
server.listen(5000);
app.get('/',function(req,res){
res.sendfile("./index.html");
});
var activeClients = 0;
var Collaborators=['Colab1','Colab2','Colab3'];
var people=[];
io.sockets.on('connection', function(socket){
clientConnect(socket);
socket.on('disconnect', function(){
clientDisconnect(socket);
});
socket.on('para',function(data){
//io.sockets.emit('updated_para',data.paragraph);
socket.broadcast.emit('updated_para',data.paragraph);
});
});
function clientConnect(socket){
//activeClients +=1;
var userSocketId=socket.id;
check_Collaborator(socket);
io.sockets.emit('message', {uid:userSocketId});
}
var online_collabs=[];
function check_Collaborator(socket){
socket.on('collabrator',function(data){
if(Collaborators.indexOf(data)!=-1){
socket.data=data;
if(online_collabs.indexOf(data)==-1) {
online_collabs.push(data);
}
io.sockets.emit('online_collabs',online_collabs);
io.sockets.emit('note_collabs',Collaborators);
} else {
console.log("collabrator not found");
}
});
}
function clientDisconnect(socket){
var index=online_collabs.indexOf(socket.data)
if(index>-1)
online_collabs.splice(index,1);
//activeClients -=1;
//io.sockets.emit('message', {clients:activeClients});
io.sockets.emit('remained_collabs',online_collabs);
}
I saw this yesterday already. What exactly is your question? Do you want to know how to 'lock' a text area with javascript? I am confused as to why you put such a strong emphasis on node/socket.io in your question.
Also, next time please format your code. You want help, I get it, but then make it easier for others to help you.
What you have to do in order to make a paragraph not editable by others, I don't know. But let me suggest what I'ld do in socket.io:
Store each paragraph separately and remember who has a lock on it. For locking, I would use the sessionID in case users don't have to register. This would look something like this:
var paragraphs = {
data : [
{
text: "this is an unlocked paragraph",
lock: ""
},
{
text: "this is a locked paragraph",
lock: "oWEALlLx5E-VejicAAAC"
}
]
}
Now, users will likely be allowed to add a paragraph before an existing one. Therefore you should keep an additional index like:
var paragraphs = {
index : [
1,
0
],
data : [
{
text: "this the second paragraph",
lock: "oWEALlLx5E-VejicAAAC"
},
{
text: "this is the first paragraph",
lock: ""
}
]
}
The amount of data being sent over the sockets should now be very small - altough with additional client/server-side logic.
Paragraph lock can be easily achieved by adding a class to the currently editing paragraph. Transfer this paragraph with the class to the other user. so that if the user tries to write over that prevent him by validate with the class.
Generate a class name look like - className_userid (className_1).

Something wrong with the way the site loads

I own a small blog and recently random people have been telling me that my site has loading problems as in the site will load but only pictures will show and not the text. I've never encountered the problem personally myself until today. I see what they mean, and if I hover my mouse over the text, then the text loads as well. Anybody have a clue on why?
If it's happening only with Google Chrome, then it might be due to Google font's not rendering properly. Use this code in your style.css to fix the issue.
body {
-webkit-animation-delay: 0.1s;
-webkit-animation-name: fontfix;
-webkit-animation-duration: 0.1s;
-webkit-animation-iteration-count: 1;
-webkit-animation-timing-function: linear;
}
#-webkit-keyframes fontfix {
from { opacity: 1; }
to { opacity: 1; }
}
Sometimes, it didn't work too so the it'll be good by adding this code in your header.php file:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript" charset="utf-8">
$(function() { $('body').hide().show(); });
</script>
<script type="text/javascript">
//JavaScript goes here
WebFontConfig = {
google: { families: ['FontOne', 'FontTwo'] },
fontinactive: function (fontFamily, fontDescription) {
//Something went wrong! Let's load our local fonts.
WebFontConfig = {
custom: { families: ['FontOne', 'FontTwo'],
urls: ['font-one.css', 'font-two.css']
}
};
loadFonts();
}
};
function loadFonts() {
var wf = document.createElement('script');
wf.src = ('https:' == document.location.protocol ? 'https' : 'http') +
'://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
wf.type = 'text/javascript';
wf.async = 'true';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(wf, s);
}
(function () {
//Once document is ready, load the fonts.
loadFonts();
})();
</script>
I hope this helps

PJax not working with MVC project

I've followed the samples. I added a _PjaxLayout:
<title>#ViewBag.Title</title>
#RenderBody()
Modified my _Layout:
<div id="shell">
#RenderBody()
</div>
<script type="text/javascript">
$(function () {
// pjax
$.pjax.defaults.timeout = 5000;
$('a').pjax('#shell');
})
</script>
Updated ViewStart:
#{
if (Request.Headers["X-PJAX"] != null) {
Layout = "~/Views/Shared/_PjaxLayout.cshtml";
} else {
Layout = "~/Views/Shared/_Layout.cshtml";
}
}
Yet every time I click on an 'a' tag, the pjax code doesn't get called. It's as if the selector isn't working when I set up pjax. What am I doing wrong?
UPDATE:
If I do this:
$('document').ready(function () {
$('a').pjax({
container: '#shell',
timeout: 5000
});
});
I see the pjax code getting hit and the Request headers get updated, and the new content loads on the page, but the styling and layout get really messed up and duplicated...
UPDATE:
Inspecting the DOM after this craziness happens reveals that the new page content is getting loaded directly into the anchor that I click, instead of into the element with id #shell. WTF?
You are using a legacy syntax, the new pjax uses the following:
$(document).pjax('a', '#shell', { fragment: '#shell' });
Also I am not familiar with the language you use, but in order to make pjax happen there has to be an HTML element with the id shell in your ViewStart.
As I am not sure about the syntax in that language, try something similar to this for testing:
#{
if (Request.Headers["X-PJAX"] != null) {
echo "<ul id="shell"> pjaaxxx </ul>"; // Would work in php, update syntax
} else {
Layout = "~/Views/Shared/_Layout.cshtml";
}
}
I am not seeing that syntax as valid in the PJax documentation.
Are you sure you didn't mean $(document).pjax('a',{});?
$.pjax immediately executes from what I can tell.

How to put a delay on AngularJS instant search?

I have a performance issue that I can't seem to address. I have an instant search but it's somewhat laggy, since it starts searching on each keyup().
JS:
var App = angular.module('App', []);
App.controller('DisplayController', function($scope, $http) {
$http.get('data.json').then(function(result){
$scope.entries = result.data;
});
});
HTML:
<input id="searchText" type="search" placeholder="live search..." ng-model="searchText" />
<div class="entry" ng-repeat="entry in entries | filter:searchText">
<span>{{entry.content}}</span>
</div>
The JSON data isn't even that large, 300KB only, I think what I need to accomplish is to put a delay of ~1 sec on the search to wait for the user to finish typing, instead of performing the action on each keystroke. AngularJS does this internally, and after reading docs and other topics on here I couldn't find a specific answer.
I would appreciate any pointers on how I can delay the instant search.
UPDATE
Now it's easier than ever (Angular 1.3), just add a debounce option on the model.
<input type="text" ng-model="searchStr" ng-model-options="{debounce: 1000}">
Updated plunker:
http://plnkr.co/edit/4V13gK
Documentation on ngModelOptions:
https://docs.angularjs.org/api/ng/directive/ngModelOptions
Old method:
Here's another method with no dependencies beyond angular itself.
You need set a timeout and compare your current string with the past version, if both are the same then it performs the search.
$scope.$watch('searchStr', function (tmpStr)
{
if (!tmpStr || tmpStr.length == 0)
return 0;
$timeout(function() {
// if searchStr is still the same..
// go ahead and retrieve the data
if (tmpStr === $scope.searchStr)
{
$http.get('//echo.jsontest.com/res/'+ tmpStr).success(function(data) {
// update the textarea
$scope.responseData = data.res;
});
}
}, 1000);
});
and this goes into your view:
<input type="text" data-ng-model="searchStr">
<textarea> {{responseData}} </textarea>
The mandatory plunker:
http://plnkr.co/dAPmwf
(See answer below for a Angular 1.3 solution.)
The issue here is that the search will execute every time the model changes, which is every keyup action on an input.
There would be cleaner ways to do this, but probably the easiest way would be to switch the binding so that you have a $scope property defined inside your Controller on which your filter operates. That way you can control how frequently that $scope variable is updated. Something like this:
JS:
var App = angular.module('App', []);
App.controller('DisplayController', function($scope, $http, $timeout) {
$http.get('data.json').then(function(result){
$scope.entries = result.data;
});
// This is what you will bind the filter to
$scope.filterText = '';
// Instantiate these variables outside the watch
var tempFilterText = '',
filterTextTimeout;
$scope.$watch('searchText', function (val) {
if (filterTextTimeout) $timeout.cancel(filterTextTimeout);
tempFilterText = val;
filterTextTimeout = $timeout(function() {
$scope.filterText = tempFilterText;
}, 250); // delay 250 ms
})
});
HTML:
<input id="searchText" type="search" placeholder="live search..." ng-model="searchText" />
<div class="entry" ng-repeat="entry in entries | filter:filterText">
<span>{{entry.content}}</span>
</div>
In Angular 1.3 I would do this:
HTML:
<input ng-model="msg" ng-model-options="{debounce: 1000}">
Controller:
$scope.$watch('variableName', function(nVal, oVal) {
if (nVal !== oVal) {
myDebouncedFunction();
}
});
Basically you're telling angular to run myDebouncedFunction(), when the the msg scope variable changes. The attribute ng-model-options="{debounce: 1000}" makes sure that msg can only update once a second.
<input type="text"
ng-model ="criteria.searchtext""
ng-model-options="{debounce: {'default': 1000, 'blur': 0}}"
class="form-control"
placeholder="Search" >
Now we can set ng-model-options debounce with time and when blur, model need to be changed immediately otherwise on save it will have older value if delay is not completed.
For those who uses keyup/keydown in the HTML markup.
This doesn't uses watch.
JS
app.controller('SearchCtrl', function ($scope, $http, $timeout) {
var promise = '';
$scope.search = function() {
if(promise){
$timeout.cancel(promise);
}
promise = $timeout(function() {
//ajax call goes here..
},2000);
};
});
HTML
<input type="search" autocomplete="off" ng-model="keywords" ng-keyup="search()" placeholder="Search...">
Debounced / throttled model updates for angularjs : http://jsfiddle.net/lgersman/vPsGb/3/
In your case there is nothing more to do than using the directive in the jsfiddle code like this:
<input
id="searchText"
type="search"
placeholder="live search..."
ng-model="searchText"
ng-ampere-debounce
/>
Its basically a small piece of code consisting of a single angular directive named "ng-ampere-debounce" utilizing http://benalman.com/projects/jquery-throttle-debounce-plugin/ which can be attached to any dom element. The directive reorders the attached event handlers so that it can control when to throttle events.
You can use it for throttling/debouncing
* model angular updates
* angular event handler ng-[event]
* jquery event handlers
Have a look : http://jsfiddle.net/lgersman/vPsGb/3/
The directive will be part of the Orangevolt Ampere framework (https://github.com/lgersman/jquery.orangevolt-ampere).
Just for users redirected here:
As introduced in Angular 1.3 you can use ng-model-options attribute:
<input
id="searchText"
type="search"
placeholder="live search..."
ng-model="searchText"
ng-model-options="{ debounce: 250 }"
/>
I believe that the best way to solve this problem is by using Ben Alman's plugin jQuery throttle / debounce. In my opinion there is no need to delay the events of every single field in your form.
Just wrap your $scope.$watch handling function in $.debounce like this:
$scope.$watch("searchText", $.debounce(1000, function() {
console.log($scope.searchText);
}), true);
Another solution is to add a delay functionality to model update. The simple directive seems to do a trick:
app.directive('delayedModel', function() {
return {
scope: {
model: '=delayedModel'
},
link: function(scope, element, attrs) {
element.val(scope.model);
scope.$watch('model', function(newVal, oldVal) {
if (newVal !== oldVal) {
element.val(scope.model);
}
});
var timeout;
element.on('keyup paste search', function() {
clearTimeout(timeout);
timeout = setTimeout(function() {
scope.model = element[0].value;
element.val(scope.model);
scope.$apply();
}, attrs.delay || 500);
});
}
};
});
Usage:
<input delayed-model="searchText" data-delay="500" id="searchText" type="search" placeholder="live search..." />
So you just use delayed-model in place of ng-model and define desired data-delay.
Demo: http://plnkr.co/edit/OmB4C3jtUD2Wjq5kzTSU?p=preview
I solved this problem with a directive that basicly what it does is to bind the real ng-model on a special attribute which I watch in the directive, then using a debounce service I update my directive attribute, so the user watch on the variable that he bind to debounce-model instead of ng-model.
.directive('debounceDelay', function ($compile, $debounce) {
return {
replace: false,
scope: {
debounceModel: '='
},
link: function (scope, element, attr) {
var delay= attr.debounceDelay;
var applyFunc = function () {
scope.debounceModel = scope.model;
}
scope.model = scope.debounceModel;
scope.$watch('model', function(){
$debounce(applyFunc, delay);
});
attr.$set('ngModel', 'model');
element.removeAttr('debounce-delay'); // so the next $compile won't run it again!
$compile(element)(scope);
}
};
});
Usage:
<input type="text" debounce-delay="1000" debounce-model="search"></input>
And in the controller :
$scope.search = "";
$scope.$watch('search', function (newVal, oldVal) {
if(newVal === oldVal){
return;
}else{ //do something meaningful }
Demo in jsfiddle: http://jsfiddle.net/6K7Kd/37/
the $debounce service can be found here: http://jsfiddle.net/Warspawn/6K7Kd/
Inspired by eventuallyBind directive http://jsfiddle.net/fctZH/12/
Angular 1.3 will have ng-model-options debounce, but until then, you have to use a timer like Josue Ibarra said. However, in his code he launches a timer on every key press. Also, he is using setTimeout, when in Angular one has to use $timeout or use $apply at the end of setTimeout.
Why does everyone wants to use watch? You could also use a function:
var tempArticleSearchTerm;
$scope.lookupArticle = function (val) {
tempArticleSearchTerm = val;
$timeout(function () {
if (val == tempArticleSearchTerm) {
//function you want to execute after 250ms, if the value as changed
}
}, 250);
};
I think the easiest way here is to preload the json or load it once on$dirty and then the filter search will take care of the rest. This'll save you the extra http calls and its much faster with preloaded data. Memory will hurt, but its worth it.

Resources