<commit_before>/*
 RequireJS 2.1.11 Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
 Available via the MIT or new BSD license.
 see: http://github.com/jrburke/requirejs for details
*/
var requirejs,require,define;
(function(ca){function G(b){return"[object Function]"===M.call(b)}function H(b){return"[object Array]"===M.call(b)}function v(b,c){if(b){var d;for(d=0;d<b.length&&(!b[d]||!c(b[d],d,b));d+=1);}}function U(b,c){if(b){var d;for(d=b.length-1;-1<d&&(!b[d]||!c(b[d],d,b));d-=1);}}function s(b,c){return ga.call(b,c)}function j(b,c){return s(b,c)&&b[c]}function B(b,c){for(var d in b)if(s(b,d)&&c(b[d],d))break}function V(b,c,d,g){c&&B(c,function(c,h){if(d||!s(b,h))g&&"object"===typeof c&&c&&!H(c)&&!G(c)&&!(c instanceof
RegExp)?(b[h]||(b[h]={}),V(b[h],c,d,g)):b[h]=c});return b}function t(b,c){return function(){return c.apply(b,arguments)}}function da(b){throw b;}function ea(b){if(!b)return b;var c=ca;v(b.split("."),function(b){c=c[b]});return c}function C(b,c,d,g){c=Error(c+"\nhttp://requirejs.org/docs/errors.html#"+b);c.requireType=b;c.requireModules=g;d&&(c.originalError=d);return c}function ha(b){function c(a,e,b){var f,n,c,d,g,h,i,I=e&&e.split("/");n=I;var m=l.map,k=m&&m["*"];if(a&&"."===a.charAt(0))if(e){n=
I.slice(0,I.length-1);a=a.split("/");e=a.length-1;l.nodeIdCompat&&R.test(a[e])&&(a[e]=a[e].replace(R,""));n=a=n.concat(a);d=n.length;for(e=0;e<d;e++)if(c=n[e],"."===c)n.splice(e,1),e-=1;else if(".."===c)if(1===e&&(".."===n[2]||".."===n[0]))break;else 0<e&&(n.splice(e-1,2),e-=2);a=a.join("/")}else 0===a.indexOf("./")&&(a=a.substring(2));if(b&&m&&(I||k)){n=a.split("/");e=n.length;a:for(;0<e;e-=1){d=n.slice(0,e).join("/");if(I)for(c=I.length;0<c;c-=1)if(b=j(m,I.slice(0,c).join("/")))if(b=j(b,d)){f=b;
g=e;break a}!h&&(k&&j(k,d))&&(h=j(k,d),i=e)}!f&&h&&(f=h,g=i);f&&(n.splice(0,g,f),a=n.join("/"))}return(f=j(l.pkgs,a))?f:a}function d(a){z&&v(document.getElementsByTagName("script"),function(e){if(e.getAttribute("data-requiremodule")===a&&e.getAttribute("data-requirecontext")===i.contextName)return e.parentNode.removeChild(e),!0})}function g(a){var e=j(l.paths,a);if(e&&H(e)&&1<e.length)return e.shift(),i.require.undef(a),i.require([a]),!0}function u(a){var e,b=a?a.indexOf("!"):-1;-1<b&&(e=a.substring(0,
b),a=a.substring(b+1,a.length));return[e,a]}function m(a,e,b,f){var n,d,g=null,h=e?e.name:null,l=a,m=!0,k="";a||(m=!1,a="_@r"+(M+=1));a=u(a);g=a[0];a=a[1];g&&(g=c(g,h,f),d=j(p,g));a&&(g?k=d&&d.normalize?d.normalize(a,function(a){return c(a,h,f)}):c(a,h,f):(k=c(a,h,f),a=u(k),g=a[0],k=a[1],b=!0,n=i.nameToUrl(k)));b=g&&!d&&!b?"_unnormalized"+(Q+=1):"";return{prefix:g,name:k,parentMap:e,unnormalized:!!b,url:n,originalName:l,isDefine:m,id:(g?g+"!"+k:k)+b}}function q(a){var e=a.id,b=j(k,e);b||(b=k[e]=new i.Module(a));
return b}function r(a,e,b){var f=a.id,n=j(k,f);if(s(p,f)&&(!n||n.defineEmitComplete))"defined"===e&&b(p[f]);else if(n=q(a),n.error&&"error"===e)b(n.error);else n.on(e,b)}function w(a,e){var b=a.requireModules,f=!1;if(e)e(a);else if(v(b,function(e){if(e=j(k,e))e.error=a,e.events.error&&(f=!0,e.emit("error",a))}),!f)h.onError(a)}function x(){S.length&&(ia.apply(A,[A.length,0].concat(S)),S=[])}function y(a){delete k[a];delete W[a]}function F(a,e,b){var f=a.map.id;a.error?a.emit("error",a.error):(e[f]=
!0,v(a.depMaps,function(f,c){var d=f.id,g=j(k,d);g&&(!a.depMatched[c]&&!b[d])&&(j(e,d)?(a.defineDep(c,p[d]),a.check()):F(g,e,b))}),b[f]=!0)}function D(){var a,e,b=(a=1E3*l.waitSeconds)&&i.startTime+a<(new Date).getTime(),f=[],c=[],h=!1,k=!0;if(!X){X=!0;B(W,function(a){var i=a.map,m=i.id;if(a.enabled&&(i.isDefine||c.push(a),!a.error))if(!a.inited&&b)g(m)?h=e=!0:(f.push(m),d(m));else if(!a.inited&&(a.fetched&&i.isDefine)&&(h=!0,!i.prefix))return k=!1});if(b&&f.length)return a=C("timeout","Load timeout for modules: "+
f,null,f),a.contextName=i.contextName,w(a);k&&v(c,function(a){F(a,{},{})});if((!b||e)&&h)if((z||fa)&&!Y)Y=setTimeout(function(){Y=0;D()},50);X=!1}}function E(a){s(p,a[0])||q(m(a[0],null,!0)).init(a[1],a[2])}function K(a){var a=a.currentTarget||a.srcElement,e=i.onScriptLoad;a.detachEvent&&!Z?a.detachEvent("onreadystatechange",e):a.removeEventListener("load",e,!1);e=i.onScriptError;(!a.detachEvent||Z)&&a.removeEventListener("error",e,!1);return{node:a,id:a&&a.getAttribute("data-requiremodule")}}function L(){var a;
for(x();A.length;){a=A.shift();if(null===a[0])return w(C("mismatch","Mismatched anonymous define() module: "+a[a.length-1]));E(a)}}var X,$,i,N,Y,l={waitSeconds:7,baseUrl:"./",paths:{},bundles:{},pkgs:{},shim:{},config:{}},k={},W={},aa={},A=[],p={},T={},ba={},M=1,Q=1;N={require:function(a){return a.require?a.require:a.require=i.makeRequire(a.map)},exports:function(a){a.usingExports=!0;if(a.map.isDefine)return a.exports?p[a.map.id]=a.exports:a.exports=p[a.map.id]={}},module:function(a){return a.module?
a.module:a.module={id:a.map.id,uri:a.map.url,config:function(){return j(l.config,a.map.id)||{}},exports:a.exports||(a.exports={})}}};$=function(a){this.events=j(aa,a.id)||{};this.map=a;this.shim=j(l.shim,a.id);this.depExports=[];this.depMaps=[];this.depMatched=[];this.pluginMaps={};this.depCount=0};$.prototype={init:function(a,e,b,f){f=f||{};if(!this.inited){this.factory=e;if(b)this.on("error",b);else this.events.error&&(b=t(this,function(a){this.emit("error",a)}));this.depMaps=a&&a.slice(0);this.errback=
b;this.inited=!0;this.ignore=f.ignore;f.enabled||this.enabled?this.enable():this.check()}},defineDep:function(a,e){this.depMatched[a]||(this.depMatched[a]=!0,this.depCount-=1,this.depExports[a]=e)},fetch:function(){if(!this.fetched){this.fetched=!0;i.startTime=(new Date).getTime();var a=this.map;if(this.shim)i.makeRequire(this.map,{enableBuildCallback:!0})(this.shim.deps||[],t(this,function(){return a.prefix?this.callPlugin():this.load()}));else return a.prefix?this.callPlugin():this.load()}},load:function(){var a=
this.map.url;T[a]||(T[a]=!0,i.load(this.map.id,a))},check:function(){if(this.enabled&&!this.enabling){var a,e,b=this.map.id;e=this.depExports;var f=this.exports,c=this.factory;if(this.inited)if(this.error)this.emit("error",this.error);else{if(!this.defining){this.defining=!0;if(1>this.depCount&&!this.defined){if(G(c)){if(this.events.error&&this.map.isDefine||h.onError!==da)try{f=i.execCb(b,c,e,f)}catch(d){a=d}else f=i.execCb(b,c,e,f);this.map.isDefine&&void 0===f&&((e=this.module)?f=e.exports:this.usingExports&&
(f=this.exports));if(a)return a.requireMap=this.map,a.requireModules=this.map.isDefine?[this.map.id]:null,a.requireType=this.map.isDefine?"define":"require",w(this.error=a)}else f=c;this.exports=f;if(this.map.isDefine&&!this.ignore&&(p[b]=f,h.onResourceLoad))h.onResourceLoad(i,this.map,this.depMaps);y(b);this.defined=!0}this.defining=!1;this.defined&&!this.defineEmitted&&(this.defineEmitted=!0,this.emit("defined",this.exports),this.defineEmitComplete=!0)}}else this.fetch()}},callPlugin:function(){var a=
this.map,b=a.id,d=m(a.prefix);this.depMaps.push(d);r(d,"defined",t(this,function(f){var d,g;g=j(ba,this.map.id);var J=this.map.name,u=this.map.parentMap?this.map.parentMap.name:null,p=i.makeRequire(a.parentMap,{enableBuildCallback:!0});if(this.map.unnormalized){if(f.normalize&&(J=f.normalize(J,function(a){return c(a,u,!0)})||""),f=m(a.prefix+"!"+J,this.map.parentMap),r(f,"defined",t(this,function(a){this.init([],function(){return a},null,{enabled:!0,ignore:!0})})),g=j(k,f.id)){this.depMaps.push(f);
if(this.events.error)g.on("error",t(this,function(a){this.emit("error",a)}));g.enable()}}else g?(this.map.url=i.nameToUrl(g),this.load()):(d=t(this,function(a){this.init([],function(){return a},null,{enabled:!0})}),d.error=t(this,function(a){this.inited=!0;this.error=a;a.requireModules=[b];B(k,function(a){0===a.map.id.indexOf(b+"_unnormalized")&&y(a.map.id)});w(a)}),d.fromText=t(this,function(f,c){var g=a.name,J=m(g),k=O;c&&(f=c);k&&(O=!1);q(J);s(l.config,b)&&(l.config[g]=l.config[b]);try{h.exec(f)}catch(j){return w(C("fromtexteval",
"fromText eval for "+b+" failed: "+j,j,[b]))}k&&(O=!0);this.depMaps.push(J);i.completeLoad(g);p([g],d)}),f.load(a.name,p,d,l))}));i.enable(d,this);this.pluginMaps[d.id]=d},enable:function(){W[this.map.id]=this;this.enabling=this.enabled=!0;v(this.depMaps,t(this,function(a,b){var c,f;if("string"===typeof a){a=m(a,this.map.isDefine?this.map:this.map.parentMap,!1,!this.skipMap);this.depMaps[b]=a;if(c=j(N,a.id)){this.depExports[b]=c(this);return}this.depCount+=1;r(a,"defined",t(this,function(a){this.defineDep(b,
a);this.check()}));this.errback&&r(a,"error",t(this,this.errback))}c=a.id;f=k[c];!s(N,c)&&(f&&!f.enabled)&&i.enable(a,this)}));B(this.pluginMaps,t(this,function(a){var b=j(k,a.id);b&&!b.enabled&&i.enable(a,this)}));this.enabling=!1;this.check()},on:function(a,b){var c=this.events[a];c||(c=this.events[a]=[]);c.push(b)},emit:function(a,b){v(this.events[a],function(a){a(b)});"error"===a&&delete this.events[a]}};i={config:l,contextName:b,registry:k,defined:p,urlFetched:T,defQueue:A,Module:$,makeModuleMap:m,
nextTick:h.nextTick,onError:w,configure:function(a){a.baseUrl&&"/"!==a.baseUrl.charAt(a.baseUrl.length-1)&&(a.baseUrl+="/");var b=l.shim,c={paths:!0,bundles:!0,config:!0,map:!0};B(a,function(a,b){c[b]?(l[b]||(l[b]={}),V(l[b],a,!0,!0)):l[b]=a});a.bundles&&B(a.bundles,function(a,b){v(a,function(a){a!==b&&(ba[a]=b)})});a.shim&&(B(a.shim,function(a,c){H(a)&&(a={deps:a});if((a.exports||a.init)&&!a.exportsFn)a.exportsFn=i.makeShimExports(a);b[c]=a}),l.shim=b);a.packages&&v(a.packages,function(a){var b,
a="string"===typeof a?{name:a}:a;b=a.name;a.location&&(l.paths[b]=a.location);l.pkgs[b]=a.name+"/"+(a.main||"main").replace(ja,"").replace(R,"")});B(k,function(a,b){!a.inited&&!a.map.unnormalized&&(a.map=m(b))});if(a.deps||a.callback)i.require(a.deps||[],a.callback)},makeShimExports:function(a){return function(){var b;a.init&&(b=a.init.apply(ca,arguments));return b||a.exports&&ea(a.exports)}},makeRequire:function(a,e){function g(f,c,d){var j,l;e.enableBuildCallback&&(c&&G(c))&&(c.__requireJsBuild=
!0);if("string"===typeof f){if(G(c))return w(C("requireargs","Invalid require call"),d);if(a&&s(N,f))return N[f](k[a.id]);if(h.get)return h.get(i,f,a,g);j=m(f,a,!1,!0);j=j.id;return!s(p,j)?w(C("notloaded",'Module name "'+j+'" has not been loaded yet for context: '+b+(a?"":". Use require([])"))):p[j]}L();i.nextTick(function(){L();l=q(m(null,a));l.skipMap=e.skipMap;l.init(f,c,d,{enabled:!0});D()});return g}e=e||{};V(g,{isBrowser:z,toUrl:function(b){var e,d=b.lastIndexOf("."),g=b.split("/")[0];if(-1!==
d&&(!("."===g||".."===g)||1<d))e=b.substring(d,b.length),b=b.substring(0,d);return i.nameToUrl(c(b,a&&a.id,!0),e,!0)},defined:function(b){return s(p,m(b,a,!1,!0).id)},specified:function(b){b=m(b,a,!1,!0).id;return s(p,b)||s(k,b)}});a||(g.undef=function(b){x();var c=m(b,a,!0),e=j(k,b);d(b);delete p[b];delete T[c.url];delete aa[b];U(A,function(a,c){a[0]===b&&A.splice(c,1)});e&&(e.events.defined&&(aa[b]=e.events),y(b))});return g},enable:function(a){j(k,a.id)&&q(a).enable()},completeLoad:function(a){var b,
c,f=j(l.shim,a)||{},d=f.exports;for(x();A.length;){c=A.shift();if(null===c[0]){c[0]=a;if(b)break;b=!0}else c[0]===a&&(b=!0);E(c)}c=j(k,a);if(!b&&!s(p,a)&&c&&!c.inited){if(l.enforceDefine&&(!d||!ea(d)))return g(a)?void 0:w(C("nodefine","No define call for "+a,null,[a]));E([a,f.deps||[],f.exportsFn])}D()},nameToUrl:function(a,b,c){var f,d,g;(f=j(l.pkgs,a))&&(a=f);if(f=j(ba,a))return i.nameToUrl(f,b,c);if(h.jsExtRegExp.test(a))f=a+(b||"");else{f=l.paths;a=a.split("/");for(d=a.length;0<d;d-=1)if(g=a.slice(0,
d).join("/"),g=j(f,g)){H(g)&&(g=g[0]);a.splice(0,d,g);break}f=a.join("/");f+=b||(/^data\:|\?/.test(f)||c?"":".js");f=("/"===f.charAt(0)||f.match(/^[\w\+\.\-]+:/)?"":l.baseUrl)+f}return l.urlArgs?f+((-1===f.indexOf("?")?"?":"&")+l.urlArgs):f},load:function(a,b){h.load(i,a,b)},execCb:function(a,b,c,d){return b.apply(d,c)},onScriptLoad:function(a){if("load"===a.type||ka.test((a.currentTarget||a.srcElement).readyState))P=null,a=K(a),i.completeLoad(a.id)},onScriptError:function(a){var b=K(a);if(!g(b.id))return w(C("scripterror",
"Script error for: "+b.id,a,[b.id]))}};i.require=i.makeRequire();return i}var h,x,y,D,K,E,P,L,q,Q,la=/(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg,ma=/[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,R=/\.js$/,ja=/^\.\//;x=Object.prototype;var M=x.toString,ga=x.hasOwnProperty,ia=Array.prototype.splice,z=!!("undefined"!==typeof window&&"undefined"!==typeof navigator&&window.document),fa=!z&&"undefined"!==typeof importScripts,ka=z&&"PLAYSTATION 3"===navigator.platform?/^complete$/:/^(complete|loaded)$/,
Z="undefined"!==typeof opera&&"[object Opera]"===opera.toString(),F={},r={},S=[],O=!1;if("undefined"===typeof define){if("undefined"!==typeof requirejs){if(G(requirejs))return;r=requirejs;requirejs=void 0}"undefined"!==typeof require&&!G(require)&&(r=require,require=void 0);h=requirejs=function(b,c,d,g){var u,m="_";!H(b)&&"string"!==typeof b&&(u=b,H(c)?(b=c,c=d,d=g):b=[]);u&&u.context&&(m=u.context);(g=j(F,m))||(g=F[m]=h.s.newContext(m));u&&g.configure(u);return g.require(b,c,d)};h.config=function(b){return h(b)};
h.nextTick="undefined"!==typeof setTimeout?function(b){setTimeout(b,4)}:function(b){b()};require||(require=h);h.version="2.1.11";h.jsExtRegExp=/^\/|:|\?|\.js$/;h.isBrowser=z;x=h.s={contexts:F,newContext:ha};h({});v(["toUrl","undef","defined","specified"],function(b){h[b]=function(){var c=F._;return c.require[b].apply(c,arguments)}});if(z&&(y=x.head=document.getElementsByTagName("head")[0],D=document.getElementsByTagName("base")[0]))y=x.head=D.parentNode;h.onError=da;h.createNode=function(b){var c=
b.xhtml?document.createElementNS("http://www.w3.org/1999/xhtml","html:script"):document.createElement("script");c.type=b.scriptType||"text/javascript";c.charset="utf-8";c.async=!0;return c};h.load=function(b,c,d){var g=b&&b.config||{};if(z)return g=h.createNode(g,c,d),g.setAttribute("data-requirecontext",b.contextName),g.setAttribute("data-requiremodule",c),g.attachEvent&&!(g.attachEvent.toString&&0>g.attachEvent.toString().indexOf("[native code"))&&!Z?(O=!0,g.attachEvent("onreadystatechange",b.onScriptLoad)):
(g.addEventListener("load",b.onScriptLoad,!1),g.addEventListener("error",b.onScriptError,!1)),g.src=d,L=g,D?y.insertBefore(g,D):y.appendChild(g),L=null,g;if(fa)try{importScripts(d),b.completeLoad(c)}catch(j){b.onError(C("importscripts","importScripts failed for "+c+" at "+d,j,[c]))}};z&&!r.skipDataMain&&U(document.getElementsByTagName("script"),function(b){y||(y=b.parentNode);if(K=b.getAttribute("data-main"))return q=K,r.baseUrl||(E=q.split("/"),q=E.pop(),Q=E.length?E.join("/")+"/":"./",r.baseUrl=
Q),q=q.replace(R,""),h.jsExtRegExp.test(q)&&(q=K),r.deps=r.deps?r.deps.concat(q):[q],!0});define=function(b,c,d){var g,h;"string"!==typeof b&&(d=c,c=b,b=null);H(c)||(d=c,c=null);!c&&G(d)&&(c=[],d.length&&(d.toString().replace(la,"").replace(ma,function(b,d){c.push(d)}),c=(1===d.length?["require"]:["require","exports","module"]).concat(c)));if(O){if(!(g=L))P&&"interactive"===P.readyState||U(document.getElementsByTagName("script"),function(b){if("interactive"===b.readyState)return P=b}),g=P;g&&(b||
(b=g.getAttribute("data-requiremodule")),h=F[g.getAttribute("data-requirecontext")])}(h?h.defQueue:S).push([b,c,d])};define.amd={jQuery:!0};h.exec=function(b){return eval(b)};h(r)}})(this);
<commit_msg>moved stuff around<commit_after><|endoftext|>


<commit_before>$(function() {
  var blankByDefault = ($("#artefact_slug").attr('value') != '');
  var generateSlug = function generateSlug() {
    if(blankByDefault) { return }
    var title = $("#artefact_name").val();
    var slug = title.toLowerCase()
      .replace(/[^\w ]+/g, '')
      .replace(/ +/g, '-')
      .replace(/^-+|-+$/, '')
    $("#artefact_slug").val(slug);
  }
  $("#artefact_name").change(generateSlug)
  $("#artefact_name").bind('keyup', generateSlug)

  $('a[rel=external]').attr('target','_blank');

  // $('.related select').chosen({
  //   allow_single_deselect: true,
  //   no_results_text: "No results matched"
  // });

  $('select#artefact_sections').chosen({
    allow_single_deselect: true,
    no_results_text: "Section not found"
  });

  $('.flash-notice').delay(4000).slideUp(300).
    one('click', function () { $(this).slideUp(300); });

  // add sections
  $('#add-section').click(function () {
    $('.remove-section').show();
    var new_select = $('.artefact-section').first().clone(true);
    new_select.find('select option:selected').removeAttr('selected');
    new_select.insertBefore(this);
    return false;
  })

  $('.remove-section').click(function () {
    if ($('.artefact-section').size() >= 2) {
      $(this).parent().remove();
      if ($('.artefact-section').size() == 1) {
        $('.remove-section').hide();
      }
    }
    return false;
  })

});
<commit_msg>Remove dead chosen dropdown code<commit_after>$(function() {
  var blankByDefault = ($("#artefact_slug").attr('value') != '');
  var generateSlug = function generateSlug() {
    if(blankByDefault) { return }
    var title = $("#artefact_name").val();
    var slug = title.toLowerCase()
      .replace(/[^\w ]+/g, '')
      .replace(/ +/g, '-')
      .replace(/^-+|-+$/, '')
    $("#artefact_slug").val(slug);
  }
  $("#artefact_name").change(generateSlug)
  $("#artefact_name").bind('keyup', generateSlug)

  $('a[rel=external]').attr('target','_blank');

  $('.flash-notice').delay(4000).slideUp(300).
    one('click', function () { $(this).slideUp(300); });

  // add sections
  $('#add-section').click(function () {
    $('.remove-section').show();
    var new_select = $('.artefact-section').first().clone(true);
    new_select.find('select option:selected').removeAttr('selected');
    new_select.insertBefore(this);
    return false;
  })

  $('.remove-section').click(function () {
    if ($('.artefact-section').size() >= 2) {
      $(this).parent().remove();
      if ($('.artefact-section').size() == 1) {
        $('.remove-section').hide();
      }
    }
    return false;
  })

});
<|endoftext|>


<commit_before>!function () {
  CIAB.Corkboard = function (tag) {
    this.cards = [];
    this.tag = tag;

    this.init();
  };

  CIAB.Corkboard.prototype = {
    init: function () {
      this.$cork_space = $('#cork-board');

      this.$cork_board = $(document.createElement('div'));
      this.$cork_board.addClass('cork-board');

      this.$cork_space.append(this.$cork_board);

      this.getEvents();
    },

    card: function (id, text) {
      var $card = $(document.createElement('div'));
      $card.addClass('index-card');

      this.$cork_board.append($card);

      if (this.currentID() == id) {
        $card.addClass('selected-card');
      }
      $card.html(text);
      $card.data('event-id', id);
      $card.on('click tap', this.gotoEvent).bind(this);
    },

    currentID: function () {
      var re = /events\/(\d*)/;
      var id = re.exec(window.location);
      if (id && id.length == 2 && id[1]) {
        return id[1];
      } else {
        return null;
      }
    },

    fillCards: function (data, status, xhr) {
      this.$cork_board.html('');

      this.$cork_label = $(document.createElement('div'));
      this.$cork_label.addClass('cork-board-label');
      this.$cork_label.html(this.tag);

      this.$cork_board.append(this.$cork_label);

      if (data.length == 0) {
        this.$cork_board.hide();
      } else {
        for (var i = 0; i < data.length; i++) {
          this.cards.push(this.card(data[i].id, data[i].entry));
        }
        this.$cork_board.show()
      }
    },

    getEvents: function () {
      if( window.banner.pause ) return;
      this.cards = []

      $.ajax({
        url: '/events/tag/' + this.tag,
        dataType: 'json',
        success: this.fillCards.bind(this)
      });

      setTimeout(function () {
        this.getEvents()
      }.bind(this), 50000000);
    },

    gotoEvent: function (evt) {
      var $target = $(evt.target).closest('.index-card');
      location.assign('/events/' + $target.data('event-id'));
    }
  }
}();

<commit_msg>Update corkboard.js<commit_after>!function () {
  CIAB.Corkboard = function (tag) {
    this.cards = [];
    this.tag = tag;

    this.init();
  };

  CIAB.Corkboard.prototype = {
    init: function () {
      this.$cork_space = $('#cork-board');

      this.$cork_board = $(document.createElement('div'));
      this.$cork_board.addClass('cork-board');

      this.$cork_space.append(this.$cork_board);

      this.getEvents();
    },

    card: function (id, text) {
      var $card = $(document.createElement('div'));
      $card.addClass('index-card');

      this.$cork_board.append($card);

      if (this.currentID() == id) {
        $card.addClass('selected-card');
      }
      $card.html(text);
      $card.data('event-id', id);
      $card.on('click tap', this.gotoEvent).bind(this);
    },

    currentID: function () {
      var re = /events\/(\d*)/;
      var id = re.exec(window.location);
      if (id && id.length == 2 && id[1]) {
        return id[1];
      } else {
        return null;
      }
    },

    fillCards: function (data, status, xhr) {
      this.$cork_board.html('');

      this.$cork_label = $(document.createElement('div'));
      this.$cork_label.addClass('cork-board-label');
      this.$cork_label.html(this.tag);

      this.$cork_board.append(this.$cork_label);

      if (data.length == 0) {
        this.$cork_board.hide();
      } else {
        for (var i = 0; i < data.length; i++) {
          this.cards.push(this.card(data[i].id, data[i].entry));
        }
        this.$cork_board.show()
      }
    },

    getEvents: function () {
      if( window.banner.pause ) return;
      this.cards = []

      $.ajax({
        url: '/events/tag/' + this.tag,
        dataType: 'json',
        success: this.fillCards.bind(this)
      });

      setTimeout(function () {
        this.getEvents()
      }.bind(this), 5000);
    },

    gotoEvent: function (evt) {
      var $target = $(evt.target).closest('.index-card');
      location.assign('/events/' + $target.data('event-id'));
    }
  }
}();

<|endoftext|>


<commit_before>$(document).ready( function () {
  $('#signup').click(function(event){
    event.preventDefault();
    $('#screen_block').show();
    $('#signup_modal').show();
  });

  $('#screen_block').click(function(event){
    event.preventDefault();

    $('#screen_block').hide();
    $('#login_modal').hide();
    $('#signup_modal').hide();
    $('#new_question_modal').hide();
  });

  $('#login').click(function(event){
    event.preventDefault();
    $('#screen_block').show();
    $('#login_modal').show();
  });

  $('.new_question_button').click(function(event){
    event.preventDefault();
    $('#screen_block').show();
    $('#new_question_modal').show();
  });
  $('form#new_question').submit(function(event){
    event.preventDefault();
    $.ajax({
      url: '/questions',
      type: 'POST',
      data: $('form#new_question').serialize(),
      dataType: 'JSON',
    }).done(function(data){
      $('ol.thumb-grid').load('/ .thumb-grid')
      clear_modals();
    }).fail(function(data){
      console.log(data);
    });
  });
});

function clear_modals(){
  $('#screen_block').hide();
    $('#login_modal').hide();
    $('#signup_modal').hide();
    $('#new_question_modal').hide();
}<commit_msg>Refactor JS To have Reusuable Functions<commit_after>$(document).ready( function () {
  $('#signup').click(function(event){
    event.preventDefault();
    $('#screen_block').show();
    $('#signup_modal').show();
  });

  $('#screen_block').click(function(event){
    event.preventDefault();
    clear_modals();
  });

  $('#login').click(function(event){
    event.preventDefault();
    $('#screen_block').show();
    $('#login_modal').show();
  });

  $('.new_question_button').click(function(event){
    event.preventDefault();
    $('#screen_block').show();
    $('#new_question_modal').show();
  });
  $('form#new_question').submit(function(event){
    event.preventDefault();
    $.ajax({
      url: '/questions',
      type: 'POST',
      data: $('form#new_question').serialize(),
      dataType: 'JSON',
    }).done(function(data){
      $('ol.thumb-grid').load('/ .thumb-grid')
      clear_modals();
    }).fail(function(data){
      console.log(data);
    });
  });
});

function clear_modals(){
  $('#screen_block').hide();
    $('#login_modal').hide();
    $('#signup_modal').hide();
    $('#new_question_modal').hide();
}<|endoftext|>


<commit_before>var kunstmaanbundles = kunstmaanbundles || {};

kunstmaanbundles.pagepartEditor = (function(window) {

    var init,
        addPagePart, editPagePart, deletePagePart;

    init = function() {
        var $body = $('body');

        // Add
        $body.on('change', '.js-add-pp-select', function() {
            addPagePart($(this));
        });

        // Edit
        $body.on('click', '.js-edit-pp-btn', function() {
            editPagePart($(this));
        });

        // Del
        $body.on('click', '.js-delete-pp-btn', function() {
            deletePagePart($(this));
        });
    };

    // Add
    addPagePart = function($select) {
        var $targetContainer = $select.closest('.js-pp-container'),
            requestUrl = $select.data('url');

        // Get necessary data
        var pageClassName = $targetContainer.data('pageclassname'),
            pageId = $targetContainer.data('pageid'),
            context = $targetContainer.data('context'),
            ppType = $select.val();

        // Set Loading
        kunstmaanbundles.appLoading.addLoading();

        // Ajax Request
        $.ajax({
            url: requestUrl,
            data: {
                'pageclassname': pageClassName,
                'pageid': pageId,
                'context': context,
                'type': ppType
            },
            async: true,
            success: function (data) {
                // Add PP
                var firstSelect = $select.hasClass('js-add-pp-select--first');
                if (firstSelect) {
                    $('#parts-' + context).prepend(data);
                } else {
                    $select.closest('.js-sortable-item').after(data);
                }

                // Remove Loading
                kunstmaanbundles.appLoading.removeLoading();

                // Enable leave-page modal
                kunstmaanbundles.checkIfEdited.edited();

                // Enable new Rich Editors
                kunstmaanbundles.richEditor.init();

                // Init new tooltips
                kunstmaanbundles.tooltip.init();

                // Init new colorpickers
                kunstmaanbundles.colorpicker.init();

                // Reinit custom selects
                kunstmaanbundles.advancedSelect.init();

                // Reinit nested forms
                kunstmaanbundles.nestedForm.init();

                // Rest ajax-modals
                kunstmaanbundles.ajaxModal.resetAjaxModals();

                // Reinitialise the datepickers
                kunstmaanbundles.datepicker.reInitialise();
            }
        });

        // Reset select
        $select.val('');
    };

    // Edit
    editPagePart = function($btn) {
        var targetId = $btn.data('target-id');

        // Enable "leave page" modal
        kunstmaanbundles.checkIfEdited.edited();

        // Show edit view and hide preview
        $('#' + targetId + '-edit-view').removeClass('pp__view__block--hidden');
        $('#' + targetId + '-preview-view').addClass('pp__view__block--hidden');

        // Add edit active class
        $('#pp-' + targetId).addClass('pp--edit-active');

        // Reinit custom selects
        kunstmaanbundles.advancedSelect.init();

        // Set Active Edit
        window.activeEdit = targetId;
    };

    // Delete
    deletePagePart = function($btn) {
        var targetId = $btn.data('target-id'),
            $container = $('#' + targetId + '-pp-container');

        // Enable "leave page" modal
        kunstmaanbundles.checkIfEdited.edited();

        // Slideup and empty container
        $container.velocity('slideUp', {
            duration: 300
        });

        $container.empty();

        // Check is-deleted checkbox
        $('#' + targetId + '-is-deleted').prop('checked', true);

        // Hide delete modal
        $('#delete-pagepart-modal-' + targetId).modal('hide');
        $('body').removeClass('modal-open');
    };

    return {
        init: init
    };

}(window));
<commit_msg>[NodeBundle] Prevent add pagepart from blocking page<commit_after>var kunstmaanbundles = kunstmaanbundles || {};

kunstmaanbundles.pagepartEditor = (function(window) {

    var init,
        addPagePart, editPagePart, deletePagePart;

    init = function() {
        var $body = $('body');

        // Add
        $body.on('change', '.js-add-pp-select', function() {
            addPagePart($(this));
        });

        // Edit
        $body.on('click', '.js-edit-pp-btn', function() {
            editPagePart($(this));
        });

        // Del
        $body.on('click', '.js-delete-pp-btn', function() {
            deletePagePart($(this));
        });
    };

    // Add
    addPagePart = function($select) {
        if (!$select.val()) {
            return false;
        }

        var $targetContainer = $select.closest('.js-pp-container'),
            requestUrl = $select.data('url');

        // Get necessary data
        var pageClassName = $targetContainer.data('pageclassname'),
            pageId = $targetContainer.data('pageid'),
            context = $targetContainer.data('context'),
            ppType = $select.val();

        // Set Loading
        kunstmaanbundles.appLoading.addLoading();

        // Ajax Request
        $.ajax({
            url: requestUrl,
            data: {
                'pageclassname': pageClassName,
                'pageid': pageId,
                'context': context,
                'type': ppType
            },
            async: true,
            success: function (data) {
                // Add PP
                var firstSelect = $select.hasClass('js-add-pp-select--first');
                if (firstSelect) {
                    $('#parts-' + context).prepend(data);
                } else {
                    $select.closest('.js-sortable-item').after(data);
                }

                // Remove Loading
                kunstmaanbundles.appLoading.removeLoading();

                // Enable leave-page modal
                kunstmaanbundles.checkIfEdited.edited();

                // Enable new Rich Editors
                kunstmaanbundles.richEditor.init();

                // Init new tooltips
                kunstmaanbundles.tooltip.init();

                // Init new colorpickers
                kunstmaanbundles.colorpicker.init();

                // Reinit custom selects
                kunstmaanbundles.advancedSelect.init();

                // Reinit nested forms
                kunstmaanbundles.nestedForm.init();

                // Rest ajax-modals
                kunstmaanbundles.ajaxModal.resetAjaxModals();

                // Reinitialise the datepickers
                kunstmaanbundles.datepicker.reInitialise();
            }
        });

        // Reset select
        $select.val('');
    };

    // Edit
    editPagePart = function($btn) {
        var targetId = $btn.data('target-id');

        // Enable "leave page" modal
        kunstmaanbundles.checkIfEdited.edited();

        // Show edit view and hide preview
        $('#' + targetId + '-edit-view').removeClass('pp__view__block--hidden');
        $('#' + targetId + '-preview-view').addClass('pp__view__block--hidden');

        // Add edit active class
        $('#pp-' + targetId).addClass('pp--edit-active');

        // Reinit custom selects
        kunstmaanbundles.advancedSelect.init();

        // Set Active Edit
        window.activeEdit = targetId;
    };

    // Delete
    deletePagePart = function($btn) {
        var targetId = $btn.data('target-id'),
            $container = $('#' + targetId + '-pp-container');

        // Enable "leave page" modal
        kunstmaanbundles.checkIfEdited.edited();

        // Slideup and empty container
        $container.velocity('slideUp', {
            duration: 300
        });

        $container.empty();

        // Check is-deleted checkbox
        $('#' + targetId + '-is-deleted').prop('checked', true);

        // Hide delete modal
        $('#delete-pagepart-modal-' + targetId).modal('hide');
        $('body').removeClass('modal-open');
    };

    return {
        init: init
    };

}(window));
<|endoftext|>


<commit_before>import Command from './command.js';
import {operator} from './utils.js';
import {functionVariables} from './cmdVariables.js';

export class If extends Command {
  constructor(condition) {
    super('IF', true)
    this.condition = condition;
  }

  executeCommand() {
    if (this.condition.executeCommand()) {
      this.executeCallbacks()
    }
  }
}

export class Condition {
  constructor(left, right, comparison) {
    this.left = left
    this.right = right
    this.comparison = comparison
  }

  executeCommand() {
    return operator(functionVariables[this.left], this.right, this.comparison);
  }
}
<commit_msg>working on red tile if coditios<commit_after>import Command from './command.js';
import {functionVariables} from './cmdVariables.js';
import store from '../store.jsx';

export class If extends Command {
  constructor(condition) {
    super('IF', true)
    this.condition = condition;
  }

  executeCommand() {
    if (this.condition.executeCommand()) {
      this.executeCallbacks()
    }
  }
}

export class IfNot extends Command {
  constructor(condition) {
    super('IFNOT', true)
    this.condition = condition;
  }

  executeCommand() {
    if (this.condition.executeCommand() === false) {
      this.executeCallbacks()
    }
  }
}

const redTileCheck = () => {
    const redTile = [store.getState().transition.redTile.xGrid, store.getState().redTile.yGrid];
    const spriteCoord = [store.getState().transition.xGrid, store.getState().transition.yGrid]
    if (redTile[0] === spriteCoord[0] && redTile[1] === spriteCoord[1]) return true;
}

export class Condition {
  constructor(left = null, right = null, comparison = null) {
    this.left = left
    this.right = right
    this.comparison = comparison
  }

  executeCommand() {
    return redTileCheck();
  }
}
<|endoftext|>


<commit_before><commit_msg>Use full MIME parsing for #10<commit_after><|endoftext|>


<commit_before>import Ember from "ember"
import hbs from "htmlbars-inline-precompile"
import _ from "npm:lodash"

export default Ember.Component.extend({
  layout: hbs`
  {{#unless item.isCollapsed}}
  {{#sortable-item tagName="div" model=item group=group handle=".sortable-standard__handle" id=(join-words 'sortable-item-' item.id) }}

          {{partial "icons/arrow-move"}}

          {{partial "icons/arrow-left"}}

          {{partial "icons/arrow-right"}}

          {{partial "icons/ios7-trash-filled"}}

        {{simple-editable
          maxLength=10
          value=item.listId
          class="sortable-standard__list-id hint--bottom"
          placeholder="List Identifier"
          onEnterKey=attrs.onEnterKey
          onMetaDelete=attrs.removeStandard
          onArrowUp=(action attrs.onArrow "up" item.id "sortable-standard__list-id")
          onArrowDown=(action attrs.onArrow "down" item.id "sortable-standard__list-id")
          onArrowLeft=(action attrs.outdent item)
          onArrowRight=(action attrs.indent item)
        }}

        {{simple-editable
          value=item.description
          class="sortable-standard__description"
          onEnterKey=attrs.onEnterKey
          onMetaDelete=attrs.removeStandard
          onArrowLeft=(action attrs.outdent item)
          onArrowRight=(action attrs.indent item)
        }}

        {{simple-editable
          value=item.statementNotation
          class="sortable-standard__statement-notation"
          onEnterKey=attrs.onEnterKey
          onMetaDelete=attrs.removeStandard
          onArrowUp=(action attrs.onArrow "up" item.id "sortable-standard__statement-notation")
          onArrowDown=(action attrs.onArrow "down" item.id "sortable-standard__statement-notation")
          onArrowLeft=(action attrs.outdent item)
          onArrowRight=(action attrs.indent item)
        }}

  {{!-- {{#unless item.isCollapsed}}
    {{#sortable-group onChange=attrs.reorder as |nestedGroup|}}
      {{#each item.ancestorIds as |id index|}}
        {{sortable-standard item=(look-up standards id) index=index group=nestedGroup standards=standards}}
      {{/each}}
    {{/sortable-group}}
  {{/unless}} --}}
  {{/sortable-item}}
  {{/unless}}

  `,
})
<commit_msg>[front] Add aria labels to unlabeled icons.<commit_after>import Ember from "ember"
import hbs from "htmlbars-inline-precompile"
import _ from "npm:lodash"

export default Ember.Component.extend({
  layout: hbs`
  {{#unless item.isCollapsed}}
  {{#sortable-item tagName="div" model=item group=group handle=".sortable-standard__handle" id=(join-words 'sortable-item-' item.id) }}

          {{partial "icons/arrow-move"}}

          {{partial "icons/arrow-left"}}

          {{partial "icons/arrow-right"}}

          {{partial "icons/ios7-trash-filled"}}

        {{simple-editable
          maxLength=10
          value=item.listId
          class="sortable-standard__list-id hint--bottom"
          placeholder="List Identifier"
          onEnterKey=attrs.onEnterKey
          onMetaDelete=attrs.removeStandard
          onArrowUp=(action attrs.onArrow "up" item.id "sortable-standard__list-id")
          onArrowDown=(action attrs.onArrow "down" item.id "sortable-standard__list-id")
          onArrowLeft=(action attrs.outdent item)
          onArrowRight=(action attrs.indent item)
        }}

        {{simple-editable
          value=item.description
          class="sortable-standard__description"
          onEnterKey=attrs.onEnterKey
          onMetaDelete=attrs.removeStandard
          onArrowLeft=(action attrs.outdent item)
          onArrowRight=(action attrs.indent item)
        }}

        {{simple-editable
          value=item.statementNotation
          class="sortable-standard__statement-notation"
          onEnterKey=attrs.onEnterKey
          onMetaDelete=attrs.removeStandard
          onArrowUp=(action attrs.onArrow "up" item.id "sortable-standard__statement-notation")
          onArrowDown=(action attrs.onArrow "down" item.id "sortable-standard__statement-notation")
          onArrowLeft=(action attrs.outdent item)
          onArrowRight=(action attrs.indent item)
        }}

  {{!-- {{#unless item.isCollapsed}}
    {{#sortable-group onChange=attrs.reorder as |nestedGroup|}}
      {{#each item.ancestorIds as |id index|}}
        {{sortable-standard item=(look-up standards id) index=index group=nestedGroup standards=standards}}
      {{/each}}
    {{/sortable-group}}
  {{/unless}} --}}
  {{/sortable-item}}
  {{/unless}}

  `,
})
<|endoftext|>


<commit_before>'use strict';

app = angular.module('myApp.students', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/students', {
    templateUrl: 'components/students/students.html',
    controller: 'StudentsCtrl'
  });
}]);

