<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import qs from 'query-string';
import Card from '../components/Card';
import HelpBubble from '../components/HelpBubble';
import GenericLoader from '../components/GenericLoader';
import {eventNoteTypeIdForAbsenceSupportMeeting} from '../helpers/PerDistrict';
import {eventNoteTypeTextMini} from '../helpes/eventNoteType';
import {apiFetchJson} from '../helpers/apiFetchJson';

// Show teachers their students who have high absences
// but don't have any notes in Insights recently (eg, haven't been brought up in SST).
class CheckStudentsWithHighAbsences extends React.Component {
  constructor(props) {
    super(props);
    this.fetchStudents = this.fetchStudents.bind(this);
    this.renderStudents = this.renderStudents.bind(this);
  }

  fetchStudents() {
    const {educatorId, limit} = this.props;
    const params = educatorId ? {limit, educator_id: educatorId} : {limit};
    const url = `/api/home/students_with_high_absences_json?${qs.stringify(params)}`;
    return apiFetchJson(url);
  }

  render() {
    return (

        <GenericLoader
          style={styles.card}
          promiseFn={this.fetchStudents}
          render={this.renderStudents} />

    );
  }

  renderStudents(json) {
    const props = {
      limit: json.limit,
      totalStudents: json.total_students,
      studentsWithHighAbsences: json.students_with_high_absences
    };
    return <CheckStudentsWithHighAbsencesView {...props} />;
  }
}
CheckStudentsWithHighAbsences.propTypes = {
  educatorId: PropTypes.number.isRequired,
  limit: PropTypes.number // limit the data returned, not the query itself
};
CheckStudentsWithHighAbsences.defaultProps = {
  limit: 100
};

// Pure UI component.
export class CheckStudentsWithHighAbsencesView extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      uiLimit: 4
    };
    this.renderHelpContent = this.renderHelpContent.bind(this);
    this.onMoreStudents = this.onMoreStudents.bind(this);
  }

  onMoreStudents(e) {
    e.preventDefault();
    const {uiLimit} = this.state;
    this.setState({ uiLimit: uiLimit + 4 });
  }

  render() {
    const {studentsWithHighAbsences, totalStudents} = this.props;
    const {uiLimit} = this.state;
    const truncatedStudentsWithHighAbsences = studentsWithHighAbsences.slice(0, uiLimit);

    return (

          Students missing school
          <HelpBubble
            teaser={what does this mean?}
            title="Students missing school"
            content={this.renderHelpContent()} />

        <Card style={{border: 'none'}}>
          {this.renderCopy(totalStudents)}
          {this.renderList(truncatedStudentsWithHighAbsences)}
          {this.renderMore(truncatedStudentsWithHighAbsences)}
        </Card>

    );
  }

  // Branching on singular and plural and zero.
  renderCopy(totalStudents) {
    const now = this.context.nowFn();
    const dateText = now.clone().subtract(45, 'days').format('MMMM Do');
    const sinceEl = Since {dateText}:;
    if (totalStudents === 0) {
      return
There are no students missing school recently who {"haven't"} been mentioned.
;
    } else if (totalStudents === 1) {
      return
There is one student missing school recently who {"hasn't"} been mentioned.  {sinceEl}
;
    } else {
      return
There are {totalStudents} students missing school recently who {"haven't"} been mentioned.  {sinceEl}
;
    }
  }

  renderList(truncatedStudentsWithHighAbsences) {
    if (truncatedStudentsWithHighAbsences.length === 0) return null;
    return (

        {truncatedStudentsWithHighAbsences.map(studentsWithHighAbsences => {
          const {student, count} = studentsWithHighAbsences;
          return (

                <a
                  style={styles.person}
                  href={`/students/${student.id}?column=attendance#absences`}>
                    {student.first_name} {student.last_name}
                   has missed {count} days of school

          );
        })}

    );
  }

  renderMore(truncatedStudentsWithHighAbsences) {
    const {totalStudents, limit, studentsWithHighAbsences} = this.props;

    if (truncatedStudentsWithHighAbsences.length !== studentsWithHighAbsences.length) {
      return
See more
;
    }

    if (studentsWithHighAbsences.length < totalStudents) {
      return
There are {totalStudents} students total.  Start with checking in on these first {limit} students.
;
    }

    return null;
  }

  renderHelpContent() {
    const {districtKey} = this.context;
    const eventNoteTypeId = eventNoteTypeIdForAbsenceSupportMeeting(districtKey);
    const shortMeetingText = eventNoteTypeTextMini(eventNoteTypeId);
    return (

These are all the students that you have access to who have a high number of absences over the last 45 days, but {"haven't"} been mentioned recently.

This means there aren't any notes about them from {shortMeetingText} meetings, parent conversations, or anything else in Student Insights.  The threshold for being included in this list is to have 4 or more absences over the last 45 calendar days.

If you work directly with this student, you could talk with them or reach out to the family.  Or you could connect with a colleague providing support services (eg, SST, attendance officers, counselors, redirect).  If the student in still missing school, attendance contracts might be a next step.

    );
  }
}
CheckStudentsWithHighAbsencesView.contextTypes = {
  districtKey: PropTypes.string.isRequired,
  nowFn: PropTypes.func.isRequired
};
CheckStudentsWithHighAbsencesView.propTypes = {
  limit: PropTypes.number.isRequired,
  totalStudents: PropTypes.number.isRequired,
  studentsWithHighAbsences: PropTypes.arrayOf(PropTypes.shape({
    count: PropTypes.number.isRequired,
    student: PropTypes.shape({
      id: PropTypes.number.isRequired,
      first_name: PropTypes.string.isRequired,
      last_name: PropTypes.string.isRequired,
      grade: PropTypes.string.isRequired,
      house: PropTypes.string
    }).isRequired
  })).isRequired
};

const styles = {
  root: {
    fontSize: 14
  },
  card: {
    margin: 10,
    marginTop: 20,
    border: '1px solid #ccc',
    borderRadius: 3
  },
  helpTeaser: {
    display: 'inline-block',
    paddingLeft: 5,
    paddingRight: 5
  },
  helpContent: {
    margin: 10
  },
  cardTitle: {
    backgroundColor: '#eee',
    padding: 10,
    color: 'black',
    borderBottom: '1px solid #ccc',
    display: 'flex',
    justifyContent: 'space-between'
  },
  person: {
    fontWeight: 'bold'
  },
  line: {
    paddingLeft: 10,
    paddingRight: 10,
    overflow: 'hidden',
    textOverflow: 'ellipsis',
    whiteSpace: 'nowrap'
  },
  middleText: {
    display: 'inline-block',
    paddingLeft: 5,
    paddingRight: 5
  }
};

export default CheckStudentsWithHighAbsences;<commit_msg>progress<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import qs from 'query-string';
import Card from '../components/Card';
import HelpBubble from '../components/HelpBubble';
import GenericLoader from '../components/GenericLoader';
import {eventNoteTypeIdForAbsenceSupportMeeting} from '../helpers/PerDistrict';
import {eventNoteTypeTextMini} from '../components/eventNoteType';
import {apiFetchJson} from '../helpers/apiFetchJson';

// Show teachers their students who have high absences
// but don't have any notes in Insights recently (eg, haven't been brought up in SST).
class CheckStudentsWithHighAbsences extends React.Component {
  constructor(props) {
    super(props);
    this.fetchStudents = this.fetchStudents.bind(this);
    this.renderStudents = this.renderStudents.bind(this);
  }

  fetchStudents() {
    const {educatorId, limit} = this.props;
    const params = educatorId ? {limit, educator_id: educatorId} : {limit};
    const url = `/api/home/students_with_high_absences_json?${qs.stringify(params)}`;
    return apiFetchJson(url);
  }

  render() {
    return (

        <GenericLoader
          style={styles.card}
          promiseFn={this.fetchStudents}
          render={this.renderStudents} />

    );
  }

  renderStudents(json) {
    const props = {
      limit: json.limit,
      totalStudents: json.total_students,
      studentsWithHighAbsences: json.students_with_high_absences
    };
    return <CheckStudentsWithHighAbsencesView {...props} />;
  }
}
CheckStudentsWithHighAbsences.propTypes = {
  educatorId: PropTypes.number.isRequired,
  limit: PropTypes.number // limit the data returned, not the query itself
};
CheckStudentsWithHighAbsences.defaultProps = {
  limit: 100
};