app.factory('userFactory', ['$http', function($http) {

    var urlBase = 'http://54.84.9.133:5000/api/';
    var userFactory = {};
    var config = {
        headers:
        {
            'Access-Control-Allow-Origin': 'True'
        }
    };

    userFactory.getUsers = function () {
        return $http.get(urlBase + 'users/', config);
    };
    userFactory.getUser = function (id) {
        return $http.get(urlBase + 'users/' + id, config);
    };
    userFactory.submitUser = function (user) {
        console.log('incoming user: '+ JSON.stringify(user))
        return $http.post(urlBase + 'submit', JSON.stringify(user), config);
    };
// return $resource('localhost:5000/users/:id', null,
//     {
//         'update': { method:'PUT' }
//     });
    return userFactory;
}]);

// In our controller we get the ID from the URL using ngRoute and $routeParams
// We pass in $routeParams and our Notes factory along with $scope
app.controller('StudentsCtrl', ['$scope', '$routeParams', 'userFactory', '$http', function($scope, $routeParams, userFactory, $http) {
    $scope.master = {};

    // jsonify the scope.user -> send to back_end for jsonification and updating database
    $scope.update = function(user) {
        $scope.master = angular.copy(user);
    };

    $scope.reset = function() {
        $scope.user = angular.copy($scope.master);
    };

    $scope.reset();

    $scope.send = function() {
        // First get a note object from the factory
        var id = 123454321;
        var user = userFactory.getUser(id)
        .success(function (custs) {
            console.log('Got user ' + id + ' response: ' + JSON.stringify(custs));
        })
        .error(function (error) {
            console.log('couldn\'t get user ' + id);
        });;

        userFactory.getUsers()
        .success(function (custs) {
            console.log('users: ' + JSON.stringify(custs));
        })
        .error(function (error) {
            console.log('couldn\'t get all users: ' + JSON.stringify(error));
        });

        userFactory.submitUser($scope.user)
        .success(function (custs) {
            console.log('this: ' + JSON.stringify(custs));
        })
        .error(function (error) {
            console.log('Bad request: ' + JSON.stringify(error));
        });
    };
}]);<commit_msg>Fix user route<commit_after>'use strict';

app = angular.module('myApp.students', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/students', {
    templateUrl: 'components/students/students.html',
    controller: 'StudentsCtrl'
  });
}]);

app.factory('userFactory', ['$http', function($http) {

    var urlBase = 'http://54.84.9.133:5000/api/';
    var userFactory = {};
    var config = {
        headers:
        {
            'Access-Control-Allow-Origin': 'True'
        }
    };

    userFactory.getUsers = function () {
        return $http.get(urlBase + 'users/', config);
    };
    userFactory.getUser = function (id) {
        return $http.get(urlBase + 'users/' + id + '/', config);
    };
    userFactory.submitUser = function (user) {
        console.log('incoming user: '+ JSON.stringify(user))
        return $http.post(urlBase + 'submit', JSON.stringify(user), config);
    };
// return $resource('localhost:5000/users/:id', null,
//     {
//         'update': { method:'PUT' }
//     });
    return userFactory;
}]);

// In our controller we get the ID from the URL using ngRoute and $routeParams
// We pass in $routeParams and our Notes factory along with $scope
app.controller('StudentsCtrl', ['$scope', '$routeParams', 'userFactory', '$http', function($scope, $routeParams, userFactory, $http) {
    $scope.master = {};

    // jsonify the scope.user -> send to back_end for jsonification and updating database
    $scope.update = function(user) {
        $scope.master = angular.copy(user);
    };

    $scope.reset = function() {
        $scope.user = angular.copy($scope.master);
    };

    $scope.reset();

    $scope.send = function() {
        // First get a note object from the factory
        var id = 123454321;
        var user = userFactory.getUser(id)
        .success(function (custs) {
            console.log('Got user ' + id + ' response: ' + JSON.stringify(custs));
        })
        .error(function (error) {
            console.log('couldn\'t get user ' + id);
        });;

        userFactory.getUsers()
        .success(function (custs) {
            console.log('users: ' + JSON.stringify(custs));
        })
        .error(function (error) {
            console.log('couldn\'t get all users: ' + JSON.stringify(error));
        });

        userFactory.submitUser($scope.user)
        .success(function (custs) {
            console.log('this: ' + JSON.stringify(custs));
        })
        .error(function (error) {
            console.log('Bad request: ' + JSON.stringify(error));
        });
    };
}]);<|endoftext|>