// Pure UI component.
export class CheckStudentsWithHighAbsencesView extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      uiLimit: 4
    };
    this.renderHelpContent = this.renderHelpContent.bind(this);
    this.onMoreStudents = this.onMoreStudents.bind(this);
  }

  onMoreStudents(e) {
    e.preventDefault();
    const {uiLimit} = this.state;
    this.setState({ uiLimit: uiLimit + 4 });
  }

  render() {
    const {studentsWithHighAbsences, totalStudents} = this.props;
    const {uiLimit} = this.state;
    const truncatedStudentsWithHighAbsences = studentsWithHighAbsences.slice(0, uiLimit);

    return (

          Students missing school
          <HelpBubble
            teaser={what does this mean?}
            title="Students missing school"
            content={this.renderHelpContent()} />

        <Card style={{border: 'none'}}>
          {this.renderCopy(totalStudents)}
          {this.renderList(truncatedStudentsWithHighAbsences)}
          {this.renderMore(truncatedStudentsWithHighAbsences)}
        </Card>

    );
  }

  // Branching on singular and plural and zero.
  renderCopy(totalStudents) {
    const now = this.context.nowFn();
    const dateText = now.clone().subtract(45, 'days').format('MMMM Do');
    const sinceEl = Since {dateText}:;
    if (totalStudents === 0) {
      return
There are no students missing school recently who {"haven't"} been mentioned.
;
    } else if (totalStudents === 1) {
      return
There is one student missing school recently who {"hasn't"} been mentioned.  {sinceEl}
;
    } else {
      return
There are {totalStudents} students missing school recently who {"haven't"} been mentioned.  {sinceEl}
;
    }
  }

  renderList(truncatedStudentsWithHighAbsences) {
    if (truncatedStudentsWithHighAbsences.length === 0) return null;
    return (

        {truncatedStudentsWithHighAbsences.map(studentsWithHighAbsences => {
          const {student, count} = studentsWithHighAbsences;
          return (

                <a
                  style={styles.person}
                  href={`/students/${student.id}?column=attendance#absences`}>
                    {student.first_name} {student.last_name}
                   has missed {count} days of school

          );
        })}

    );
  }

  renderMore(truncatedStudentsWithHighAbsences) {
    const {totalStudents, limit, studentsWithHighAbsences} = this.props;

    if (truncatedStudentsWithHighAbsences.length !== studentsWithHighAbsences.length) {
      return
See more
;
    }

    if (studentsWithHighAbsences.length < totalStudents) {
      return
There are {totalStudents} students total.  Start with checking in on these first {limit} students.
;
    }

    return null;
  }

  renderHelpContent() {
    const {districtKey} = this.context;
    const eventNoteTypeId = eventNoteTypeIdForAbsenceSupportMeeting(districtKey);
    const shortMeetingText = eventNoteTypeTextMini(eventNoteTypeId);
    return (

These are all the students that you have access to who have a high number of absences over the last 45 days, but {"haven't"} been mentioned recently.

This means there aren't any notes about them from {shortMeetingText} meetings, parent conversations, or anything else in Student Insights.  The threshold for being included in this list is to have 4 or more absences over the last 45 calendar days.

If you work directly with this student, you could talk with them or reach out to the family.  Or you could connect with a colleague providing support services (eg, SST, attendance officers, counselors, redirect).  If the student in still missing school, attendance contracts might be a next step.

    );
  }
}
CheckStudentsWithHighAbsencesView.contextTypes = {
  districtKey: PropTypes.string.isRequired,
  nowFn: PropTypes.func.isRequired
};
CheckStudentsWithHighAbsencesView.propTypes = {
  limit: PropTypes.number.isRequired,
  totalStudents: PropTypes.number.isRequired,
  studentsWithHighAbsences: PropTypes.arrayOf(PropTypes.shape({
    count: PropTypes.number.isRequired,
    student: PropTypes.shape({
      id: PropTypes.number.isRequired,
      first_name: PropTypes.string.isRequired,
      last_name: PropTypes.string.isRequired,
      grade: PropTypes.string.isRequired,
      house: PropTypes.string
    }).isRequired
  })).isRequired
};

const styles = {
  root: {
    fontSize: 14
  },
  card: {
    margin: 10,
    marginTop: 20,
    border: '1px solid #ccc',
    borderRadius: 3
  },
  helpTeaser: {
    display: 'inline-block',
    paddingLeft: 5,
    paddingRight: 5
  },
  helpContent: {
    margin: 10
  },
  cardTitle: {
    backgroundColor: '#eee',
    padding: 10,
    color: 'black',
    borderBottom: '1px solid #ccc',
    display: 'flex',
    justifyContent: 'space-between'
  },
  person: {
    fontWeight: 'bold'
  },
  line: {
    paddingLeft: 10,
    paddingRight: 10,
    overflow: 'hidden',
    textOverflow: 'ellipsis',
    whiteSpace: 'nowrap'
  },
  middleText: {
    display: 'inline-block',
    paddingLeft: 5,
    paddingRight: 5
  }
};

export default CheckStudentsWithHighAbsences;<|endoftext|>


<commit_before>// framed glossary support, runs in parent window
rc_wait = null
rc_cleanup = null

rc_keypress = function () {
	if (rc_wait) clearTimeout(rc_wait)
	rc_wait = setTimeout(rc_gloss, 850)
	if (rc_cleanup) {
		clearTimeout(rc_cleanup)
		rc_cleanup = null
		}
	return event.keyCode != 13
	}

rc_gloss = function (term) {
	var inp = document.getElementById("rc-find")
	if ('ontouchstart' in window) inp.blur()
	if (!term) term = inp.value
	if (!term) return
	document.getElementById('rc-glossary').contentWindow.postMessage('gloss ' + term, '*')
	}

addEventListener('message', function (event) {
	var d = event.data.split(' ')
	if (d[0] == 'height') document.getElementById('rc-glossary').height = parseInt(d[1]) + 40
	})
<commit_msg>rewrite as object<commit_after>// framed glossary support, runs in parent window
Glossary = {
	//timers...
	wait: null,
	dirty: null,

	input: document.getElementById("rc-find"),
	warning: document.getElementById("rc-warning"),
	window: document.getElementById('rc-glossary').contentWindow,
	touch: 'ontouchstart' in window,

	init: function () { // messages from inside iframe...
		addEventListener('message', function (event) {
			var d = event.data
			if (d.indexOf('height ') === 0) {
				document.getElementById('rc-glossary').height = parseInt(d.substr(7)) + 100
				if (location.hash) Glossary.gloss(location.hash.substr(1))
				}
			else if (d.indexOf('top ') === 0) {
				document.documentElement.scrollTop = document.body.scrollTop = window.pageYOffset = parseInt(d.substr(4)) - 104
				if (!Glossary.touch) Glossary.input.focus()
				}
			else if (d.indexOf('no ') === 0) {
				document.getElementById('rc-warning').textContent = d.substr(3) + ' cannot be found.'
				if (this.dirty) clearTimeout(this.dirty)
				this.dirty = setTimeout(function () {
					Glossary.warning.textContent = ''
					}, 4000)
				}
			})
		},

	gloss: function (term) { // scroll to term...
		if (this.touch) this.input.blur()
		if (!term) term = this.input.value
		if (!term) return
		this.window.postMessage('gloss ' + term, '*')
		if (this.dirty) clearTimeout(this.dirty)
		this.dirty = setTimeout(function () {
			Glossary.input.value = Glossary.warning.textContent = ''
			}, 4000)
		},

	keypress: function () { // user input...
		if (this.wait) clearTimeout(this.wait)
		this.wait = setTimeout(function () {Glossary.gloss()}, 850)
		if (this.dirty) this.dirty = clearTimeout(this.dirty)
		this.warning.textContent = ''
		return event.keyCode != 13
		}

	}

Glossary.init()
<|endoftext|>


<commit_before>var util = require ("util");

/* ItemManager:
 * This object is the main router for all of lic's events.
 * Petals like the IRC manager will register all of its events
 * with the ItemManager instance belonging to the hub.
 * This is the main starting point for all of the events.
 */
var ItemManager = module.exports = function () {
};

ItemManager.prototype.send = function(event) {
	util.puts (util.inspect (event, false, 2, true));
};
<commit_msg>Add sexy listener tree to ItemManager.<commit_after>var util = require ("util");

/* ItemManager:
 * This object is the main router for all of lic's events.
 * Petals like the IRC manager will register all of its events
 * with the ItemManager instance belonging to the hub.
 * This is the main starting point for all of the events.
 */
var ItemManager = module.exports = function () {
	this.listener_tree = {};
};

ItemManager.prototype.send = function(event) {
	util.puts (util.inspect (event, false, 2, true));
};

ItemManager.prototype.listen = function(items, listener, callback) {
	if (Array.isArray (items)) {
		if (typeof items[0] === "string") {
			add_listener.call (this, items, listener);
		} else {
			items.forEach (function(item) {
				add_listener.call (this, item, listener);
			});
		}
	} else {
		if (callback) {
			callback.call (this, new Error("Invalid argument for listen"));
		}
	}

	function add_listener(item, listener) {
		var node = this.listener_tree;
		var item_length = item.length;
		var part;

		for (var i = 0; i < item_length; i++) {
			part = item[i];
			if (typeof node[part] !== "object") {
				node[part] = {};
			}

			if (i === item_length-1) {
				// Append the listener
				if (node[part].listeners) {
					node[part].listeners.push (listener);
				} else {
					node[part].listeners = [listener];
				}
				break;
			}

			node = node[part];
		}
	}
};
<|endoftext|>


<commit_before>import _ from 'underscore';

function sortMetrics(metrics) {
  return _.chain(metrics).sortBy('weight').sortBy('title').value();
}

function normalizeMetrics(metrics) {
  return metrics.map(metric => ({
    ...metric,
    queries: metric.queries.map(query => ({
      ...query,
      result: query.result.map(result => ({
        ...result,
        values: result.values.map(([timestamp, value]) => ({
          time: new Date(timestamp * 1000),
          value,
        })),
      })),
    })),
  }));
}

export default class MonitoringStore {
  constructor() {
    this.groups = [];
    this.deploymentData = [];
  }

  storeMetrics(groups = []) {
    this.groups = groups.map(group => ({
      ...group,
      metrics: normalizeMetrics(sortMetrics(group.metrics)),
    }));
  }

  storeDeploymentData(deploymentData = []) {
    this.deploymentData = deploymentData;
  }

  getMetricsCount() {
    return this.groups.reduce((count, group) => count + group.metrics.length, 0);
  }
}
<commit_msg>ensure prometheus graph values are properly typecast as numbers<commit_after>import _ from 'underscore';

function sortMetrics(metrics) {
  return _.chain(metrics).sortBy('weight').sortBy('title').value();
}

function normalizeMetrics(metrics) {
  return metrics.map(metric => ({
    ...metric,
    queries: metric.queries.map(query => ({
      ...query,
      result: query.result.map(result => ({
        ...result,
        values: result.values.map(([timestamp, value]) => ({
          time: new Date(timestamp * 1000),
          value: Number(value),
        })),
      })),
    })),
  }));
}

export default class MonitoringStore {
  constructor() {
    this.groups = [];
    this.deploymentData = [];
  }

  storeMetrics(groups = []) {
    this.groups = groups.map(group => ({
      ...group,
      metrics: normalizeMetrics(sortMetrics(group.metrics)),
    }));
  }

  storeDeploymentData(deploymentData = []) {
    this.deploymentData = deploymentData;
  }

  getMetricsCount() {
    return this.groups.reduce((count, group) => count + group.metrics.length, 0);
  }
}
<|endoftext|>


<commit_before>alert("Editado");
<commit_msg>nuevo texto<commit_after>alert("Cambio");
console.log("cambios en el archivo")
<|endoftext|>


<commit_before>/*
 * Here are all of the gulp tasks you can use to help manage your blog
 * Use `npm install` to install all the dependencies located in package.json
 * Then `gulp default` to minimize css and images.
 */
const gulp = require('gulp');
const concat = require('gulp-concat');
const uglify = require('gulp-uglify');
const imagemin = require('gulp-imagemin');
const less = require('gulp-less');
const cleanCSS = require('gulp-clean-css');
const replace = require('gulp-replace');
const webp = require('gulp-webp');

gulp.task('js', function minijs() {
  return gulp.src(['js/partials/**.js'])
    .pipe(concat('main.min.js'))
    .pipe(uglify())
    .on('error', (err) => {
      console.log(err.toString());
    })
    .pipe(gulp.dest("js/"))
});

gulp.task("img", function imging() {
  return gulp.src('img/**/*.{png,svg,jpg,webp,jpeg,gif}')
    .pipe(imagemin())
    .on('error', (err) => {
      console.log(err.toString());
    })
    .pipe(gulp.dest('img/'))
});

gulp.task('webp', () =>
  gulp.src('img/**/*.{png,svg,jpg,jpeg,gif}')
    .pipe(webp({
      quality: 60,
      preset: 'photo',
      method: 6
    }))
    .pipe(gulp.dest('img/'))
);

gulp.task('css', function minicss() {
  return gulp.src('css/vendor/bootstrap-iso.css')
    .pipe(cleanCSS())
    .on('error', (err) => {
      console.log(err.toString());
    })
    .pipe(concat('bootstrap-iso.min.css'))
    .pipe(gulp.dest('css/vendor/'));
});

gulp.task("isolate-bootstrap-css", gulp.series('css', function isolating() {
  return gulp.src('css/bootstrap-iso.less')
    .pipe(less())
    .pipe(replace('.bootstrap-iso html', ''))
    .pipe(replace('.bootstrap-iso body', ''))
    .pipe(gulp.dest('css/vendor/'));
}));

gulp.task("default", gulp.series(gulp.parallel('js', 'css', 'img')));
<commit_msg>#183 Update gulpfile<commit_after>/*
 * Here are all of the gulp tasks you can use to help manage your blog
 * Use `npm install` to install all the dependencies located in package.json
 * Then `gulp default` to minimize css and images.
 */
const gulp = require('gulp');
const concat = require('gulp-concat');
const uglify = require('gulp-uglify');
const imagemin = require('gulp-imagemin');
const less = require('gulp-less');
const cleanCSS = require('gulp-clean-css');
const replace = require('gulp-replace');
const webp = require('gulp-webp');

gulp.task('js', function minijs() {
  return gulp.src(['js/partials/**.js'])
    .pipe(concat('main.min.js'))
    .pipe(uglify())
    .on('error', (err) => {
      console.log(err.toString());
    })
    .pipe(gulp.dest("js/"))
});

gulp.task("img", function imging() {
  return gulp.src('img/**/*.{png,svg,jpg,webp,jpeg,gif}')
    .pipe(imagemin())
    .on('error', (err) => {
      console.log(err.toString());
    })
    .pipe(gulp.dest('img/'))
});

gulp.task('webp', () =>
  gulp.src('img/**/*.{png,svg,jpg,jpeg,gif}')
    .pipe(webp({
      quality: 60,
      preset: 'photo',
      method: 6
    }))
    .pipe(gulp.dest('img/'))
);

gulp.task('css', function minicss() {
  return gulp.src('css/vendor/bootstrap-iso.css')
    .pipe(cleanCSS())
    .on('error', (err) => {
      console.log(err.toString());
    })
    .pipe(concat('bootstrap-iso.min.css'))
    .pipe(gulp.dest('css/vendor/'));
});

gulp.task('isolate', function isolateBootstrap() {
  return gulp.src('css/bootstrap-iso.less')
    .pipe(less({strictMath: 'on'}))
    .pipe(replace('.bootstrap-iso html', ''))
    .pipe(replace('.bootstrap-iso body', ''))
    .pipe(gulp.dest('css/vendor/'));
});

gulp.task("isolate-bootstrap-css", gulp.series('isolate', 'css'));

gulp.task("default", gulp.series(gulp.parallel('js', 'css', 'img')));
<|endoftext|>


<commit_before>$( document ).ready(function() {
	$("#dialog").hide ();
	$("#dialog").click (function () {
        $("#dialog").hide ();
    });

	if (connected == 1) {
		loadPage("apps-list.html");
	}
});

$("#forgotpass").on ("click",function () {
	loadPage ("forgot-password-view.html");
});

$("#registerlink").on ("click",function () {
	loadPage ("register-view.html");
});

$("#frensh").on ("click",function () {
	$("#buttongo").html("Se connecter");
	$("#registerlink").html("S'enregister");
	$("#forgotpass").html("Mot de passe oulbié!");
	$("#passwordinput").attr("placeholder", "Mot de passe");
	$("#emailinput").attr("placeholder", "Email");

});
$("#arabic").on ("click",function () {
	$("#buttongo").html("تسجيل الدخول");
	$("#registerlink").html("التسجيل");
	$("#forgotpass").html("إستعادة كلمة السر");
	$("#emailinput").attr("placeholder","البريد");
	$("#passwordinput").attr("placeholder","كلمة السر");

});

$("#buttongo").on("click",function(){
	if($('#emailinput').val () == "demo" && $('#passwordinput').val () == "demo") {
		connected = 1;

		//loadPage("pages/home-view.html");
		loadPage ("home-view.html");
	} else {
		$("#dialog").dialog ();
		$("#dialog").show ();
	}
});

<commit_msg>Update login-view.js<commit_after>var language = "french";