<commit_before>'use strict';

var request = require('urllib-sync').request;
var sleep = require('sleep').sleep;
var path = require('path');
var fs = require('fs');
var util = require('util');
var cheerio = require('cheerio');
var req = require('request');
var redis = require('./lib/redis');
var cookie = require('./job/cookie');

var apiRoot = 'http://weixin.sogou.com';
var userAgent = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36';
var mockHeaders = {
  'Cookie': 'CXID=B3EBF622BC23A4DD15784FC9617F7C36; SUID=52FC111B142D900A55B72DFB0004A20B; SUV=1439361586856051; pgv_pvi=2340838400; GOTO=Af99046; ssuid=2533552660; ABTEST=7|' + parseInt(new Date().getTime() / 1000 + '') + '|v1; weixinIndexVisited=1; sct=28; ld=Lkllllllll2Q1IgtlllllVbA1FwlllllpenAGyllllwllllljZlll5@@@@@@@@@@; ad=$lllllllll2qHhTElllllVboMpolllllpe4DUkllll9lllll9llll5@@@@@@@@@@; SNUID={SNUID}; IPLOC=CN4201',
  'Host': 'weixin.sogou.com',
  'User-Agent': userAgent,
};
var skipPage = 0;
var totalPage = 10;
var interval = 5; // 60s

function onerror(err) {
  console.log(err);
  console.log(err.stack);
  process.exit(1);
}

function ensureResult(body) {
  if (body.indexOf('您的访问出错了') >= 0) {
    var err = new Error('Reached list request limit.');
    err.name = 'RequestListLimited';
    err.url = url;
    err.originBody = body;
    return onerror(err);
  }
}

// 请求文章列表页
function requestList(page) {
  var url = apiRoot + util.format('/weixin?query=%s&sourceid=inttime_day&type=2&interation=&tsn=1&t=' + new Date().getTime(), 'node.js');
  console.log(apiRoot);
  console.log('[%s] %s', new Date(), url);
  var result = request(url, {
    timeout: 5000,
    headers: mockHeaders,
  });
  var body = result.data.toString();
  ensureResult(body);
//  console.log(body);
  handleList(body);
}

// 请求文章详情页
function requestArticle(link) {
  var url = link.indexOf('weixin.qq') === -1 ? apiRoot + link : link;
  console.log('[%s] requestArticle => %s', new Date(), url);
  var result = request(url, {
    timeout: 5000,
    headers: mockHeaders,
  });
  var body = result.data.toString();
  var headers = result.headers || {};
  var redirUrl = headers['location'] || '';
  ensureResult(body);
  if (String(result.status)[0] !== '3' ||
      !redirUrl || redirUrl.indexOf('antispider') >= 0) {

    var err = new Error('Request article failed.');
    err.name = 'RequestArticleError';
    err.url = url;
    err.originBody = body;
    return onerror(err);
  }
  console.log('[%s] redirUrl => %s', new Date(), redirUrl);
  var redirResult = request(redirUrl, {timeout: 5000});
  var redirBody = redirResult.data.toString();
  ensureResult(redirBody);
  return redirBody;
}