$(document).on ("pageinit", function () {

	$(".language-actions .ui-block-b a").on ("click", function () {
		if (language == "arabic") {
			changeStyle (
				$(this),
				$(".language-actions .ui-block-a a"),
				false
			);
			language =  "french";

			$(".loading-language").css ("display", "block");
			$(".loader").css ("display", "block");
			$(".authentication-error").css ("display", "none");

			displayRedPopup (false, true);
		}
	});

	$(".language-actions .ui-block-a a").on ("click", function () {
		if (language == "french") {
			changeStyle (
				$(this),
				$(".language-actions .ui-block-b a")
			);
			language =  "arabic";

			$(".loading-language").css ("display", "block");
			$(".loader").css ("display", "block");
			$(".authentication-error").css ("display", "none");

			displayRedPopup (false, true);
		}
	});

	$(".submit-login").on ("click", function () {
		testData ();
	});
});

function changeStyle (focusBlock, freeBlock) {
	focusBlock.css ("color", "#FFF");
	focusBlock.css ("background-color", "#ef5a49");
	focusBlock.css ("border-color", "#ef5a49");

	freeBlock.css ("color", "#ef5a49");
	freeBlock.css ("background-color", "#FFF");
	freeBlock.css ("border-color", "#ef5a49");
}

function displayRedPopup (dismissibleBool, translateBool) {
	$("#confirmationPopup").attr ("data-dismissible", dismissibleBool);

	$("#confirmationPopup").popup ({ tolerance: "0px, 12px, 32px, 12px" });
	$("#confirmationPopup").popup ("open");

	setTimeout (
		function () {
			$("#confirmationPopup").popup ("close");
		},
		4000
	);

	$(document).bind ({
		popupafterclose: function (event, ui) {
			if (translateBool) {
				console.log ("yes translate");
				translate ();
			}
		}
	});
}

function translate () {
	// translation
	if (language == "french") {
		$(".email-p input").attr ("placeholder", "Addresse E-mail");
		$(".pass-p input").attr ("placeholder", "Mot de passe");
		$(".submit-login button").text ("Connexion");
		$(".links a.left").text ("Mot de passe oublié ?");

		$(".email-p input").css ("text-align", "left");
		$(".pass-p input").css ("text-align", "left");
	} else {
		$(".email-p input").attr ("placeholder","البريد");
		$(".pass-p input").attr ("placeholder","كلمة السر");
		$(".submit-login button").text ("دخول");
		$(".links a.left").text ("إستعادة كلمة السر");

		$(".email-p input").css ("text-align", "right");
		$(".pass-p input").css ("text-align", "right");
	}
}

function testData () {

	if ($.trim ($(".email-p input").val ()) === '' ||
			$.trim ($(".pass-p input").val ()) === '' ||
			$.trim ($(".email-p input").val ()) !== 'demo' ||
			$.trim ($(".pass-p input").val ()) !== 'demo') {

		$(".loading-language").css ("display", "none");
		$(".loader").css ("display", "none");
		$(".authentication-error").css ("display", "block");

		displayRedPopup (true, false);
	} else {
		connected = 1;
		loadPage ("home-view.html");
	}
}
<|endoftext|>