/**
 * 解析真实url
 * @returns {*|string}
 */
function handleRedirectUrl(link) {
  var url = link.indexOf('weixin.qq') === -1 ? apiRoot + link : link;
  //console.log('[%s] requestArticle => %s', new Date(), url);
  var result = request(url, {
    timeout: 5000,
    headers: mockHeaders
  });
  var headers = result.headers || {};
  //console.log('redirectUrl', headers['location']);
  return headers['location'] || '';
}

function handleList(res) {
  var articleList = [];
  var $ = cheerio.load(res, {normalizeWhitespace: true});
  var $chapters = $('.wx-rb .txt-box');

  $chapters.each(function(index, chapter) {
    var title = $(chapter).find('h4 a').text();
    var link = $(chapter).find('h4 a').attr('href');
    var $weixinAccount = $(chapter).find('.s-p a#weixin_account');
    var weixinAccountName = $weixinAccount.attr('title');
    var weixinAccountLink = $weixinAccount.attr('href');

    var article = {
      title: title,
      link: handleRedirectUrl(link),
      accountName: weixinAccountName,
      accountLink: apiRoot + weixinAccountLink,
      category: 'node.js'
    };

    articleList.push(article);

    console.log(article);

    sleep(interval);
  });

  console.log('articleList: ', articleList);

  articleList.forEach(function(article) {
    console.log('post data =>', article);
    req
      .post('http://blog.gaoqixhb.com/api/topic/add')
      .form(article);
  });
}

/**
 * 爬取
 */
function crawl() {
  console.log('key:', cookie.key);
  redis.srandmember(cookie.key, function(err, result) {
    if (err) return onerror(err);
    console.log('SUNID from redis:', result);
    result = result || '6E58D903A9AD86069D3733E3A916887E';

    console.log('get SNUID from pool:', result);
    mockHeaders.Cookie = mockHeaders.Cookie.replace('{SNUID}', result);
    if (err) return onerror(err);
    for (var page = 1 + skipPage; page <= totalPage; page++) {
      requestList(page);
      sleep(interval);
    }
  });
}

crawl();

<commit_msg>redis srandmember<commit_after>'use strict';

var request = require('urllib-sync').request;
var sleep = require('sleep').sleep;
var path = require('path');
var fs = require('fs');
var util = require('util');
var cheerio = require('cheerio');
var req = require('request');
var redis = require('./lib/redis');
var cookie = require('./job/cookie');

var apiRoot = 'http://weixin.sogou.com';
var userAgent = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36';
var mockHeaders = {
  'Cookie': 'CXID=B3EBF622BC23A4DD15784FC9617F7C36; SUID=52FC111B142D900A55B72DFB0004A20B; SUV=1439361586856051; pgv_pvi=2340838400; GOTO=Af99046; ssuid=2533552660; ABTEST=7|' + parseInt(new Date().getTime() / 1000 + '') + '|v1; weixinIndexVisited=1; sct=28; ld=Lkllllllll2Q1IgtlllllVbA1FwlllllpenAGyllllwllllljZlll5@@@@@@@@@@; ad=$lllllllll2qHhTElllllVboMpolllllpe4DUkllll9lllll9llll5@@@@@@@@@@; SNUID={SNUID}; IPLOC=CN4201',
  'Host': 'weixin.sogou.com',
  'User-Agent': userAgent,
};
var skipPage = 0;
var totalPage = 10;
var interval = 5; // 60s

function onerror(err) {
  console.log(err);
  console.log(err.stack);
  process.exit(1);
}

function ensureResult(body) {
  if (body.indexOf('您的访问出错了') >= 0) {
    var err = new Error('Reached list request limit.');
    err.name = 'RequestListLimited';
    err.url = url;
    err.originBody = body;
    return onerror(err);
  }
}

// 请求文章列表页
function requestList(page) {
  var url = apiRoot + util.format('/weixin?query=%s&sourceid=inttime_day&type=2&interation=&tsn=1&t=' + new Date().getTime(), 'node.js');
  console.log(apiRoot);
  console.log('[%s] %s', new Date(), url);
  var result = request(url, {
    timeout: 5000,
    headers: mockHeaders,
  });
  var body = result.data.toString();
//  console.log(body);
  ensureResult(body);
//  console.log(body);
  handleList(body);
}

// 请求文章详情页
function requestArticle(link) {
  var url = link.indexOf('weixin.qq') === -1 ? apiRoot + link : link;
  console.log('[%s] requestArticle => %s', new Date(), url);
  var result = request(url, {
    timeout: 5000,
    headers: mockHeaders,
  });
  var body = result.data.toString();
  var headers = result.headers || {};
  var redirUrl = headers['location'] || '';
  ensureResult(body);
  if (String(result.status)[0] !== '3' ||
      !redirUrl || redirUrl.indexOf('antispider') >= 0) {

    var err = new Error('Request article failed.');
    err.name = 'RequestArticleError';
    err.url = url;
    err.originBody = body;
    return onerror(err);
  }
  console.log('[%s] redirUrl => %s', new Date(), redirUrl);
  var redirResult = request(redirUrl, {timeout: 5000});
  var redirBody = redirResult.data.toString();
  ensureResult(redirBody);
  return redirBody;
}

/**
 * 解析真实url
 * @returns {*|string}
 */
function handleRedirectUrl(link) {
  var url = link.indexOf('weixin.qq') === -1 ? apiRoot + link : link;
  //console.log('[%s] requestArticle => %s', new Date(), url);
  var result = request(url, {
    timeout: 5000,
    headers: mockHeaders
  });
  var body = result.data.toString();
  console.log(body);
  var headers = result.headers || {};
  //console.log('redirectUrl', headers['location']);
  return headers['location'] || '';
}

function handleList(res) {
  var articleList = [];
  var $ = cheerio.load(res, {normalizeWhitespace: true});
  var $chapters = $('.wx-rb .txt-box');

  $chapters.each(function(index, chapter) {
    var title = $(chapter).find('h4 a').text();
    var link = $(chapter).find('h4 a').attr('href');
    var $weixinAccount = $(chapter).find('.s-p a#weixin_account');
    var weixinAccountName = $weixinAccount.attr('title');
    var weixinAccountLink = $weixinAccount.attr('href');

    var article = {
      title: title,
      link: handleRedirectUrl(link),
      accountName: weixinAccountName,
      accountLink: apiRoot + weixinAccountLink,
      category: 'node.js'
    };

    articleList.push(article);

    console.log(article);

    sleep(interval);
  });

  console.log('articleList: ', articleList);

  articleList.forEach(function(article) {
    console.log('post data =>', article);
    req
      .post('http://blog.gaoqixhb.com/api/topic/add')
      .form(article);
  });
}

/**
 * 爬取
 */
function crawl() {
  console.log('key:', cookie.key);
  redis
    .multi()
    .srandmember(cookie.key)
    .exec(function(err, result) {
      if (err) return onerror(err);
      result = result || '6E58D903A9AD86069D3733E3A916887E';

      console.log('get SNUID from pool:', result);
      mockHeaders.Cookie = mockHeaders.Cookie.replace('{SNUID}', result);
      if (err) return onerror(err);
      for (var page = 1 + skipPage; page <= totalPage; page++) {
        requestList(page);
        sleep(interval);
      }
    });
}

crawl();

<|endoftext|>


<commit_before>var node = require('./node');

function builder(optionsHandler){
	var parents = [ node(null) ];

	var b = {
		getRoot : function(){
			return parents[parents.length-1];
		},
		getAct : function(){
			return parents[0];
		},
		path : function(path, _fcts){
			if(typeof path !== "string"){
				throw new Error("Expect string param");
			}

			var alreadyExists = parents[0].childs.some(function(child){
				if(path === child.path){
					parents.unshift(child);
					return true;
				}
			});

			if(alreadyExists){
				if(arguments.length > 1){
					throw new Error("Path "+path+" already exists but you give me some use fcts");
				}
				return this;
			}
			var newChild = node(path);
			parents[0].childs.push(newChild);
			parents.unshift(newChild);
			this.use.apply(this, Array.prototype.slice.call(arguments,1));
			return this;
		},
		use : function(_fcts) {
			Array.prototype.slice.call(arguments).forEach(function(fct){
				if(typeof fct !== "function"){
					throw new Error("Expect function param");
				}
				parents[0].uses.push(fct);
			});
			return this;
		},
		method : function(verb, name, _fct){
			if(typeof verb !== "string"){
				throw new Error("First param must be string");
			}

			var fcts = Array.prototype.slice.call(arguments, (typeof name==='string'?2:1));

			if(fcts.length === 0){
				throw new Error("Expect at least one function for varargs second param");
			}
			fcts.some(function(fct){
				if(typeof fct !== "function"){
					throw new Error("Varargs second param must contains only functions");
				}
			});

			if(parents[0].methods[verb]){
				console.warn("You override the method",verb,"on path", parents[0].path);
			}
			parents[0].methods[verb] = {
				fcts : fcts
			};
			if(typeof name==='string'?name:null){
				parents[0].methods[verb].name = name;
			}

			if( !parents[0].methods['OPTIONS'] && optionsHandler){
				parents[0].methods['OPTIONS'] = {fcts : (typeof optionsHandler === 'function' ? [optionsHandler] : optionsHandler ) };
			}
			return this;
		},
		parent : function(){
			if(parents.length === 0){
				console.warn("You asked parent but already on root");
			}
			parents.shift();
			return this;
		}
	};
	['HEAD','OPTIONS','GET','PUT','POST', 'PATCH'].forEach(function(method){
		b[method.toLowerCase()] = b.method.bind(b, method);
	});
	b['del'] = b.method.bind(b,'DELETE');
	return b;
}

module.exports = builder;
<commit_msg>Use process.stderr instead of console.warn<commit_after>var node = require('./node');

function builder(optionsHandler){
	var parents = [ node(null) ];

	var b = {
		getRoot : function(){
			return parents[parents.length-1];
		},
		getAct : function(){
			return parents[0];
		},
		path : function(path, _fcts){
			if(typeof path !== "string"){
				throw new Error("Expect string param");
			}

			var alreadyExists = parents[0].childs.some(function(child){
				if(path === child.path){
					parents.unshift(child);
					return true;
				}
			});

			if(alreadyExists){
				if(arguments.length > 1){
					throw new Error("Path "+path+" already exists but you give me some use fcts");
				}
				return this;
			}
			var newChild = node(path);
			parents[0].childs.push(newChild);
			parents.unshift(newChild);
			this.use.apply(this, Array.prototype.slice.call(arguments,1));
			return this;
		},
		use : function(_fcts) {
			Array.prototype.slice.call(arguments).forEach(function(fct){
				if(typeof fct !== "function"){
					throw new Error("Expect function param");
				}
				parents[0].uses.push(fct);
			});
			return this;
		},
		method : function(verb, name, _fct){
			if(typeof verb !== "string"){
				throw new Error("First param must be string");
			}

			var fcts = Array.prototype.slice.call(arguments, (typeof name==='string'?2:1));

			if(fcts.length === 0){
				throw new Error("Expect at least one function for varargs second param");
			}
			fcts.some(function(fct){
				if(typeof fct !== "function"){
					throw new Error("Varargs second param must contains only functions");
				}
			});

			if(parents[0].methods[verb]){
				process.stderr.write("You override the method " + verb + " on path :" + parents[0].path + "\n");
			}
			parents[0].methods[verb] = {
				fcts : fcts
			};
			if(typeof name==='string'?name:null){
				parents[0].methods[verb].name = name;
			}

			if( !parents[0].methods['OPTIONS'] && optionsHandler){
				parents[0].methods['OPTIONS'] = {fcts : (typeof optionsHandler === 'function' ? [optionsHandler] : optionsHandler ) };
			}
			return this;
		},
		parent : function(){
			if(parents.length === 0){
				process.stderr.write("You asked parent but already on root.\n");
			}
			parents.shift();
			return this;
		}
	};
	['HEAD','OPTIONS','GET','PUT','POST', 'PATCH'].forEach(function(method){
		b[method.toLowerCase()] = b.method.bind(b, method);
	});
	b['del'] = b.method.bind(b,'DELETE');
	return b;
}

module.exports = builder;
<|endoftext|>