<commit_before>(function() {
  tinymce.PluginManager.requireLangPack('uploadimage');

  tinymce.create('tinymce.plugins.UploadImage', {
    UploadImage: function(ed, url) {
      var form,
          iframe,
          win,
          throbber,
          editor = ed;

      function showDialog() {
        win = editor.windowManager.open({
          title: ed.translate('Insert an image from your computer'),
          width:  500 + parseInt(editor.getLang('uploadimage.delta_width', 0), 10),
          height: 180 + parseInt(editor.getLang('uploadimage.delta_height', 0), 10),
          body: [
            {type: 'iframe',  url: 'javascript:void(0)'},
            {type: 'textbox', name: 'file', label: ed.translate('Choose an image'), subtype: 'file'},
            {type: 'textbox', name: 'alt',  label: ed.translate('Image description')},
            {type: 'container', classes: 'error', html: "

"},
          ],
          buttons: [
            {
              text: ed.translate('Insert'),
              onclick: insertImage,
              subtype: 'primary'
            },
            {
              text: ed.translate('Cancel'),
              onclick: ed.windowManager.close
            }
          ]
        }, {
          plugin_url: url
        });

        /* WHY DO YOU HATE <form>, TINYMCE!? */
        iframe = win.find("iframe")[0];
        form = createElement('form', {
          action: ed.getParam("uploadimage_form_url", "/tinymce_assets"),
          target: iframe._id,
          method: "POST",
          enctype: 'multipart/form-data',
          accept_charset: "UTF-8",
        });
        // Might have several instances on the same page, so let TinyMCE create unique IDs
        iframe.getEl().name = iframe._id;
        form.appendChild(createElement('input', {type: "hidden", name: "utf8", value: "✓"}));
        form.appendChild(createElement('input', {type: 'hidden', name: 'authenticity_token', value: getMetaContents('csrf-token')}));
        form.appendChild(createElement('input', {type: 'hidden', name: 'hint', value: ed.getParam("uploadimage_hint", "")}));
        win.find("*").each(function(ctrl) {
          var name = ctrl.name(),
              value = ctrl.value(),
              el;
          if (name && typeof(value) != "undefined") {
            /* WHAT IS THIS I DON'T EVEN… WHY DON'T YOU USE name ATTRIBUTES!? */
            el = ctrl.getEl();
            el.name = name;

            form.appendChild(el);
          }
        });

        var el = win.getEl();
        var body = document.getElementById(el.id + "-body");
        body.appendChild(form);
      }

      function insertImage() {
        throbber = new top.tinymce.ui.Throbber(win.getEl());
        throbber.show();

        /* Add event listeners.
         * We remove the existing to avoid them being called twice in case
         * of errors and re-submitting afterwards.
         */
        var target = iframe.getEl();
        if(target.attachEvent) {
          target.detachEvent('onload', uploadDone);
          target.attachEvent('onload', uploadDone);
        } else {
          target.removeEventListener('load', uploadDone);
          target.addEventListener('load', uploadDone, false);
        }

        form.submit();
      }

      function uploadDone() {
        if(throbber) {
          throbber.hide();
        }
      }

      function createElement(element, attributes) {
        var el = document.createElement(element);
        for(var property in attributes) {
          if (!(attributes[property] instanceof Function)) {
            el[property] = attributes[property];
          }
        }

        return el;
      }

      function getMetaContents(mn) {
        var m = document.getElementsByTagName('meta');

        for(var i in m)
          if(m[i].name == mn)
            return m[i].content;

        return null;
      }

      // Add a button that opens a window
      editor.addButton('uploadimage', {
        tooltip: ed.translate('Insert an image from your computer'),
        icon : 'image',
        onclick: showDialog
      });

      // Adds a menu item to the tools menu
      editor.addMenuItem('uploadimage', {
        text: ed.translate('Insert an image from your computer'),
        icon : 'image',
        context: 'insert',
        onclick: showDialog
      });
    }
  });

  tinymce.PluginManager.add('uploadimage', tinymce.plugins.UploadImage);
})();
<commit_msg>Partial response and error handling<commit_after>(function() {
  tinymce.PluginManager.requireLangPack('uploadimage');

  tinymce.create('tinymce.plugins.UploadImage', {
    UploadImage: function(ed, url) {
      var form,
          iframe,
          win,
          throbber,
          editor = ed;

      function showDialog() {
        win = editor.windowManager.open({
          title: ed.translate('Insert an image from your computer'),
          width:  500 + parseInt(editor.getLang('uploadimage.delta_width', 0), 10),
          height: 180 + parseInt(editor.getLang('uploadimage.delta_height', 0), 10),
          body: [
            {type: 'iframe',  url: 'javascript:void(0)'},
            {type: 'textbox', name: 'file', label: ed.translate('Choose an image'), subtype: 'file'},
            {type: 'textbox', name: 'alt',  label: ed.translate('Image description')},
            {type: 'container', classes: 'error', html: "

"},
          ],
          buttons: [
            {
              text: ed.translate('Insert'),
              onclick: insertImage,
              subtype: 'primary'
            },
            {
              text: ed.translate('Cancel'),
              onclick: ed.windowManager.close
            }
          ]
        }, {
          plugin_url: url
        });

        /* WHY DO YOU HATE <form>, TINYMCE!? */
        iframe = win.find("iframe")[0];
        form = createElement('form', {
          action: ed.getParam("uploadimage_form_url", "/tinymce_assets"),
          target: iframe._id,
          method: "POST",
          enctype: 'multipart/form-data',
          accept_charset: "UTF-8",
        });
        // Might have several instances on the same page, so let TinyMCE create unique IDs
        iframe.getEl().name = iframe._id;
        form.appendChild(createElement('input', {type: "hidden", name: "utf8", value: "✓"}));
        form.appendChild(createElement('input', {type: 'hidden', name: 'authenticity_token', value: getMetaContents('csrf-token')}));
        form.appendChild(createElement('input', {type: 'hidden', name: 'hint', value: ed.getParam("uploadimage_hint", "")}));
        win.find("*").each(function(ctrl) {
          var name = ctrl.name(),
              value = ctrl.value(),
              el;
          if (name && typeof(value) != "undefined") {
            /* WHAT IS THIS I DON'T EVEN… WHY DON'T YOU USE name ATTRIBUTES!? */
            el = ctrl.getEl();
            el.name = name;

            form.appendChild(el);
          }
        });

        var el = win.getEl();
        var body = document.getElementById(el.id + "-body");
        body.appendChild(form);
      }

      function insertImage() {
        throbber = new top.tinymce.ui.Throbber(win.getEl());
        throbber.show();

        /* Add event listeners.
         * We remove the existing to avoid them being called twice in case
         * of errors and re-submitting afterwards.
         */
        var target = iframe.getEl();
        if(target.attachEvent) {
          target.detachEvent('onload', uploadDone);
          target.attachEvent('onload', uploadDone);
        } else {
          target.removeEventListener('load', uploadDone);
          target.addEventListener('load', uploadDone, false);
        }

        form.submit();
      }

      function uploadDone() {
        if(throbber) {
          throbber.hide();
        }

        var target = iframe.getEl();
        if(target.document || target.contentDocument) {
          var doc = target.contentDocument || target.contentWindow.document;
          handleResponse(doc.getElementsByTagName("body")[0].innerHTML);
        } else {
          handleError("Didn't get a response from the server");
        }
      }

      function handleResponse(ret) {
        try {
          var json = tinymce.util.JSON.parse(ret);
          console.log("Parsed", json);

          if(json["error"]) {
            handleError(json["error"]["message"]);
          } else {
            ed.execCommand('mceInsertContent', false, buildHTML(json));
            ed.windowManager.close();
          }
        } catch(e) {
          handleError('Got a bad response from the server');
        }
      }

      function handleError(error) {
        var message = win.find(".error")[0].getEl();

        if(message)
          message.getElementsByTagName("p").innerHTML = ed.translate(error);
      }

      function createElement(element, attributes) {
        var el = document.createElement(element);
        for(var property in attributes) {
          if (!(attributes[property] instanceof Function)) {
            el[property] = attributes[property];
          }
        }

        return el;
      }

      function buildHTML(json) {
        var default_class = ed.getParam("uploadimage_default_img_class", "");
        var alt_text = "FIXME PLOX";//document.getElementById("alt_text").value;

        var imgstr = "";

        return imgstr;
      }

      function getMetaContents(mn) {
        var m = document.getElementsByTagName('meta');

        for(var i in m)
          if(m[i].name == mn)
            return m[i].content;

        return null;
      }

      // Add a button that opens a window
      editor.addButton('uploadimage', {
        tooltip: ed.translate('Insert an image from your computer'),
        icon : 'image',
        onclick: showDialog
      });

      // Adds a menu item to the tools menu
      editor.addMenuItem('uploadimage', {
        text: ed.translate('Insert an image from your computer'),
        icon : 'image',
        context: 'insert',
        onclick: showDialog
      });
    }
  });

  tinymce.PluginManager.add('uploadimage', tinymce.plugins.UploadImage);
})();
<|endoftext|>


<commit_before>module.exports = {

    incoming: function (message, args) {
        console.log(args);
        console.log(args.address.conversation);
        // add info to objs
        // access data from existing options

        // 1 try looking up an existing objs
        // 2 update info if found
        // make routing decision based on info -- this prob goes to sent
        // 3 if not found, create
        var thisUser = global.agents[message.user.id] || global.users[message.user.id];

        if (message.text && thisUser !== 'undefined') {
            if (message.user.isStaff) {
                global.agents[message.user.id] = new global.User(message);
            } else {
                global.users[message.user.id] = new global.User(message);
            }
        }
        console.log('agents');
        console.log(global.agents);
        console.log('users')
        console.log(global.users);
        console.log('************');
        return message;
    },

    outgoing: function (message, args) {
        console.log(args);
        console.log('===========');
        if (message.address.user.id === 'hannah') {
            message.address = {
                id: 'L8YqoKYYo7x|000000000000000001',

                channelId: 'directline',

                user: { id: 'scott', name: 'scott' },

                conversation: { id: 'L8YqoKYYo7x' },

                bot: { id: 'handoffbotdev@Vyk0lb3f67A', name: 'HandOffBot' },

                serviceUrl: 'https://directline.botframework.com',

                useAuth: true
            }

    }
        return message
},

    connectToAgent: function (data) {

    }
}
<commit_msg>update convo id<commit_after>module.exports = {

    incoming: function (message, args) {
        console.log(args);
        console.log(args.address.conversation);
        // add info to objs
        // access data from existing options

        // 1 try looking up an existing objs
        // 2 update info if found
        // make routing decision based on info -- this prob goes to sent
        // 3 if not found, create
        var thisUser = global.agents[message.user.id] || global.users[message.user.id];

        if (message.text && thisUser !== 'undefined') {
            if (message.user.isStaff) {
                global.agents[message.user.id] = new global.User(message);
            } else {
                global.users[message.user.id] = new global.User(message);
            }
        }
        console.log('agents');
        console.log(global.agents);
        console.log('users')
        console.log(global.users);
        console.log('************');
        return message;
    },

    outgoing: function (message, args) {
        console.log(args);
        console.log('===========');
        if (message.address.user.id === 'hannah') {
            message.address = {
                id: 'L8YqoKYYo7x|000000000000000001',

                channelId: 'directline',

                user: { id: 'scott', name: 'scott' },

                conversation: { id: 'AUBYa4BHo8U'  },

                bot: { id: 'handoffbotdev@Vyk0lb3f67A', name: 'HandOffBot' },

                serviceUrl: 'https://directline.botframework.com',

                useAuth: true
            }

    }
        return message
},

    connectToAgent: function (data) {

    }
}
<|endoftext|>


<commit_before>'use strict';
let _ADMIN;

import '../sass/admin.scss';
import Alerts from './components/Alerts.js';
import Confirm from './components/Confirm.js';
import CopyToClipboard from './components/CopyToClipboard.js';
import DisabledElements from './components/DisabledElements.js';
import DynamicTable from './components/DynamicTable.js';
import IndexButtons from './components/IndexButtons.js';
import InputHelper from './components/InputHelper.js';
import Modalize from './components/Modalize.js';
import Notes from './components/Notes.js';
import Repeater from './components/Repeater.js';
import Revealer from './components/Revealer.js';
import Searcher from './components/Searcher.js';
import Sortable from './components/Sortable.js';
import Stripes from './components/Stripes.js';
import Tabs from './components/Tabs.js';
import Toggles from './components/Toggles.js';
import Wysiwyg from './components/Wysiwyg.js';

_ADMIN = function() {
    return {

        /**
         * The admin module namespace
         */
        'namespace': 'nails/module-admin',

        /**
         * All the registered plugins
         */
        'instances': {},

        /**
         * Registers a new plugin
         * @param {String} slug The name of the plugin
         * @param plugin
         */
        'registerPlugin': function(vendor, slug, plugin) {
            if (typeof this.instances[vendor] === 'undefined') {
                this.instances[vendor] = {};
            }
            this.instances[vendor][slug] = plugin;
            return this;
        },

        /**
         * Triggers an event
         * @param eventName
         */
        'trigger': function(eventName, detail) {
            document
                .dispatchEvent(
                    new CustomEvent(eventName, {detail: detail})
                );
            return this;
        },

        /**
         * Allows plugins to listen for events
         * @param {String} event The event to listen for
         * @param {function} callback The callback to execute
         */
        'on': function(event, callback) {
            document
                .addEventListener(event, callback);
            return this;
        },

        /**
         * Triggers a UI refresh
         * @param domElement The domElement to focus the refresh on
         */
        'refreshUi': function(domElement) {
            this.log('Refreshing UI', domElement || document);
            this.trigger('admin:refresh-ui', {domElement: domElement || document});
            return this;
        },

        /**
         * Allows plugins to register callbacks for UI refreshing
         * @param {function} callback The callback to execute
         */
        'onRefreshUi': function(callback) {
            this.on('admin:refresh-ui', function(e) {
                callback(e, e.detail ? e.detail.domElement : null);
            });
            return this;
        },

        /**
         * Triggers a UI destroy
         * @param domElement The domElement to focus the destroy on
         */
        'destroyUi': function(domElement) {
            this.log('Destroying UI', domElement || document);
            this.trigger('admin:destroy-ui', {domElement: domElement || document});
            return this;
        },

        /**
         * Allows plugins to register callbacks for UI destruction
         * @param {function} callback The callback to execute
         */
        'onDestroyUi': function(callback) {
            this.on('admin:destroy-ui', function(e) {
                callback(e, e.detail ? e.detail.domElement : null);
            });
            return this;
        },

        // --------------------------------------------------------------------------

        /**
         * Write a log to the console
         * @return {void}
         */
        'log': function() {
            if (typeof (console.log) === 'function') {
                console.log("\x1b[33m[Admin]\x1b[0m", ...arguments);
            }
        },

        // --------------------------------------------------------------------------

        /**
         * Write a warning to the console
         * @return {void}
         */
        'warn': function(message, payload) {
            if (typeof (console.warn) === 'function') {
                console.warn("\x1b[33m[Admin]\x1b[0m", ...arguments);
            }
        }
    };
};

window.NAILS.ADMIN = new _ADMIN();

window
    .NAILS
    .ADMIN
    .registerPlugin(window.NAILS.ADMIN.namespace, 'Alerts', new Alerts(window.NAILS.ADMIN))
    .registerPlugin(window.NAILS.ADMIN.namespace, 'Confirm', new Confirm(window.NAILS.ADMIN))
    .registerPlugin(window.NAILS.ADMIN.namespace, 'CopyToClipboard', new CopyToClipboard(window.NAILS.ADMIN))
    .registerPlugin(window.NAILS.ADMIN.namespace, 'DisabledElements', new DisabledElements())
    .registerPlugin(window.NAILS.ADMIN.namespace, 'DynamicTable', new DynamicTable(window.NAILS.ADMIN))
    .registerPlugin(window.NAILS.ADMIN.namespace, 'IndexButtons', new IndexButtons(window.NAILS.ADMIN))
    .registerPlugin(window.NAILS.ADMIN.namespace, 'InputHelper', new InputHelper(window.NAILS.ADMIN))
    .registerPlugin(window.NAILS.ADMIN.namespace, 'Modalize', new Modalize(window.NAILS.ADMIN))
    .registerPlugin(window.NAILS.ADMIN.namespace, 'Notes', new Notes(window.NAILS.ADMIN))
    .registerPlugin(window.NAILS.ADMIN.namespace, 'Repeater', new Repeater(window.NAILS.ADMIN))
    .registerPlugin(window.NAILS.ADMIN.namespace, 'Revealer', new Revealer(window.NAILS.ADMIN))
    .registerPlugin(window.NAILS.ADMIN.namespace, 'Searcher', new Searcher(window.NAILS.ADMIN))
    .registerPlugin(window.NAILS.ADMIN.namespace, 'Sortable', new Sortable(window.NAILS.ADMIN))
    .registerPlugin(window.NAILS.ADMIN.namespace, 'Stripes', new Stripes(window.NAILS.ADMIN))
    .registerPlugin(window.NAILS.ADMIN.namespace, 'Tabs', new Tabs(window.NAILS.ADMIN))
    .registerPlugin(window.NAILS.ADMIN.namespace, 'Toggles', new Toggles(window.NAILS.ADMIN))
    .registerPlugin(window.NAILS.ADMIN.namespace, 'Wysiwyg', new Wysiwyg(window.NAILS.ADMIN));
<commit_msg>Adda _ADMIN_PROXY class<commit_after>'use strict';
let _ADMIN, _ADMIN_PROXY;

import '../sass/admin.scss';
import Alerts from './components/Alerts.js';
import Confirm from './components/Confirm.js';
import CopyToClipboard from './components/CopyToClipboard.js';
import DisabledElements from './components/DisabledElements.js';
import DynamicTable from './components/DynamicTable.js';
import IndexButtons from './components/IndexButtons.js';
import InputHelper from './components/InputHelper.js';
import Modalize from './components/Modalize.js';
import Notes from './components/Notes.js';
import Repeater from './components/Repeater.js';
import Revealer from './components/Revealer.js';
import Searcher from './components/Searcher.js';
import Sortable from './components/Sortable.js';
import Stripes from './components/Stripes.js';
import Tabs from './components/Tabs.js';
import Toggles from './components/Toggles.js';
import Wysiwyg from './components/Wysiwyg.js';

_ADMIN_PROXY = function(vendor, slug) {
    return {
        'vendor': vendor,
        'slug': slug,
        'onRefreshUi': function(callback) {
            window.NAILS.ADMIN.onRefreshUi(callback);
            return this;
        },
        'refreshUi': function(domElement) {
            this.log('UI refresh requested', domElement || document);
            window.NAILS.ADMIN.refreshUi(domElement);
            return this;
        },
        'destroyUi': function(domElement) {
            window.NAILS.ADMIN.destroyUi(domElement);
            return this;
        },
        'onDestroyUi': function(callback) {
            window.NAILS.ADMIN.onDestroyUi(callback);
            return this;
        },
        'log': function() {
            if (typeof (console.log) === 'function') {
                console.log(
                    "\x1b[33m[" +
                    this.vendor +
                    ': ' +
                    this.slug +
                    "]\x1b[0m",
                    ...arguments
                );
            }
        },
        'warn': function() {
            if (typeof (console.warn) === 'function') {
                console.warn(
                    "\x1b[33m[" +
                    this.vendor +
                    ': ' +
                    this.slug +
                    "]\x1b[0m",
                    ...arguments
                );
            }
        },
        'error': function() {
            if (typeof (console.error) === 'function') {
                console.error(
                    "\x1b[33m[" +
                    this.vendor +
                    ': ' +
                    this.slug +
                    "]\x1b[0m",
                    ...arguments
                );
            }
        }
    }
}

_ADMIN = function() {
    return {

        /**
         * The admin module namespace
         */
        'namespace': 'nails/module-admin',

        /**
         * All the registered plugins
         */
        'instances': {},

        /**
         * Registers a new plugin
         * @param {String} slug The name of the plugin
         * @param plugin
         */
        'registerPlugin': function(vendor, slug, plugin) {

            if (typeof this.instances[vendor] === 'undefined') {
                this.instances[vendor] = {};
            }

            if (typeof plugin === 'function') {

                this.instances[vendor][slug] = plugin(
                    new _ADMIN_PROXY(vendor, slug)
                );

            } else {
                this.instances[vendor][slug] = plugin;
            }

            return this;
        },

        /**
         * Triggers an event
         * @param eventName
         */
        'trigger': function(eventName, detail) {
            document
                .dispatchEvent(
                    new CustomEvent(eventName, {detail: detail})
                );
            return this;
        },

        /**
         * Allows plugins to listen for events
         * @param {String} event The event to listen for
         * @param {function} callback The callback to execute
         */
        'on': function(event, callback) {
            document
                .addEventListener(event, callback);
            return this;
        },

        /**
         * Triggers a UI refresh
         * @param domElement The domElement to focus the refresh on
         */
        'refreshUi': function(domElement) {
            this.log('Refreshing UI', domElement || document);
            this.trigger('admin:refresh-ui', {domElement: domElement || document});
            return this;
        },

        /**
         * Allows plugins to register callbacks for UI refreshing
         * @param {function} callback The callback to execute
         */
        'onRefreshUi': function(callback) {
            this.on('admin:refresh-ui', function(e) {
                callback(e, e.detail ? e.detail.domElement : null);
            });
            return this;
        },

        /**
         * Triggers a UI destroy
         * @param domElement The domElement to focus the destroy on
         */
        'destroyUi': function(domElement) {
            this.log('Destroying UI', domElement || document);
            this.trigger('admin:destroy-ui', {domElement: domElement || document});
            return this;
        },

        /**
         * Allows plugins to register callbacks for UI destruction
         * @param {function} callback The callback to execute
         */
        'onDestroyUi': function(callback) {
            this.on('admin:destroy-ui', function(e) {
                callback(e, e.detail ? e.detail.domElement : null);
            });
            return this;
        },

        // --------------------------------------------------------------------------

        /**
         * Write a log to the console
         * @return {void}
         */
        'log': function() {
            if (typeof (console.log) === 'function') {
                console.log("\x1b[33m[Admin]\x1b[0m", ...arguments);
            }
        },

        // --------------------------------------------------------------------------

        /**
         * Write a warning to the console
         * @return {void}
         */
        'warn': function(message, payload) {
            if (typeof (console.warn) === 'function') {
                console.warn("\x1b[33m[Admin]\x1b[0m", ...arguments);
            }
        }
    };
};

window.NAILS.ADMIN = new _ADMIN();

window
    .NAILS
    .ADMIN
    .registerPlugin(
        window.NAILS.ADMIN.namespace,
        'Alerts',
        function(controller) {
            return new Alerts(controller);
        }
    )
    .registerPlugin(
        window.NAILS.ADMIN.namespace,
        'Confirm',
        function(controller) {
            return new Confirm(controller);
        }
    )
    .registerPlugin(
        window.NAILS.ADMIN.namespace,
        'CopyToClipboard',
        function(controller) {
            return new CopyToClipboard(controller);
        }
    )
    .registerPlugin(
        window.NAILS.ADMIN.namespace,
        'DisabledElements',
        function(controller) {
            return new DisabledElements(controller);
        }
    )
    .registerPlugin(
        window.NAILS.ADMIN.namespace,
        'DynamicTable',
        function(controller) {
            return new DynamicTable(controller);
        }
    )
    .registerPlugin(
        window.NAILS.ADMIN.namespace,
        'IndexButtons',
        function(controller) {
            return new IndexButtons(controller);
        }
    )
    .registerPlugin(
        window.NAILS.ADMIN.namespace,
        'InputHelper',
        function(controller) {
            return new InputHelper(controller);
        }
    )
    .registerPlugin(
        window.NAILS.ADMIN.namespace,
        'Modalize',
        function(controller) {
            return new Modalize(controller);
        }
    )
    .registerPlugin(
        window.NAILS.ADMIN.namespace,
        'Notes',
        function(controller) {
            return new Notes(controller);
        }
    )
    .registerPlugin(
        window.NAILS.ADMIN.namespace,
        'Repeater',
        function(controller) {
            return new Repeater(controller);
        }
    )
    .registerPlugin(
        window.NAILS.ADMIN.namespace,
        'Revealer',
        function(controller) {
            return new Revealer(controller);
        }
    )
    .registerPlugin(
        window.NAILS.ADMIN.namespace,
        'Searcher',
        function(controller) {
            return new Searcher(controller);
        }
    )
    .registerPlugin(
        window.NAILS.ADMIN.namespace,
        'Sortable',
        function(controller) {
            return new Sortable(controller);
        }
    )
    .registerPlugin(
        window.NAILS.ADMIN.namespace,
        'Stripes',
        function(controller) {
            return new Stripes(controller);
        }
    )
    .registerPlugin(
        window.NAILS.ADMIN.namespace,
        'Tabs',
        function(controller) {
            return new Tabs(controller);
        }
    )
    .registerPlugin(
        window.NAILS.ADMIN.namespace,
        'Toggles',
        function(controller) {
            return new Toggles(controller);
        }
    )
    .registerPlugin(
        window.NAILS.ADMIN.namespace,
        'Wysiwyg',
        function(controller) {
            return new Wysiwyg(controller);
        }
    )
<|endoftext|>


<commit_before>#!/usr/bin/env node

const { spawn } = require('child_process');
const { promisify } = require('util');
const {
  readdir: readdirRaw,
  readFile: readFileRaw,
  writeFile: writeFileRaw,
  statSync,
  cop,
} = require('fs');
const { join } = require('path');

const readdir = promisify(readdirRaw);
const readFile = promisify(readFileRaw);
const writeFile = promisify(writeFileRaw);

const p = l => join(__dirname, '..', ...l);
const logger = console;

const exec = async (command, args = [], options = {}) =>
  new Promise((resolve, reject) => {
    const child = spawn(command, args, { ...options, stdio: 'inherit', shell: true });

    child
      .on('close', code => {
        if (code) {
          reject();
        } else {
          resolve();
        }
      })
      .on('error', e => {
        logger.error(e);
      });
  });

const hasBuildScript = async l => {
  const text = await readFile(l, 'utf8');
  const json = JSON.parse(text);

  return !!json.scripts['build-storybook'];
};

const handleExamples = async files => {
  const deployables = files.filter(f => {
    const packageJsonLocation = p(['examples', f, 'package.json']);
    const stats = statSync(packageJsonLocation);

    return stats.isFile() && hasBuildScript(packageJsonLocation);
  });

  await deployables.reduce(async (acc, d) => {
    await acc;

    logger.log('');
    logger.log(
      `-----------------${Array(d.length)
        .fill('-')
        .join('')}`
    );
    logger.log(`▶  building: ${d}`);
    logger.log(
      `-----------------${Array(d.length)
        .fill('-')
        .join('')}`
    );
    const out = p(['built-storybooks', d]);
    const cwd = p(['examples', d]);

    await exec(`yarn`, [`build-storybook`, `--output-dir=${out}`, '--quiet'], { cwd });

    logger.log('-------');
    logger.log('✅ done');
    logger.log('-------');
  }, Promise.resolve());

  logger.log('');
  logger.log(`📑 creating index`);

  const indexLocation = p(['built-storybooks', 'index.html']);
  const indexContent = `
    <style>
      body {
        background: black;
        color: white;
      }
      #frame {
        position: absolute;
        left: 0;
        right: 0;
        width: 100vw;
        height: calc(100vh - 30px);
        bottom: 0;
        top: 30px;
        border: 0 none;
        margin: 0;
        padding: 0;
      }
      #select {
        position: absolute;
        top: 0;
        right: 100px;
        left: 10px;
        height: 30px;
        width: calc(100vw - 120px);
        background: black;
        color: white;
        border: 0 none;
        border-radius: 0;
        padding: 10px;
        box-sizing: border-box;
      }
      #open {
        position: absolute;
        top: 0;
        right: 0;
        width: 100px;
        height: 30px;
        background: black;
        color: white;
        border: 0 none;
        border-radius: 0;
        padding: 10px;
        box-sizing: border-box;
      }
    </style>

    <script>
      function handleClick() {
        var value = document.getElementById("select").value;
        window.location = document.location.origin + value;
      }
      function handleSelect() {
        var value = document.getElementById("select").value;
        var frame = document.getElementById("frame");

        sessionStorage.clear();
        localStorage.clear();

        frame.setAttribute('src', value);
      }
    </script>

    <button id="open" onclick="handleClick()">open</button>

    <select id="select" onchange="handleSelect()">
      ${deployables.map(i => `<option value="/${i}/">${i}</option>`).join('\n')}
    </select>

    <iframe id="frame" src="/${deployables[0]}/" />
  `;

  await writeFile(indexLocation, indexContent);

  logger.log('-------');
  logger.log('✅ done');
  logger.log('-------');
};

const run = async () => {
  const examples = await readdir(p(['examples']));

  await handleExamples(examples);
};

run();
<commit_msg>ADD reject<commit_after>#!/usr/bin/env node

const { spawn } = require('child_process');
const { promisify } = require('util');
const {
  readdir: readdirRaw,
  readFile: readFileRaw,
  writeFile: writeFileRaw,
  statSync,
  cop,
} = require('fs');
const { join } = require('path');

const readdir = promisify(readdirRaw);
const readFile = promisify(readFileRaw);
const writeFile = promisify(writeFileRaw);

const p = l => join(__dirname, '..', ...l);
const logger = console;

const exec = async (command, args = [], options = {}) =>
  new Promise((resolve, reject) => {
    const child = spawn(command, args, { ...options, stdio: 'inherit', shell: true });

    child
      .on('close', code => {
        if (code) {
          reject();
        } else {
          resolve();
        }
      })
      .on('error', e => {
        logger.error(e);
        reject();
      });
  });

const hasBuildScript = async l => {
  const text = await readFile(l, 'utf8');
  const json = JSON.parse(text);

  return !!json.scripts['build-storybook'];
};

const handleExamples = async files => {
  const deployables = files.filter(f => {
    const packageJsonLocation = p(['examples', f, 'package.json']);
    const stats = statSync(packageJsonLocation);

    return stats.isFile() && hasBuildScript(packageJsonLocation);
  });

  await deployables.reduce(async (acc, d) => {
    await acc;

    logger.log('');
    logger.log(
      `-----------------${Array(d.length)
        .fill('-')
        .join('')}`
    );
    logger.log(`▶  building: ${d}`);
    logger.log(
      `-----------------${Array(d.length)
        .fill('-')
        .join('')}`
    );
    const out = p(['built-storybooks', d]);
    const cwd = p(['examples', d]);

    await exec(`yarn`, [`build-storybook`, `--output-dir=${out}`, '--quiet'], { cwd });

    logger.log('-------');
    logger.log('✅ done');
    logger.log('-------');
  }, Promise.resolve());

  logger.log('');
  logger.log(`📑 creating index`);

  const indexLocation = p(['built-storybooks', 'index.html']);
  const indexContent = `
    <style>
      body {
        background: black;
        color: white;
      }
      #frame {
        position: absolute;
        left: 0;
        right: 0;
        width: 100vw;
        height: calc(100vh - 30px);
        bottom: 0;
        top: 30px;
        border: 0 none;
        margin: 0;
        padding: 0;
      }
      #select {
        position: absolute;
        top: 0;
        right: 100px;
        left: 10px;
        height: 30px;
        width: calc(100vw - 120px);
        background: black;
        color: white;
        border: 0 none;
        border-radius: 0;
        padding: 10px;
        box-sizing: border-box;
      }
      #open {
        position: absolute;
        top: 0;
        right: 0;
        width: 100px;
        height: 30px;
        background: black;
        color: white;
        border: 0 none;
        border-radius: 0;
        padding: 10px;
        box-sizing: border-box;
      }
    </style>

    <script>
      function handleClick() {
        var value = document.getElementById("select").value;
        window.location = document.location.origin + value;
      }
      function handleSelect() {
        var value = document.getElementById("select").value;
        var frame = document.getElementById("frame");

        sessionStorage.clear();
        localStorage.clear();

        frame.setAttribute('src', value);
      }
    </script>

    <button id="open" onclick="handleClick()">open</button>

    <select id="select" onchange="handleSelect()">
      ${deployables.map(i => `<option value="/${i}/">${i}</option>`).join('\n')}
    </select>

    <iframe id="frame" src="/${deployables[0]}/" />
  `;

  await writeFile(indexLocation, indexContent);

  logger.log('-------');
  logger.log('✅ done');
  logger.log('-------');
};

const run = async () => {
  const examples = await readdir(p(['examples']));

  await handleExamples(examples);
};

run();
<|endoftext|>


<commit_before>import React, { PropTypes, Component } from "react";
import ReactDOM from "react-dom";
import {
  BrowserRouter as Router,
  Route,
  Link,
  Redirect,
  withRouter
} from "react-router-dom";

import {
  DASHBOARD_OVERVIEW_URL,
  DASHBOARD_INDEX_URL,
  LOGIN_URL,
  HOME_URL,
  SETTINGS_URL, LOGOUT_URL
} from "./urls/constants";
import { Authenticator } from "./authentication/auth";
import LoginView from "./authentication/login";
import Header from "./fragments/header";
import Footer from "./fragments/footer";
import { HomePage } from "./home/home";
import {Dashboard} from "./dashboard";
import {LogoutView} from "./authentication/logout";

const BetterSelfRouter = () => (
  <Router>

      {/*Public Routes*/}
      <Route exact path={HOME_URL} component={HomePage} />

      <Route path={LOGIN_URL} component={LoginView} />
      <Route path={LOGOUT_URL} component={LogoutView} />

      {/*<Route path={SETTINGS_URL} component={LoggedOutView} />*/}
      {/*<Route path={DASHBOARD_OVERVIEW_URL} component={LoggedOutView} />*/}

      {/*Private Routes*/}
      <PrivateRoute path={DASHBOARD_INDEX_URL} component={Dashboard} />

  </Router>
);

const PrivateRoute = ({ component, ...rest }) => (
  <Route
    {...rest}
    render={props =>
      (Authenticator.isAuthenticated
        ? React.createElement(component, props)
        : <Redirect
            to={{
              pathname: LOGIN_URL,
              state: { from: props.location }
            }}
          />)}
  />
);

ReactDOM.render(<BetterSelfRouter />, document.getElementById("root"));
<commit_msg>Prettify<commit_after>import React, { PropTypes, Component } from "react";
import ReactDOM from "react-dom";
import {
  BrowserRouter as Router,
  Route,
  Link,
  Redirect,
  withRouter
} from "react-router-dom";

import {
  DASHBOARD_INDEX_URL,
  LOGIN_URL,
  HOME_URL,
  LOGOUT_URL
} from "./urls/constants";
import { Authenticator } from "./authentication/auth";
import LoginView from "./authentication/login";
import Header from "./fragments/header";
import Footer from "./fragments/footer";
import { HomePage } from "./home/home";
import { Dashboard } from "./dashboard";
import { LogoutView } from "./authentication/logout";

const BetterSelfRouter = () => (
  <Router>

      {/*Public Routes*/}
      <Route exact path={HOME_URL} component={HomePage} />

      <Route path={LOGIN_URL} component={LoginView} />
      <Route path={LOGOUT_URL} component={LogoutView} />

      {/* TODO Routes and Components */}
      {/*<Route path={SETTINGS_URL} component={LoggedOutView} />*/}
      {/*<Route path={DASHBOARD_OVERVIEW_URL} component={LoggedOutView} />*/}

      {/*Private Routes*/}
      <PrivateRoute path={DASHBOARD_INDEX_URL} component={Dashboard} />

  </Router>
);

const PrivateRoute = ({ component, ...rest }) => (
  <Route
    {...rest}
    render={props =>
      (Authenticator.isAuthenticated
        ? React.createElement(component, props)
        : <Redirect
            to={{
              pathname: LOGIN_URL,
              state: { from: props.location }
            }}
          />)}
  />
);

ReactDOM.render(<BetterSelfRouter />, document.getElementById("root"));
<|endoftext|>


<commit_before>function Game(){
  this.$track = $('#racetrack');
  this.finishLine = this.$track.width() - 90;
}

function Player(id,img){
  this.player = $('.player')[id - 1];
  this.position = 10;
  this.img = img;
}

Player.prototype.updateImage = function(){
  $player = $(this.player);
  $player.css('background-image', 'url(' + this.img + ')');
};

Player.prototype.move = function(){
  this.position += 20;
};

Player.prototype.updatePosition = function(){
  $player = $(this.player);
  $player.css('margin-left', this.position);
};

function checkWinner(player, game){
  var $modal_message = $('.lead');

  if( player.position > game.finishLine ){
    // var again = window.confirm("Player " + player.player.id + " has won!" + "\n Play Again?");
    $('.hacky-workaround').click();
    $modal_message.html("Player " + player.player.id + " has won!" + "\n Play Again?");
    // if (again === true) {
    //   location.reload(document);
    // }
  }
}

function wikipediaRedirect(){
  window.location.replace("http://en.wikipedia.org/wiki/Special:Random");
  return false;
};

$(document).ready(function() {
    var game = new Game();
    var player1 = new Player(1, "./assets/img/nyanCat.gif");
    var player2 = new Player(2, "./assets/img/zombieCat.gif");

    player1.updateImage();
    player2.updateImage();

    $(document).on('keyup', function(keyPress){

      if(keyPress.keyCode === 80) {
        player1.move();
        player1.updatePosition();
        checkWinner(player1, game);
      } else if (keyPress.keyCode === 81) {
        player2.move();
        player2.updatePosition();
        checkWinner(player2, game);
      }
    });

    // $('.no-button').click(function (){
    //   window.location.replace("http://en.wikipedia.org/wiki/Special:Random");
    //   return false;
    // });

    $('.no-button').click(function (){
      var timedRedirct = setInterval(wikipediaRedirect, 2500);
    });
  });<commit_msg>Refactor modal message code. Make redirect link stop replacing window<commit_after>function Game(){
  this.$track = $('#racetrack');
  this.finishLine = this.$track.width() - 90;
}

function Player(id,img){
  this.player = $('.player')[id - 1];
  this.position = 10;
  this.img = img;
}

Player.prototype.updateImage = function(){
  $player = $(this.player);
  $player.css('background-image', 'url(' + this.img + ')');
};

Player.prototype.move = function(){
  this.position += 20;
};

Player.prototype.stop = function(){
  this.position -= 20;
};

Player.prototype.updatePosition = function(){
  $player = $(this.player);
  $player.css('margin-left', this.position);
};

function checkWinner(player, game){
  $('.lead').html("Player " + player.player.id + " has won!" + "\n Play Again?");

  if( player.position > game.finishLine ){
    // var again = window.confirm("Player " + player.player.id + " has won!" + "\n Play Again?");
    player.stop();
    $('.hacky-workaround').click($('#myModal').foundation('reveal','open'));

    // if (again === true) {
    //   location.reload(document);
    // }
  }
}

function wikipediaRedirect(){
  window.location.replace("http://en.wikipedia.org/wiki/Special:Random");
  return false;
};

$(document).ready(function() {
    var game = new Game();
    var player1 = new Player(1, "./assets/img/nyanCat.gif");
    var player2 = new Player(2, "./assets/img/zombieCat.gif");

    player1.updateImage();
    player2.updateImage();

    $(document).on('keyup', function(keyPress){

      if(keyPress.keyCode === 80) {
        player1.move();
        player1.updatePosition();
        checkWinner(player1, game);
      } else if (keyPress.keyCode === 81) {
        player2.move();
        player2.updatePosition();
        checkWinner(player2, game);
      }
    });

    // $('.no-button').click(function (){
    //   window.location.replace("http://en.wikipedia.org/wiki/Special:Random");
    //   return false;
    // });

    $('.no-button').click(function (){
      var timedRedirct = setInterval(wikipediaRedirect, 2500);
    });
  });<|endoftext|>