<commit_before><commit_msg>Fix win32 init problem with extra prompt (#75)<commit_after><|endoftext|>


<commit_before>/*
 * Copyright (c) 2011-2012, Yahoo! Inc.  All rights reserved.
 * Copyrights licensed under the New BSD License.
 * See the accompanying LICENSE file for terms.
 */
var State = require('buildy').State,
    Crypto = require('crypto'),
    mime = require('mime');

/**
 * Send content to s3. Simple Buildy wrapper for knox.
 * See https://github.com/LearnBoost/knox
 *
 * Example:
 *
 * var Registry = require('../../node_modules/buildy').Registry,
 *     Queue = require('../../node_modules/buildy').Queue,
 *     reg = new Registry(),
 *     knox_config = {
            key: '<api-key-here>',
            secret: '<secret-here>',
            bucket: 'shaker'
 *     };
 *
 * reg.load(__dirname + '/s3.js'); // s3 task
 *
 * new Queue('deploy', {registry: reg})
 *     .task('files', ['s3.js'])
 *     .task('concat')
 *     .task('jsminify')
 *     .task('s3', {name: '/foo/bar/baz_{checksum}.js', client: knox_config})
 *     .task('write', {name: 'baz.js'})
 *     .task('inspect')
 *     .run();
 *
 * @method s3Task
 * @param options {Object} s3 task options.
 * @param options.name {String} Resource name.
 * @param options.client {Object} s3 client (key, secret, bucket).
 * @param status {EventEmitter} Status object, handles 'complete' and 'failed' task exit statuses.
 * @param logger {winston.Logger} Logger instance, if additional logging required (other than task exit status)
 * @return {undefined}
 * @public
 */
function s3Task(options, status, logger) {
    var self = this,
        name = options.name,
        root = (options && options.root) || '',
        knox,
        client;

    try {
        knox = require('knox');
    } catch (exception) {
        console.log('Failed to find knox module, please install.');
        throw exception;
    }

    client = knox.createClient(options.client);

    // Send content to s3.
    function storeFile(filename, data) {
        var md5sum, req;

        if (filename.indexOf('{checksum}') > -1) {  // Replace {checksum} with md5 string
            md5sum = Crypto.createHash('md5');
            md5sum.update(data);
            filename = filename.replace('{checksum}', md5sum.digest('hex'));
        }

        filename = root + filename;

        req = client.put(filename, {'Content-Length': data.length, 'Content-Type': mime.lookup(filename)});

        req.on('response', function (res) {
            if (res.statusCode === 200) {
                self._state.set(State.TYPES.STRING, data);
                status.emit('complete', 's3', req.url);
            } else {
                status.emit('failed', 's3', 'error sending file: ' + res.statusCode);
            }
        });
        req.end(data);
    }

    switch (this._state.get().type) {

    case State.TYPES.FILES:
        storeFile(name, self._state.get().value.join("\n"));
        break;

    case State.TYPES.STRING:
        storeFile(name, self._state.get().value);
        break;

    case State.TYPES.STRINGS:
        storeFile(name, self._state.get().value.join(""));
        break;

    case State.TYPES.UNDEFINED:
        storeFile(name, "");
        break;

    default:
        status.emit('failed', 's3', 'unrecognised input type: ' + this._type);
        break;
    }
}

exports.tasks = {
    's3' : {
        callback: s3Task
    }
};
<commit_msg>removed yahoo copyright<commit_after>var State = require('buildy').State,
    Crypto = require('crypto'),
    mime = require('mime');

/**
 * Send content to s3. Simple Buildy wrapper for knox.
 * See https://github.com/LearnBoost/knox
 *
 * Example:
 *
 * var Registry = require('../../node_modules/buildy').Registry,
 *     Queue = require('../../node_modules/buildy').Queue,
 *     reg = new Registry(),
 *     knox_config = {
            key: '<api-key-here>',
            secret: '<secret-here>',
            bucket: 'shaker'
 *     };
 *
 * reg.load(__dirname + '/s3.js'); // s3 task
 *
 * new Queue('deploy', {registry: reg})
 *     .task('files', ['s3.js'])
 *     .task('concat')
 *     .task('jsminify')
 *     .task('s3', {name: '/foo/bar/baz_{checksum}.js', client: knox_config})
 *     .task('write', {name: 'baz.js'})
 *     .task('inspect')
 *     .run();
 *
 * @method s3Task
 * @param options {Object} s3 task options.
 * @param options.name {String} Resource name.
 * @param options.client {Object} s3 client (key, secret, bucket).
 * @param status {EventEmitter} Status object, handles 'complete' and 'failed' task exit statuses.
 * @param logger {winston.Logger} Logger instance, if additional logging required (other than task exit status)
 * @return {undefined}
 * @public
 */
function s3Task(options, status, logger) {
    var self = this,
        name = options.name,
        root = (options && options.root) || '',
        knox,
        client;

    try {
        knox = require('knox');
    } catch (exception) {
        console.log('Failed to find knox module, please install.');
        throw exception;
    }

    client = knox.createClient(options.client);

    // Send content to s3.
    function storeFile(filename, data) {
        var md5sum, req;

        if (filename.indexOf('{checksum}') > -1) {  // Replace {checksum} with md5 string
            md5sum = Crypto.createHash('md5');
            md5sum.update(data);
            filename = filename.replace('{checksum}', md5sum.digest('hex'));
        }

        filename = root + filename;

        req = client.put(filename, {'Content-Length': data.length, 'Content-Type': mime.lookup(filename)});

        req.on('response', function (res) {
            if (res.statusCode === 200) {
                self._state.set(State.TYPES.STRING, data);
                status.emit('complete', 's3', req.url);
            } else {
                status.emit('failed', 's3', 'error sending file: ' + res.statusCode);
            }
        });
        req.end(data);
    }

    switch (this._state.get().type) {

    case State.TYPES.FILES:
        storeFile(name, self._state.get().value.join("\n"));
        break;

    case State.TYPES.STRING:
        storeFile(name, self._state.get().value);
        break;

    case State.TYPES.STRINGS:
        storeFile(name, self._state.get().value.join(""));
        break;

    case State.TYPES.UNDEFINED:
        storeFile(name, "");
        break;

    default:
        status.emit('failed', 's3', 'unrecognised input type: ' + this._type);
        break;
    }
}

exports.tasks = {
    's3' : {
        callback: s3Task
    }
};
<|endoftext|>


<commit_before>const fs = require('fs');
const cp = require('child_process');
const im = require('imagemagick');
const readline = require('readline');
const commandLineArgs = require('command-line-args');

const fullWidth = 1920;
const fullHeight = 1080;
const outDir = './clips';

const optionDefinitions = [
  { name: 'delimiter', alias: 'd', type: String },
  { name: 'font', alias: 'f', type: String },
  { name: 'fontfamily', alias: 'a', type: String },
  { name: 'imagefolder', alias: 'i', type: String },
  { name: 'justify', alias: 'j', type: String },
  { name: 'lines', alias: 'l', type: Number },
  { name: 'music', alias: 'm', type: String },
  { name: 'size', alias: 's', type: Number },
  { name: 'text', alias: 't', type: String },
];
const options = commandLineArgs(optionDefinitions);

class TextBlock {
  constructor(text, i, j, font, fontsize) {
    this.text = text;
    this.font = font;
    this.fontsize = fontsize;
    this.i = i;
    this.j = j;
    this.x = 0;
    this.y = 0;
    this.width = 0;
    this.height = 0;
    this.fillSize(text, font, fontsize);
  }

  fillSize(text, font, fontsize) {
    im.convert([
      '-debug', 'annotate',
      'xc:',
      '-font', font,
      '-pointsize', fontsize,
      '-annotate', 0,
      text, 'null:'
    ], function (err, output) {
      if (err) {
        // In this case, stderr should have the output
        console.log('ERR: ' + err + '\n');
      } else if (output) {
        console.log('OUT: ' + output + '\n');
      }
    });
  }
}

var delimiter = options.hasOwnProperty('delimiter') ? options.delimiter : '===';
var font = options.font;
var fontfamily = options.fontfamily;
var justify = options.hasOwnProperty('justify') ? options.justify : 'c';
var nlines = options.hasOwnProperty('lines') ? options.lines : -1;
var music = options.music;
var fontsize = options.hasOwnProperty('size') ? options.size : '48';
var text = options.text;
var imgfolder = options.hasOwnProperty('imagefolder') ? options.imagefolder : '';

if (!options.hasOwnProperty('fontfamily')
 || !options.hasOwnProperty('music')
 || !options.hasOwnProperty('text')) {
  // Can't do anything useful without input
  return;
}

var proc = cp.spawnSync('/usr/bin/soxi', [ '-D', music ]);
var time = parseFloat(proc.stdout.toString().trim(), 10);
var images = [];
var finished = [];
var pages = 1;
var timePerPage = 1;
var lineReader = readline.createInterface({
  terminal: false,
  input: fs.createReadStream(text)
});
var screens = [];
var screenful = [];

lineReader.on('line', function (line) {
  if (line.startsWith(delimiter)) {
    var length = screenful.length;
    var reDelimiter = new RegExp('^' + delimiter, 'i');
    var bgimage = line.replace(reDelimiter, '').trim();
    var imageName = './bg-' + ('0000' + (screens.length + 1)).slice(-5) + '.png';

    images.push(imageName);
    if (bgimage !== '') {
      im.convert([
        imgfolder + '/' + bgimage,
        '-background', '#000030',
        '-gravity', 'Center',
        '-extent', fullWidth + 'x' + fullHeight,
        imageName
      ], function (err, output) {
        if (err) {
          console.log(err);
        } else {
          finished.push('bg' + screens.length);
        }
      });
    } else {
      im.convert([
        '-size', fullWidth + 'x' + fullHeight,
        'xc:#000030',
        imageName
      ], function (err, output) {
        if (err) {
          console.log(err);
        } else {
          finished.push('bg' + screens.length);
        }
      });
    }

    if (length < nlines) {
      var toAdd = Math.trunc((nlines - length) / 2);
      for (var l = 0; l < toAdd; l++) {
        screenful.unshift('');
      }
    }

    screens.push(screenful);
    screenful = [];
  } else {
    screenful.push(line);
  }
});
lineReader.on('close', function() {
  setTimeout(foregroundImages, 100);
});

function foregroundImages() {
  if (images.length != finished.length) {
    console.log('Waiting for image processing (' + finished.length + ' of ' + images.length + ')...');
    setTimeout(foregroundImages, 100);
  } else {
    pages = screens.length;
    timePerPage = time / pages;

    console.log('Runs for ' + time + 's, or ' + timePerPage + 's per page.');
    setTimeout(videoFromImages, 100);
    for (var page = 0; page < pages; page++) {
      var imageName = './credit-' + ('0000' + (page + 1)).slice(-5) + '.png';
      var bgImageName = './bg-' + ('0000' + (page + 1)).slice(-5) + '.png';
      var blocks = [];
      var lines = screens[page];
      var contents = lines.join('\n');
      var imageNames = [];

      if (nlines > 0) {
        var lineHeight = fullHeight / nlines;

        for (var l = 0; l < lines.length; l++) {
          if (lines[l].startsWith('[')) {
          }
        }
      }

      for (var ll = 0; ll < lines.length; ll++) {
        var fields = lines[ll].split('\t');

        for (var ff = 0; ff < fields.length; ff++) {
          blocks.push(new TextBlock(fields[ff], ll, ff, font, fontsize));
        }
      }

      images.push(imageName);
      im.convert([
        '-page', '+0+0', bgImageName,
        '-background', 'rgba(0,0,0,0)',
        '-fill', '#F0F0B0',
        '-font', font,
        '-size', fullWidth + 'x' + fullHeight,
        '-pointsize', fontsize,
        '-gravity', 'Center',
        'pango:' + contents + '',
        '-layers', 'flatten',
        imageName
      ], function (err, output) {
        if (err) {
          console.log(err);
        }

        finished.push(page);
      });
    }
  }
}

function videoFromImages() {
  if (images.length != finished.length) {
    console.log('Waiting for image processing (' + finished.length + ' of ' + images.length + ')...');
    setTimeout(videoFromImages, 100);
  } else {
    var outfile = text + '.mp4';
    fs.stat(outfile, function(err, stat) {
      if(err == null) {
        fs.unlink(outfile);
      }
      cp.spawnSync('/usr/bin/ffmpeg', [
        '-framerate', 1 / timePerPage,
        '-i', 'credit-%05d.png',
        '-i', music,
        '-strict', '-2',
        '-c:v', 'libx264',
        '-r', 30,
        '-shortest',
        '-pix_fmt', 'yuv420p',
        '-max_muxing_queue_size', '9999',
        text + '.mp4'
      ]);
      for (var i = 0; i < images.length; i++) {
        fs.unlink(images[i]);
      }
    });
  }
}

<commit_msg>Pull image file names out of each line<commit_after>const fs = require('fs');
const cp = require('child_process');
const im = require('imagemagick');
const readline = require('readline');
const commandLineArgs = require('command-line-args');

const fullWidth = 1920;
const fullHeight = 1080;
const outDir = './clips';

const optionDefinitions = [
  { name: 'delimiter', alias: 'd', type: String },
  { name: 'font', alias: 'f', type: String },
  { name: 'fontfamily', alias: 'a', type: String },
  { name: 'imagefolder', alias: 'i', type: String },
  { name: 'justify', alias: 'j', type: String },
  { name: 'lines', alias: 'l', type: Number },
  { name: 'music', alias: 'm', type: String },
  { name: 'size', alias: 's', type: Number },
  { name: 'text', alias: 't', type: String },
];
const options = commandLineArgs(optionDefinitions);

class TextBlock {
  constructor(text, i, j, font, fontsize) {
    this.text = text;
    this.font = font;
    this.fontsize = fontsize;
    this.i = i;
    this.j = j;
    this.x = 0;
    this.y = 0;
    this.width = 0;
    this.height = 0;
    this.fillSize(text, font, fontsize);
  }

  fillSize(text, font, fontsize) {
    im.convert([
      '-debug', 'annotate',
      'xc:',
      '-font', font,
      '-pointsize', fontsize,
      '-annotate', 0,
      text, 'null:'
    ], function (err, output) {
      if (err) {
        // In this case, stderr should have the output
        console.log('ERR: ' + err + '\n');
      } else if (output) {
        console.log('OUT: ' + output + '\n');
      }
    });
  }
}

var delimiter = options.hasOwnProperty('delimiter') ? options.delimiter : '===';
var font = options.font;
var fontfamily = options.fontfamily;
var justify = options.hasOwnProperty('justify') ? options.justify : 'c';
var nlines = options.hasOwnProperty('lines') ? options.lines : -1;
var music = options.music;
var fontsize = options.hasOwnProperty('size') ? options.size : '48';
var text = options.text;
var imgfolder = options.hasOwnProperty('imagefolder') ? options.imagefolder : '';

if (!options.hasOwnProperty('fontfamily')
 || !options.hasOwnProperty('music')
 || !options.hasOwnProperty('text')) {
  // Can't do anything useful without input
  return;
}

var proc = cp.spawnSync('/usr/bin/soxi', [ '-D', music ]);
var time = parseFloat(proc.stdout.toString().trim(), 10);
var images = [];
var finished = [];
var pages = 1;
var timePerPage = 1;
var lineReader = readline.createInterface({
  terminal: false,
  input: fs.createReadStream(text)
});
var screens = [];
var screenful = [];

lineReader.on('line', function (line) {
  if (line.startsWith(delimiter)) {
    var length = screenful.length;
    var reDelimiter = new RegExp('^' + delimiter, 'i');
    var bgimage = line.replace(reDelimiter, '').trim();
    var imageName = './bg-' + ('0000' + (screens.length + 1)).slice(-5) + '.png';

    images.push(imageName);
    if (bgimage !== '') {
      im.convert([
        imgfolder + '/' + bgimage,
        '-background', '#000030',
        '-gravity', 'Center',
        '-extent', fullWidth + 'x' + fullHeight,
        imageName
      ], function (err, output) {
        if (err) {
          console.log(err);
        } else {
          finished.push('bg' + screens.length);
        }
      });
    } else {
      im.convert([
        '-size', fullWidth + 'x' + fullHeight,
        'xc:#000030',
        imageName
      ], function (err, output) {
        if (err) {
          console.log(err);
        } else {
          finished.push('bg' + screens.length);
        }
      });
    }

    if (length < nlines) {
      var toAdd = Math.trunc((nlines - length) / 2);
      for (var l = 0; l < toAdd; l++) {
        screenful.unshift('');
      }
    }

    screens.push(screenful);
    screenful = [];
  } else {
    screenful.push(line);
  }
});
lineReader.on('close', function() {
  setTimeout(foregroundImages, 100);
});

function foregroundImages() {
  if (images.length != finished.length) {
    console.log('Waiting for image processing (' + finished.length + ' of ' + images.length + ')...');
    setTimeout(foregroundImages, 100);
  } else {
    pages = screens.length;
    timePerPage = time / pages;

    console.log('Runs for ' + time + 's, or ' + timePerPage + 's per page.');
    setTimeout(videoFromImages, 100);
    for (var page = 0; page < pages; page++) {
      var imageName = './credit-' + ('0000' + (page + 1)).slice(-5) + '.png';
      var bgImageName = './bg-' + ('0000' + (page + 1)).slice(-5) + '.png';
      var blocks = [];
      var lines = screens[page];
      var contents = lines.join('\n');
      var imageNames = [];

      if (nlines > 0) {
        var lineHeight = fullHeight / nlines;

        for (var l = 0; l < lines.length; l++) {
          if (lines[l].startsWith('[')) {
            var imagelist = lines[l].split(' ');

            for (var ii = 0 ; ii < imagelist.length; ii++) {
              cmdConvert.push(imgfolder + '/' + imagelist[ii].slice(1, -1));
            }
          }
        }
      }

      for (var ll = 0; ll < lines.length; ll++) {
        var fields = lines[ll].split('\t');

        for (var ff = 0; ff < fields.length; ff++) {
          blocks.push(new TextBlock(fields[ff], ll, ff, font, fontsize));
        }
      }

      images.push(imageName);
      im.convert([
        '-page', '+0+0', bgImageName,
        '-background', 'rgba(0,0,0,0)',
        '-fill', '#F0F0B0',
        '-font', font,
        '-size', fullWidth + 'x' + fullHeight,
        '-pointsize', fontsize,
        '-gravity', 'Center',
        'pango:' + contents + '',
        '-layers', 'flatten',
        imageName
      ], function (err, output) {
        if (err) {
          console.log(err);
        }

        finished.push(page);
      });
    }
  }
}

function videoFromImages() {
  if (images.length != finished.length) {
    console.log('Waiting for image processing (' + finished.length + ' of ' + images.length + ')...');
    setTimeout(videoFromImages, 100);
  } else {
    var outfile = text + '.mp4';
    fs.stat(outfile, function(err, stat) {
      if(err == null) {
        fs.unlink(outfile);
      }
      cp.spawnSync('/usr/bin/ffmpeg', [
        '-framerate', 1 / timePerPage,
        '-i', 'credit-%05d.png',
        '-i', music,
        '-strict', '-2',
        '-c:v', 'libx264',
        '-r', 30,
        '-shortest',
        '-pix_fmt', 'yuv420p',
        '-max_muxing_queue_size', '9999',
        text + '.mp4'
      ]);
      for (var i = 0; i < images.length; i++) {
        fs.unlink(images[i]);
      }
    });
  }
}

<|endoftext|>


<commit_before>import fsp from 'fs-promise'
import path from 'path'
import thenify from 'thenify'
import filesize from 'filesize'
import sortModulesBySize from '../../stats/sortModulesBySize'
import getConfig from '@sanity/util/lib/getConfig'
import {
  getWebpackCompiler,
  getDocumentElement,
  ReactDOM
} from '@sanity/server'

const absoluteMatch = /^https?:\/\//i

export default async (args, context) => {
  const {output, workDir} = context
  const flags = args.extOptions
  const outputDir = args.argsWithoutOptions[0] || path.join(workDir, 'dist')
  const config = getConfig(workDir).get('server')
  const compilationConfig = {
    env: 'production',
    staticPath: resolveStaticPath(workDir, config),
    basePath: workDir,
    outputPath: path.join(outputDir, 'static'),
    sourceMaps: flags['source-maps'],
    skipMinify: flags['skip-minify'] || false
  }

  const compiler = getWebpackCompiler(compilationConfig)
  const compile = thenify(compiler.run.bind(compiler))

  const spin = output.spinner('Building Sanity...')
  spin.start()

  const bundle = {}

  try {
    // Compile the bundle
    const statistics = await compile()
    const stats = statistics.toJson()
    if (stats.errors && stats.errors.length > 0) {
      throw new Error(
        `Errors while building:\n\n${stats.errors.join('\n\n')}`
      )
    }

    // Get hashes for each chunk
    const chunkMap = {}
    stats.chunks.forEach(chunk =>
      chunk.files.forEach(file => {
        chunkMap[file] = chunk.hash
      })
    )

    bundle.stats = stats

    // Build new index document with correct hashes
    spin.text = 'Building index document'
    console.log(chunkMap)
    const doc = await getDocumentElement({...compilationConfig, hashes: chunkMap}, {
      scripts: ['https://cdn.polyfill.io/v2/polyfill.min.js?features=Intl.~locale.en', 'vendor.bundle.js', 'app.bundle.js'].map(asset => {
        const assetPath = absoluteMatch.test(asset) ? asset : `js/${asset}`
        return {
          path: assetPath,
          hash: chunkMap[assetPath] || chunkMap[asset]
        }
      })
    })

    // Write index file to output destination
    await fsp.writeFile(
      path.join(outputDir, 'index.html'),
      `<!doctype html>${ReactDOM.renderToStaticMarkup(doc)}`
    )

    spin.stop()

    // Print build output, optionally stats if requested
    bundle.stats.warnings.forEach(output.print)
    output.print(`Javascript bundles built, time spent: ${bundle.stats.time}ms`)

    if (flags.stats) {
      output.print('\nLargest modules (unminified, uncompressed sizes):')
      sortModulesBySize(bundle.stats.modules).slice(0, 10).forEach(module =>
        output.print(`[${filesize(module.size)}] ${module.name}`)
      )
    }
  } catch (err) {
    spin.stop()
    output.error(err)
  }

  return bundle
}

function resolveStaticPath(rootDir, config) {
  const {staticPath} = config
  return path.isAbsolute(staticPath)
    ? staticPath
    : path.resolve(path.join(rootDir, staticPath))
}
<commit_msg>Remove debug statement<commit_after>import fsp from 'fs-promise'
import path from 'path'
import thenify from 'thenify'
import filesize from 'filesize'
import sortModulesBySize from '../../stats/sortModulesBySize'
import getConfig from '@sanity/util/lib/getConfig'
import {
  getWebpackCompiler,
  getDocumentElement,
  ReactDOM
} from '@sanity/server'

const absoluteMatch = /^https?:\/\//i

export default async (args, context) => {
  const {output, workDir} = context
  const flags = args.extOptions
  const outputDir = args.argsWithoutOptions[0] || path.join(workDir, 'dist')
  const config = getConfig(workDir).get('server')
  const compilationConfig = {
    env: 'production',
    staticPath: resolveStaticPath(workDir, config),
    basePath: workDir,
    outputPath: path.join(outputDir, 'static'),
    sourceMaps: flags['source-maps'],
    skipMinify: flags['skip-minify'] || false
  }

  const compiler = getWebpackCompiler(compilationConfig)
  const compile = thenify(compiler.run.bind(compiler))

  const spin = output.spinner('Building Sanity...')
  spin.start()

  const bundle = {}

  try {
    // Compile the bundle
    const statistics = await compile()
    const stats = statistics.toJson()
    if (stats.errors && stats.errors.length > 0) {
      throw new Error(
        `Errors while building:\n\n${stats.errors.join('\n\n')}`
      )
    }

    // Get hashes for each chunk
    const chunkMap = {}
    stats.chunks.forEach(chunk =>
      chunk.files.forEach(file => {
        chunkMap[file] = chunk.hash
      })
    )

    bundle.stats = stats

    // Build new index document with correct hashes
    spin.text = 'Building index document'
    const doc = await getDocumentElement({...compilationConfig, hashes: chunkMap}, {
      scripts: ['https://cdn.polyfill.io/v2/polyfill.min.js?features=Intl.~locale.en', 'vendor.bundle.js', 'app.bundle.js'].map(asset => {
        const assetPath = absoluteMatch.test(asset) ? asset : `js/${asset}`
        return {
          path: assetPath,
          hash: chunkMap[assetPath] || chunkMap[asset]
        }
      })
    })

    // Write index file to output destination
    await fsp.writeFile(
      path.join(outputDir, 'index.html'),
      `<!doctype html>${ReactDOM.renderToStaticMarkup(doc)}`
    )

    spin.stop()

    // Print build output, optionally stats if requested
    bundle.stats.warnings.forEach(output.print)
    output.print(`Javascript bundles built, time spent: ${bundle.stats.time}ms`)

    if (flags.stats) {
      output.print('\nLargest modules (unminified, uncompressed sizes):')
      sortModulesBySize(bundle.stats.modules).slice(0, 10).forEach(module =>
        output.print(`[${filesize(module.size)}] ${module.name}`)
      )
    }
  } catch (err) {
    spin.stop()
    output.error(err)
  }

  return bundle
}

function resolveStaticPath(rootDir, config) {
  const {staticPath} = config
  return path.isAbsolute(staticPath)
    ? staticPath
    : path.resolve(path.join(rootDir, staticPath))
}
<|endoftext|>


<commit_before>import React from 'react';
import BpkCheckbox from 'bpk-component-checkbox';
import BpkParagraph from 'bpk-component-paragraph';
import { spacingSm } from 'bpk-tokens/tokens/base.es6';
import accordionsReadme from 'bpk-component-accordion/readme.md';
import { BpkAccordionContainer, BpkAccordionItem } from 'bpk-component-accordion';

import DocsPageBuilder from './../../components/DocsPageBuilder';

const CheckboxWrapper = props => <div style={{ padding: `${spacingSm} 0` }} {...props} />;

const StopsContent = () => (
  <form>
    <CheckboxWrapper>
      <BpkCheckbox
        name="direct"
        label="Direct"
        onChange={() => null}
        checked
      />
    </CheckboxWrapper>
    <CheckboxWrapper>
      <BpkCheckbox
        name="1-stop"
        label="1 stop"
        onChange={() => null}
        checked
      />
    </CheckboxWrapper>
    <CheckboxWrapper>
      <BpkCheckbox
        name="2-plus-stops"
        label="2+ stops"
        onChange={() => null}
        checked
      />
    </CheckboxWrapper>
  </form>
);

const AirlinesContent = () => (
  <form>
    <CheckboxWrapper>
      <BpkCheckbox
        name="air-france"
        label="Air France"
        onChange={() => null}
        checked
      />
    </CheckboxWrapper>
    <CheckboxWrapper>
      <BpkCheckbox
        name="alitalia"
        label="Alitalia"
        onChange={() => null}
        checked
      />
    </CheckboxWrapper>
    <CheckboxWrapper>
      <BpkCheckbox
        name="bmi-regional"
        label="bmi regional"
        onChange={() => null}
        checked
      />
    </CheckboxWrapper>
    <CheckboxWrapper>
      <BpkCheckbox
        name="british-airways"
        label="British Airways"
        onChange={() => null}
        checked
      />
    </CheckboxWrapper>
    <CheckboxWrapper>
      <BpkCheckbox
        name="easyjet"
        label="Easyjet"
        onChange={() => null}
        checked
      />
    </CheckboxWrapper>
  </form>
);

const AirportsContent = () => (
  <form>
    <CheckboxWrapper>
      <BpkCheckbox
        name="lcy"
        label="London City"
        onChange={() => null}
        checked
      />
    </CheckboxWrapper>
    <CheckboxWrapper>
      <BpkCheckbox
        name="LGW"
        label="London Gatwick"
        onChange={() => null}
        checked
      />
    </CheckboxWrapper>
    <CheckboxWrapper>
      <BpkCheckbox
        name="lhr"
        label="London Heathrow"
        onChange={() => null}
        checked
      />
    </CheckboxWrapper>
    <CheckboxWrapper>
      <BpkCheckbox
        name="ltn"
        label="London Luton"
        onChange={() => null}
        checked
      />
    </CheckboxWrapper>
    <CheckboxWrapper>
      <BpkCheckbox
        name="stn"
        label="London Stansted"
        onChange={() => null}
        checked
      />
    </CheckboxWrapper>
  </form>
);

const components = [
  {
    id: 'default',
    title: 'Default',
    blurb: [
      <BpkParagraph>
        By default, accorions allow only one section to be expanded at any time.
      </BpkParagraph>,
    ],
    examples: [
      <BpkAccordionContainer>
        <BpkAccordionItem id="stops" title="Stops" expanded>
          <StopsContent />
        </BpkAccordionItem>
        <BpkAccordionItem id="airlines" title="Airlines">
          <AirlinesContent />
        </BpkAccordionItem>
        <BpkAccordionItem id="airports" title="Airports">
          <AirportsContent />
        </BpkAccordionItem>
      </BpkAccordionContainer>,
    ],
  },
  {
    id: 'multiple-section-open',
    title: 'Multiple sections open',
    blurb: [
      <BpkParagraph>
        Accordions can also be configured to allow multiple sections to be expanded simultaneously.
      </BpkParagraph>,
    ],
    examples: [
      <BpkAccordionContainer allowMultiple>
        <BpkAccordionItem id="stops" title="Stops" expanded>
          <StopsContent />
        </BpkAccordionItem>
        <BpkAccordionItem id="airlines" title="Airlines">
          <AirlinesContent />
        </BpkAccordionItem>
        <BpkAccordionItem id="airports" title="Airports">
          <AirportsContent />
        </BpkAccordionItem>
      </BpkAccordionContainer>,
    ],
  },
];

const AccordionsPage = () => <DocsPageBuilder
  title="Accordions"
  blurb={[
    <BpkParagraph>
      An accordion is a vertically stacked set of elements, such as content or forms, that allow the user to toggle
      the display of sections of content. Each labeling element can be expanded or collapsed to reveal or hide its
      associated content. Accordions are commonly used to reduce the need to scroll when presenting multiple sections
      of content on a single page.
    </BpkParagraph>,
  ]}
  components={components}
  readme={accordionsReadme}
  sassdocId="accordions"
/>;

export default AccordionsPage;
<commit_msg>Fix typo<commit_after>import React from 'react';
import BpkCheckbox from 'bpk-component-checkbox';
import BpkParagraph from 'bpk-component-paragraph';
import { spacingSm } from 'bpk-tokens/tokens/base.es6';
import accordionsReadme from 'bpk-component-accordion/readme.md';
import { BpkAccordionContainer, BpkAccordionItem } from 'bpk-component-accordion';

import DocsPageBuilder from './../../components/DocsPageBuilder';

const CheckboxWrapper = props => <div style={{ padding: `${spacingSm} 0` }} {...props} />;

const StopsContent = () => (
  <form>
    <CheckboxWrapper>
      <BpkCheckbox
        name="direct"
        label="Direct"
        onChange={() => null}
        checked
      />
    </CheckboxWrapper>
    <CheckboxWrapper>
      <BpkCheckbox
        name="1-stop"
        label="1 stop"
        onChange={() => null}
        checked
      />
    </CheckboxWrapper>
    <CheckboxWrapper>
      <BpkCheckbox
        name="2-plus-stops"
        label="2+ stops"
        onChange={() => null}
        checked
      />
    </CheckboxWrapper>
  </form>
);

const AirlinesContent = () => (
  <form>
    <CheckboxWrapper>
      <BpkCheckbox
        name="air-france"
        label="Air France"
        onChange={() => null}
        checked
      />
    </CheckboxWrapper>
    <CheckboxWrapper>
      <BpkCheckbox
        name="alitalia"
        label="Alitalia"
        onChange={() => null}
        checked
      />
    </CheckboxWrapper>
    <CheckboxWrapper>
      <BpkCheckbox
        name="bmi-regional"
        label="bmi regional"
        onChange={() => null}
        checked
      />
    </CheckboxWrapper>
    <CheckboxWrapper>
      <BpkCheckbox
        name="british-airways"
        label="British Airways"
        onChange={() => null}
        checked
      />
    </CheckboxWrapper>
    <CheckboxWrapper>
      <BpkCheckbox
        name="easyjet"
        label="Easyjet"
        onChange={() => null}
        checked
      />
    </CheckboxWrapper>
  </form>
);

const AirportsContent = () => (
  <form>
    <CheckboxWrapper>
      <BpkCheckbox
        name="lcy"
        label="London City"
        onChange={() => null}
        checked
      />
    </CheckboxWrapper>
    <CheckboxWrapper>
      <BpkCheckbox
        name="LGW"
        label="London Gatwick"
        onChange={() => null}
        checked
      />
    </CheckboxWrapper>
    <CheckboxWrapper>
      <BpkCheckbox
        name="lhr"
        label="London Heathrow"
        onChange={() => null}
        checked
      />
    </CheckboxWrapper>
    <CheckboxWrapper>
      <BpkCheckbox
        name="ltn"
        label="London Luton"
        onChange={() => null}
        checked
      />
    </CheckboxWrapper>
    <CheckboxWrapper>
      <BpkCheckbox
        name="stn"
        label="London Stansted"
        onChange={() => null}
        checked
      />
    </CheckboxWrapper>
  </form>
);

const components = [
  {
    id: 'default',
    title: 'Default',
    blurb: [
      <BpkParagraph>
        By default, accordions allow only one section to be expanded at any time.
      </BpkParagraph>,
    ],
    examples: [
      <BpkAccordionContainer>
        <BpkAccordionItem id="stops" title="Stops" expanded>
          <StopsContent />
        </BpkAccordionItem>
        <BpkAccordionItem id="airlines" title="Airlines">
          <AirlinesContent />
        </BpkAccordionItem>
        <BpkAccordionItem id="airports" title="Airports">
          <AirportsContent />
        </BpkAccordionItem>
      </BpkAccordionContainer>,
    ],
  },
  {
    id: 'multiple-section-open',
    title: 'Multiple sections open',
    blurb: [
      <BpkParagraph>
        Accordions can also be configured to allow multiple sections to be expanded simultaneously.
      </BpkParagraph>,
    ],
    examples: [
      <BpkAccordionContainer allowMultiple>
        <BpkAccordionItem id="stops" title="Stops" expanded>
          <StopsContent />
        </BpkAccordionItem>
        <BpkAccordionItem id="airlines" title="Airlines">
          <AirlinesContent />
        </BpkAccordionItem>
        <BpkAccordionItem id="airports" title="Airports">
          <AirportsContent />
        </BpkAccordionItem>
      </BpkAccordionContainer>,
    ],
  },
];

const AccordionsPage = () => <DocsPageBuilder
  title="Accordions"
  blurb={[
    <BpkParagraph>
      An accordion is a vertically stacked set of elements, such as content or forms, that allow the user to toggle
      the display of sections of content. Each labeling element can be expanded or collapsed to reveal or hide its
      associated content. Accordions are commonly used to reduce the need to scroll when presenting multiple sections
      of content on a single page.
    </BpkParagraph>,
  ]}
  components={components}
  readme={accordionsReadme}
  sassdocId="accordions"
/>;

export default AccordionsPage;
<|endoftext|>


<commit_before>/**
 * @license RequireCSS 0.3.1 Copyright (c) 2011, VIISON All Rights Reserved.
 * Available via the MIT or new BSD license.
 * see: http://github.com/VIISON/RequireCSS for details
 */
(function(){function e(b){var c=a.createElement("link");return c.rel="stylesheet",c.type="text/css",c.href=b,c}function f(b){var c;d.href=b;for(c in a.styleSheets)if(a.styleSheets[c].href===d.href)return!0;return!1}function g(a,b){c?h(a,b):i(a,b)}function h(a,c){var d=e(a);d.onload=function(){c()},b.appendChild(d)}function i(c,d){var g=e(c),h=a.createElement("script");b.appendChild(g),h.onload=h.onerror=function(){b.removeChild(h);var a=function(){if(f(c)){d();return}setTimeout(a,25)};a()},h.src=c,b.appendChild(h)}"use strict";var a=document,b=a.head||a.getElementsByTagName("head")[0],c=a.createElement("link").onload===null?undefined:!1,d=a.createElement("a");define(function(){var a;return a={version:"0.3.1",load:function(a,d,f){var h=d.toUrl(a.search(/\.(css|less|scss)$/i)===-1?a+".css":a);if(c===undefined){var i=e("data:text/css,");i.onload=function(){c=!0},b.appendChild(i),setTimeout(function(){b.removeChild(i),c!==!0&&(c=!1),g(h,f)},0)}else g(h,f)}},a})})()<commit_msg>Update minified version<commit_after>/**
 * @license RequireCSS 0.3.1 Copyright (c) 2011, VIISON All Rights Reserved.
 * Available via the MIT or new BSD license.
 * see: http://github.com/VIISON/RequireCSS for details
 */
(function(){function e(b){var c=a.createElement("link");return c.rel="stylesheet",c.type="text/css",c.href=b,c}function f(b){var c;d.href=b;for(c in a.styleSheets)if(a.styleSheets[c].href===d.href)return!0;return!1}function g(a,c){var d=e(a);d.onload=function(){c()},b.appendChild(d)}function h(c,d){var g=e(c),h=a.createElement("script");b.appendChild(g),h.onload=h.onerror=function(){b.removeChild(h);var a=function(){if(f(c)){d();return}setTimeout(a,25)};a()},h.src=c,b.appendChild(h)}function i(a,b){c?g(a,b):h(a,b)}"use strict";var a=document,b=a.head||a.getElementsByTagName("head")[0],c=a.createElement("link").onload===null?undefined:!1,d=a.createElement("a");define(function(){var a;return a={version:"0.3.1",load:function(a,d,f){var g=d.toUrl(a.search(/\.(css|less|scss)$/i)===-1?a+".css":a);if(c===undefined){var h=e("data:text/css,");h.onload=function(){c=!0},b.appendChild(h),setTimeout(function(){b.removeChild(h),c!==!0&&(c=!1),i(g,f)},0)}else i(g,f)}},a})})()<|endoftext|>