<commit_before>var letter = "
 From the Secretary General
\

\

\
Greetings,\

\
It is my utmost pleasure to welcome you to the 3rd edition of IIITH-MUN, from 27 January to 29 January, 2017 at IIIT Hyderabad. IIITH-MUN aims to offer a platform where you can meet a number of talented delegates, and debate on a diverse range of problems relevant on the global scale.\

\
IIITH-MUN intends to promote healthy debate, deliberation and cooperation. As you battle it out (intellectually, of course) with the rest of the delegates, IIITH-MUN will expose you to a host of world problems - not just those we face currently, but potential ones that can arise in the future too. It will challenge you to design solutions in a diplomatic manner, through continued discussion and cooperation with delegates representing other countries. \

\

\
This year, we will be hosting the MUN in partnership with CID (Conclave of International Diplomats), an organization which is an independent body of young enthusiasts hailing from various professional and non- professional backgrounds who aim to involve Indian youth to participate and bring out their talents. We hope that you take away more than just the memories of the MUN after it's done - valuable experience in diplomacy, better debating skills and a more open mind towards finding cooperative and synergistic solutions to diplomatic issues.\

\

\
We hope to have an enjoyable and exciting IIITH-MUN, and look forward to welcoming all of you in January 2017.\

Read More\

\

\
With regards
\
<object type=\"image/svg+xml\" data=\"images/signature.svg\">\
  Your browser does not support SVG\
</object>\

\
Siddhant Shrivastava,\

\
Secretary General,\

\
IIITH-MUN, 2017\
"

var links = [
    {t:"Home",l:"index"},
    {t:"Schedule",l:"schedule"},
   // {t:"Executive Board",l:"eb"},
    {t:"Committees",l:"committees"},
   // {t:"Allotment",l:"resources"},
    {t:"Contact",l:"contact"}
];
var menus = [{t:"About",l:[
    {t:'About Felicity',l:'about-felicity'},
    {t:'About IIIT-H MUN',l:'about-iiith-mun'},
    {t:'About MUNs',l:'about-mun'}
    ]}];

var secretariat =
[
{'position':'Secretary General','image':'sid.png','name': 'Siddhant Shrivastava', 'pno': '+96895162722', 'email': 'siddhant.shrivastava23@gmail.com'},
{'position':'Director General','name': 'Aayush Naik','image':'aayush.png', 'pno': '+96567056579', 'email': 'aayushnaik17@gmail.com'},
{'position':'USG Admin','name': 'Aditya Bharti', 'pno': '+919618153254','image':'adi.png', 'email': 'adibhar97@gmail.com'},
{'position':'USG Marketing','name': 'Saumya Prabodh', 'pno': '919618207958','image':'saumya.jpg', 'email': 'srivastava.saumya2811@gmail.com'},
{'position':'USG Policy','name': 'Nitin John Raj', 'pno': '+919148157997','image':'nitin.jpg', 'email': 'nitinjohnraj@gmail.com'},
{'position':'USG Design','name': 'Pranav Nair', 'pno': '+919642071222','image':'pranav.jpg', 'email': 'pranavnair97@gmail.com'},
{'position':'USG Content Writing','name': 'Aurobindo Mungala', 'pno': '+919566067176','image':'auro.jpg', 'email': 'koolschoolfan@gmail.com'},
{'position':'USG Technology','name': 'Mukul Hase', 'pno': '9652743554','image':'mukul.jpg', 'email': 'mukulhase@gmail.com'},
{'position':'USG Hospitality','name': 'Riya Pal', 'pno': '+918886222863','image':'riya.jpg', 'email': 'riya.pal@gmail.com'},
{'position':'USG Design','name': 'Suhas Darsi', 'pno': '9000725505', 'email': 'darsisuhas666@gmail.com'},
{'name':'Sriram Indurthi','position':'Founder General','image':'Sriram.jpg'}
];

var committees =
[
{
    'image':'fsc.png',
    'title':'Futuristic Security Council',
    'content': '\'The United Nations remains our most important global actor. These days we are continuously reminded of the enormous responsibility of the Security Council to uphold international peace and stability.”\
Anna Lindh\
The UN Security Council is one of the six principal organs of the UN, tasked with the maintenance of international peace and security, as well as accepting new members to the UN and approving any changes to the United Nations Charter. It’s powers include the establishment of peacekeeping operations, imposing international sanctions, and the authorization of military action through resolutions. It is the only committee that is capable of issuing binding resolutions to member states.\'\
At IIIT-H MUN 2016, FSC delegates will be taken a few years into the future, to discuss and resolve issues that a potential Security Council of that time would deal with. This committee will allow each delegate to test both their deductive and imaginative skills, and to create solutions to problems that generations of the future will have to eventually face, and resolve. \
'
},{
    'image':'disec.png',
    'title':'DISEC',
    'content':'‘Terrorism festers where conflicts are endemic... and when human rights, human dignity, and human life are not protected and impunity prevails... We have to drown out shrill appeals to intolerance and extremism with sound calls for compassion and moderation.’ \
 – Ban Ki-moon, UN Secretary-General\
\
\
The Disarmament and International Security Committee (DISEC) is the First Committee of the United Nations General Assembly. It deals with disarmament and threats to global peace. In light of the events in Hiroshima and Nagasaki, the first resolution by DISEC was created in 1946 to address international concerns for the “Establishment of a Commission to Deal with the Problems Raised by the Discovery of Atomic Energy.”\
DISEC is perhaps one of the most important General Assembly committees, and it is the only one other than the Main Committee of the General Assembly entitled to verbatim records coverage. \
\
\
As DISEC members, delegates will debate and discuss about a wide variety of arms- and security-related issues, and pass resolutions that would help to make the world a safer and more peaceful place.\
'

},
{
    'image':'unhrc.png',
    'title':'Human Rights Council',
    'content':'“Human rights are not a privilege granted by the few, they are a liberty entitled to all, and human rights, by definition, include the rights of all humans, those in the dawn of life, the dusk of life, or the shadows of life.”\
Kay Granger\
\
\
The Human Rights Council is an inter-governmental body within the United Nations system responsible for strengthening the promotion and protection of human rights around the globe and for addressing situations of human rights violations and make recommendations on them. It has the ability to discuss all thematic human rights issues and situations that require its attention throughout the year. The Council is made up of 47 United Nations Member States which are elected by the UN General Assembly. \
 \
The UN HRC deals with topics that revolve around Human Rights violations - such as discrimination against minority groups, abuse of human rights, and human rights during conflict. It abides by the many different human rights conventions, and works with special rapporteurs and working groups to investigate human rights violations, and to keep states in check. \
'
},
{
    'image':'unodc.png',
    'title':'Office On Drugs and Crime',
    'content':'\
“Working together to take action against drugs, crime, corruption and terrorism, we can increase security and improve the lives of individuals, families and communities all over the world."\
UNODC Executive DIrector, Yury Fedotov\
\
\
A unique and specialised committee, the UNODC deals with the global fight against illicit drugs and international crime. It combats certain specialised problems faced by the international community, such as: organised crime and trafficking, crime prevention, crime prevention and criminal justice reform, drug abuse prevention and terrorism prevention.\
\
\
Due to the broad scope of its work, the UNODC operates through all the regions of the world through an extensive network of field offices. It works via three main channels - field-based cooperation projects to help states combat the above problems, research and analytical work that provides a solid theoretical base for policy decisions on the above topics, and assisting states in the ratification and implementation of international treaties.\
\
\
As UNODC members, delegates will confront problems specific to drugs and crime prevention, looking at these topics both from the national and global point of view, and be challenged to devise policies and solutions that would be relevant and implementable in today’s world.\
'
},
{
    'image':'aippm.png',
    'title':'All India Political Parties Meet',
    'content':'“Unity in diversity is India\'s strength. There is simplicity in every Indian. There is unity in every corener of India. This is our strength”\
-Narendra Modi, Prime Minister, India\
\
\
AIPPM is a council consisting of political representatives of various parties, working together to discuss issues of national importance. \
\
\
Members of this council must be aware that many of these issues are complex, and should keep in mind that there are more than a billion people in India - of diverse religions, castes, creeds and try to represent views inclusively. \
'
}
]
var applications = [
{
    name:"Delegate",
    link:"https://iiithmun.typeform.com/to/cd67cV?typeform-embed=embed-widget"
},
{
    name:"International Press",
    link:"https://iiithmun.typeform.com/to/cd67cV?typeform-embed=embed-widget"
},
{
    name:"Delegation",
    link:"https://iiithmun.typeform.com/to/WjHJLU?typeform-embed=embed-widget"
}
]
var schedule = [
{
   'day':"27th January",
   'events':[
        "Registration",
        "Opening ceremony",
        "Orientation",
        "Lunch",
        "1st committee session",
        "Tea/Snacks break",
        "1st Committee session continues",
        "Dinner",
        "Social night (Felicity night), if any",
        "Buses depart to delegate accommodation "
    ]
},
{
    'day':"28th January",
    'events':[
        "Breakfast3",
        "2nd Committee session",
        "Lunch",
        "3rd committee session",
        "Tea/Snacks break",
        "Break",
        "Dinner",
        "Social night",
    ]
},
{
    'day':'29th January',
    'events':[
        "Breakfast",
        "4th committee session",
        "Lunch",
        "5th committee session",
        "Closing ceremony"
    ]
}
];
contact = [
{
    'name': 'Saumya Prabodh',
    'position':'USG Marketing',
    'phone': '09618207958',
    'email': 'srivastava.saumya2811@gmail.com'
},
{
    'name': 'Aditya Bharti',
    'position': 'USG Administration',
    'phone': '9618153254',
    'email': 'adibhar97@gmail.com'
}];
sponsors = [
{
    'image': "cid.jpg"
},{
    'image': "iiit-new.png"
},{
    'image': "oyo.png"
}]
<commit_msg>Changed typeform link<commit_after>var letter = "
 From the Secretary General
\

\

\
Greetings,\

\
It is my utmost pleasure to welcome you to the 3rd edition of IIITH-MUN, from 27 January to 29 January, 2017 at IIIT Hyderabad. IIITH-MUN aims to offer a platform where you can meet a number of talented delegates, and debate on a diverse range of problems relevant on the global scale.\

\
IIITH-MUN intends to promote healthy debate, deliberation and cooperation. As you battle it out (intellectually, of course) with the rest of the delegates, IIITH-MUN will expose you to a host of world problems - not just those we face currently, but potential ones that can arise in the future too. It will challenge you to design solutions in a diplomatic manner, through continued discussion and cooperation with delegates representing other countries. \

\

\
This year, we will be hosting the MUN in partnership with CID (Conclave of International Diplomats), an organization which is an independent body of young enthusiasts hailing from various professional and non- professional backgrounds who aim to involve Indian youth to participate and bring out their talents. We hope that you take away more than just the memories of the MUN after it's done - valuable experience in diplomacy, better debating skills and a more open mind towards finding cooperative and synergistic solutions to diplomatic issues.\

\

\
We hope to have an enjoyable and exciting IIITH-MUN, and look forward to welcoming all of you in January 2017.\

Read More\

\

\
With regards
\
<object type=\"image/svg+xml\" data=\"images/signature.svg\">\
  Your browser does not support SVG\
</object>\

\
Siddhant Shrivastava,\

\
Secretary General,\

\
IIITH-MUN, 2017\
"

var links = [
    {t:"Home",l:"index"},
    {t:"Schedule",l:"schedule"},
   // {t:"Executive Board",l:"eb"},
    {t:"Committees",l:"committees"},
   // {t:"Allotment",l:"resources"},
    {t:"Contact",l:"contact"}
];
var menus = [{t:"About",l:[
    {t:'About Felicity',l:'about-felicity'},
    {t:'About IIIT-H MUN',l:'about-iiith-mun'},
    {t:'About MUNs',l:'about-mun'}
    ]}];

var secretariat =
[
{'position':'Secretary General','image':'sid.png','name': 'Siddhant Shrivastava', 'pno': '+96895162722', 'email': 'siddhant.shrivastava23@gmail.com'},
{'position':'Director General','name': 'Aayush Naik','image':'aayush.png', 'pno': '+96567056579', 'email': 'aayushnaik17@gmail.com'},
{'position':'USG Admin','name': 'Aditya Bharti', 'pno': '+919618153254','image':'adi.png', 'email': 'adibhar97@gmail.com'},
{'position':'USG Marketing','name': 'Saumya Prabodh', 'pno': '919618207958','image':'saumya.jpg', 'email': 'srivastava.saumya2811@gmail.com'},
{'position':'USG Policy','name': 'Nitin John Raj', 'pno': '+919148157997','image':'nitin.jpg', 'email': 'nitinjohnraj@gmail.com'},
{'position':'USG Design','name': 'Pranav Nair', 'pno': '+919642071222','image':'pranav.jpg', 'email': 'pranavnair97@gmail.com'},
{'position':'USG Content Writing','name': 'Aurobindo Mungala', 'pno': '+919566067176','image':'auro.jpg', 'email': 'koolschoolfan@gmail.com'},
{'position':'USG Technology','name': 'Mukul Hase', 'pno': '9652743554','image':'mukul.jpg', 'email': 'mukulhase@gmail.com'},
{'position':'USG Hospitality','name': 'Riya Pal', 'pno': '+918886222863','image':'riya.jpg', 'email': 'riya.pal@gmail.com'},
{'position':'USG Design','name': 'Suhas Darsi', 'pno': '9000725505', 'email': 'darsisuhas666@gmail.com'},
{'name':'Sriram Indurthi','position':'Founder General','image':'Sriram.jpg'}
];

var committees =
[
{
    'image':'fsc.png',
    'title':'Futuristic Security Council',
    'content': '\'The United Nations remains our most important global actor. These days we are continuously reminded of the enormous responsibility of the Security Council to uphold international peace and stability.”\
Anna Lindh\
The UN Security Council is one of the six principal organs of the UN, tasked with the maintenance of international peace and security, as well as accepting new members to the UN and approving any changes to the United Nations Charter. It’s powers include the establishment of peacekeeping operations, imposing international sanctions, and the authorization of military action through resolutions. It is the only committee that is capable of issuing binding resolutions to member states.\'\
At IIIT-H MUN 2016, FSC delegates will be taken a few years into the future, to discuss and resolve issues that a potential Security Council of that time would deal with. This committee will allow each delegate to test both their deductive and imaginative skills, and to create solutions to problems that generations of the future will have to eventually face, and resolve. \
'
},{
    'image':'disec.png',
    'title':'DISEC',
    'content':'‘Terrorism festers where conflicts are endemic... and when human rights, human dignity, and human life are not protected and impunity prevails... We have to drown out shrill appeals to intolerance and extremism with sound calls for compassion and moderation.’ \
 – Ban Ki-moon, UN Secretary-General\
\
\
The Disarmament and International Security Committee (DISEC) is the First Committee of the United Nations General Assembly. It deals with disarmament and threats to global peace. In light of the events in Hiroshima and Nagasaki, the first resolution by DISEC was created in 1946 to address international concerns for the “Establishment of a Commission to Deal with the Problems Raised by the Discovery of Atomic Energy.”\
DISEC is perhaps one of the most important General Assembly committees, and it is the only one other than the Main Committee of the General Assembly entitled to verbatim records coverage. \
\
\
As DISEC members, delegates will debate and discuss about a wide variety of arms- and security-related issues, and pass resolutions that would help to make the world a safer and more peaceful place.\
'

},
{
    'image':'unhrc.png',
    'title':'Human Rights Council',
    'content':'“Human rights are not a privilege granted by the few, they are a liberty entitled to all, and human rights, by definition, include the rights of all humans, those in the dawn of life, the dusk of life, or the shadows of life.”\
Kay Granger\
\
\
The Human Rights Council is an inter-governmental body within the United Nations system responsible for strengthening the promotion and protection of human rights around the globe and for addressing situations of human rights violations and make recommendations on them. It has the ability to discuss all thematic human rights issues and situations that require its attention throughout the year. The Council is made up of 47 United Nations Member States which are elected by the UN General Assembly. \
 \
The UN HRC deals with topics that revolve around Human Rights violations - such as discrimination against minority groups, abuse of human rights, and human rights during conflict. It abides by the many different human rights conventions, and works with special rapporteurs and working groups to investigate human rights violations, and to keep states in check. \
'
},
{
    'image':'unodc.png',
    'title':'Office On Drugs and Crime',
    'content':'\
“Working together to take action against drugs, crime, corruption and terrorism, we can increase security and improve the lives of individuals, families and communities all over the world."\
UNODC Executive DIrector, Yury Fedotov\
\
\
A unique and specialised committee, the UNODC deals with the global fight against illicit drugs and international crime. It combats certain specialised problems faced by the international community, such as: organised crime and trafficking, crime prevention, crime prevention and criminal justice reform, drug abuse prevention and terrorism prevention.\
\
\
Due to the broad scope of its work, the UNODC operates through all the regions of the world through an extensive network of field offices. It works via three main channels - field-based cooperation projects to help states combat the above problems, research and analytical work that provides a solid theoretical base for policy decisions on the above topics, and assisting states in the ratification and implementation of international treaties.\
\
\
As UNODC members, delegates will confront problems specific to drugs and crime prevention, looking at these topics both from the national and global point of view, and be challenged to devise policies and solutions that would be relevant and implementable in today’s world.\
'
},
{
    'image':'aippm.png',
    'title':'All India Political Parties Meet',
    'content':'“Unity in diversity is India\'s strength. There is simplicity in every Indian. There is unity in every corener of India. This is our strength”\
-Narendra Modi, Prime Minister, India\
\
\
AIPPM is a council consisting of political representatives of various parties, working together to discuss issues of national importance. \
\
\
Members of this council must be aware that many of these issues are complex, and should keep in mind that there are more than a billion people in India - of diverse religions, castes, creeds and try to represent views inclusively. \
'
}
]
var applications = [
{
    name:"Delegate",
    link:"https://iiithmun.typeform.com/to/T4EDSF?typeform-embed=embed-widget"
},
{
    name:"International Press",
    link:"https://iiithmun.typeform.com/to/cd67cV?typeform-embed=embed-widget"
},
{
    name:"Delegation",
    link:"https://iiithmun.typeform.com/to/WjHJLU?typeform-embed=embed-widget"
}
]
var schedule = [
{
   'day':"27th January",
   'events':[
        "Registration",
        "Opening ceremony",
        "Orientation",
        "Lunch",
        "1st committee session",
        "Tea/Snacks break",
        "1st Committee session continues",
        "Dinner",
        "Social night (Felicity night), if any",
        "Buses depart to delegate accommodation "
    ]
},
{
    'day':"28th January",
    'events':[
        "Breakfast3",
        "2nd Committee session",
        "Lunch",
        "3rd committee session",
        "Tea/Snacks break",
        "Break",
        "Dinner",
        "Social night",
    ]
},
{
    'day':'29th January',
    'events':[
        "Breakfast",
        "4th committee session",
        "Lunch",
        "5th committee session",
        "Closing ceremony"
    ]
}
];
contact = [
{
    'name': 'Saumya Prabodh',
    'position':'USG Marketing',
    'phone': '09618207958',
    'email': 'srivastava.saumya2811@gmail.com'
},
{
    'name': 'Aditya Bharti',
    'position': 'USG Administration',
    'phone': '9618153254',
    'email': 'adibhar97@gmail.com'
}];
sponsors = [
{
    'image': "cid.jpg"
},{
    'image': "iiit-new.png"
},{
    'image': "oyo.png"
}]
<|endoftext|>


<commit_before>/*global angular */
/*
 jQuery UI Datepicker plugin wrapper

 @note If ≤ IE8 make sure you have a polyfill for Date.toISOString()
 @param [ui-date] {object} Options to pass to $.fn.datepicker() merged onto uiDateConfig
 */

angular.module('ui.date', [])

.constant('uiDateConfig', {})

.directive('uiDate', ['uiDateConfig', 'uiDateConverter', function (uiDateConfig, uiDateConverter) {
  'use strict';
  var options;
  options = {};
  angular.extend(options, uiDateConfig);
  return {
    require:'?ngModel',
    link:function (scope, element, attrs, controller) {
      var getOptions = function () {
        return angular.extend({}, uiDateConfig, scope.$eval(attrs.uiDate));
      };
      var initDateWidget = function () {
        var showing = false;
        var opts = getOptions();

        function setVal() {
          var keys = ['Hours', 'Minutes', 'Seconds', 'Milliseconds'],
              isDate = angular.isDate(controller.$modelValue),
              preserve = {};

          if(isDate && controller.$modelValue.toDateString() === element.datepicker('getDate').toDateString()) {
            return;
          }

          if (isDate) {
            angular.forEach(keys, function(key) {
              preserve[key] = controller.$modelValue['get' + key]();
            });
          }
          controller.$setViewValue(element.datepicker('getDate'));

          if (isDate) {
            angular.forEach(keys, function(key) {
               controller.$viewValue['set' + key](preserve[key]);
            });
          }
        }

        // If we have a controller (i.e. ngModelController) then wire it up
        if (controller) {

          // Set the view value in a $apply block when users selects
          // (calling directive user's function too if provided)
          var _onSelect = opts.onSelect || angular.noop;
          opts.onSelect = function (value, picker) {
            scope.$apply(function() {
              showing = true;
              setVal();
              _onSelect(value, picker);
              element.blur();
            });
          };

          var _beforeShow = opts.beforeShow || angular.noop;
          opts.beforeShow = function(input, picker) {
            showing = true;
            _beforeShow(input, picker);
          };

          var _onClose = opts.onClose || angular.noop;
          opts.onClose = function(value, picker) {
            showing = false;
            _onClose(value, picker);
          };
          element.off('blur.datepicker').on('blur.datepicker', function() {
            if ( !showing ) {
              scope.$apply(function() {
                element.datepicker('setDate', element.datepicker('getDate'));
                setVal();
              });
            }
          });

          // Update the date picker when the model changes
          controller.$render = function () {
            var date = controller.$modelValue;
            if ( angular.isDefined(date) && date !== null && !angular.isDate(date) ) {
                if ( angular.isString(controller.$modelValue) ) {
                    date = uiDateConverter.stringToDate(attrs.uiDateFormat, controller.$modelValue);
                } else {
                    throw new Error('ng-Model value must be a Date, or a String object with a date formatter - currently it is a ' + typeof date + ' - use ui-date-format to convert it from a string');
                }
            }
            element.datepicker('setDate', date);
          };
        }
        // Check if the element already has a datepicker.
        if (element.data('datepicker')) {
            // Updates the datepicker options
            element.datepicker('option', opts);
            element.datepicker('refresh');
        } else {
            // Creates the new datepicker widget
            element.datepicker(opts);

            //Cleanup on destroy, prevent memory leaking
            element.on('$destroy', function () {
               element.datepicker('destroy');
            });
        }

        if ( controller ) {
          // Force a render to override whatever is in the input text box
          controller.$render();
        }
      };
      // Watch for changes to the directives options
      scope.$watch(getOptions, initDateWidget, true);
    }
  };
}
])
.factory('uiDateConverter', ['uiDateFormatConfig', function(uiDateFormatConfig){

    function dateToString(dateFormat, value){
        dateFormat = dateFormat || uiDateFormatConfig;
        if (value) {
            if (dateFormat) {
                return jQuery.datepicker.formatDate(dateFormat, value);
            }

            if (value.toISOString) {
                return value.toISOString();
            }
        }
        return null;
    }

    function stringToDate(dateFormat, value) {
        dateFormat = dateFormat || uiDateFormatConfig;
        if ( angular.isString(value) ) {
            if (dateFormat) {
                return jQuery.datepicker.parseDate(dateFormat, value);
            }

            var isoDate = new Date(value);
            return isNaN(isoDate.getTime()) ? null : isoDate;
        }
        return null;
    }

    return {
        stringToDate: stringToDate,
        dateToString: dateToString
    };

}])
.constant('uiDateFormatConfig', '')
.directive('uiDateFormat', ['uiDateConverter', function(uiDateConverter) {
  var directive = {
    require:'ngModel',
    link: function(scope, element, attrs, modelCtrl) {
        var dateFormat = attrs.uiDateFormat;

        // Use the datepicker with the attribute value as the dateFormat string to convert to and from a string
        modelCtrl.$formatters.unshift(function(value) {
            return uiDateConverter.stringToDate(dateFormat, value);
        });

        modelCtrl.$parsers.push(function(value){
            return uiDateConverter.dateToString(dateFormat, value);
        });

    }
  };

  return directive;
}]);
<commit_msg>Hide datepicker on route change<commit_after>/*global angular */
/*
 jQuery UI Datepicker plugin wrapper

 @note If ≤ IE8 make sure you have a polyfill for Date.toISOString()
 @param [ui-date] {object} Options to pass to $.fn.datepicker() merged onto uiDateConfig
 */

angular.module('ui.date', [])

.constant('uiDateConfig', {})

.directive('uiDate', ['uiDateConfig', 'uiDateConverter', function (uiDateConfig, uiDateConverter) {
  'use strict';
  var options;
  options = {};
  angular.extend(options, uiDateConfig);
  return {
    require:'?ngModel',
    link:function (scope, element, attrs, controller) {
      var getOptions = function () {
        return angular.extend({}, uiDateConfig, scope.$eval(attrs.uiDate));
      };
      var initDateWidget = function () {
        var showing = false;
        var opts = getOptions();

        function setVal() {
          var keys = ['Hours', 'Minutes', 'Seconds', 'Milliseconds'],
              isDate = angular.isDate(controller.$modelValue),
              preserve = {};

          if(isDate && controller.$modelValue.toDateString() === element.datepicker('getDate').toDateString()) {
            return;
          }

          if (isDate) {
            angular.forEach(keys, function(key) {
              preserve[key] = controller.$modelValue['get' + key]();
            });
          }
          controller.$setViewValue(element.datepicker('getDate'));

          if (isDate) {
            angular.forEach(keys, function(key) {
               controller.$viewValue['set' + key](preserve[key]);
            });
          }
        }

        // If we have a controller (i.e. ngModelController) then wire it up
        if (controller) {

          // Set the view value in a $apply block when users selects
          // (calling directive user's function too if provided)
          var _onSelect = opts.onSelect || angular.noop;
          opts.onSelect = function (value, picker) {
            scope.$apply(function() {
              showing = true;
              setVal();
              _onSelect(value, picker);
              element.blur();
            });
          };

          var _beforeShow = opts.beforeShow || angular.noop;
          opts.beforeShow = function(input, picker) {
            showing = true;
            _beforeShow(input, picker);
          };

          var _onClose = opts.onClose || angular.noop;
          opts.onClose = function(value, picker) {
            showing = false;
            _onClose(value, picker);
          };
          element.off('blur.datepicker').on('blur.datepicker', function() {
            if ( !showing ) {
              scope.$apply(function() {
                element.datepicker('setDate', element.datepicker('getDate'));
                setVal();
              });
            }
          });

          // Update the date picker when the model changes
          controller.$render = function () {
            var date = controller.$modelValue;
            if ( angular.isDefined(date) && date !== null && !angular.isDate(date) ) {
                if ( angular.isString(controller.$modelValue) ) {
                    date = uiDateConverter.stringToDate(attrs.uiDateFormat, controller.$modelValue);
                } else {
                    throw new Error('ng-Model value must be a Date, or a String object with a date formatter - currently it is a ' + typeof date + ' - use ui-date-format to convert it from a string');
                }
            }
            element.datepicker('setDate', date);
          };
        }
        // Check if the element already has a datepicker.
        if (element.data('datepicker')) {
            // Updates the datepicker options
            element.datepicker('option', opts);
            element.datepicker('refresh');
        } else {
            // Creates the new datepicker widget
            element.datepicker(opts);

            //Cleanup on destroy, prevent memory leaking
            element.on('$destroy', function () {
               element.datepicker('hide');
               element.datepicker('destroy');
            });
        }

        if ( controller ) {
          // Force a render to override whatever is in the input text box
          controller.$render();
        }
      };
      // Watch for changes to the directives options
      scope.$watch(getOptions, initDateWidget, true);
    }
  };
}
])
.factory('uiDateConverter', ['uiDateFormatConfig', function(uiDateFormatConfig){

    function dateToString(dateFormat, value){
        dateFormat = dateFormat || uiDateFormatConfig;
        if (value) {
            if (dateFormat) {
                return jQuery.datepicker.formatDate(dateFormat, value);
            }

            if (value.toISOString) {
                return value.toISOString();
            }
        }
        return null;
    }

    function stringToDate(dateFormat, value) {
        dateFormat = dateFormat || uiDateFormatConfig;
        if ( angular.isString(value) ) {
            if (dateFormat) {
                return jQuery.datepicker.parseDate(dateFormat, value);
            }

            var isoDate = new Date(value);
            return isNaN(isoDate.getTime()) ? null : isoDate;
        }
        return null;
    }

    return {
        stringToDate: stringToDate,
        dateToString: dateToString
    };

}])
.constant('uiDateFormatConfig', '')
.directive('uiDateFormat', ['uiDateConverter', function(uiDateConverter) {
  var directive = {
    require:'ngModel',
    link: function(scope, element, attrs, modelCtrl) {
        var dateFormat = attrs.uiDateFormat;

        // Use the datepicker with the attribute value as the dateFormat string to convert to and from a string
        modelCtrl.$formatters.unshift(function(value) {
            return uiDateConverter.stringToDate(dateFormat, value);
        });

        modelCtrl.$parsers.push(function(value){
            return uiDateConverter.dateToString(dateFormat, value);
        });

    }
  };

  return directive;
}]);
<|endoftext|>


<commit_before>#!/usr/bin/env node
/*global ls:true, target:true, find: true, echo: true, cat:true, exit:true, exec: true */

"use strict";

require("shelljs/make");
var cli = require("cli");

var TESTS = [
	"tests/stable/unit/",
	"tests/stable/regression/",
	"tests/next/unit/"
];

var OPTIONS = JSON.parse(cat("./jshint.json"));

target.all = function () {
	target.lint();
	target.test();
	target.build();
};

target.lint = function () {
	var jshint = require("jshint").JSHINT;
	var files = find("src").filter(function (file) {
		return file.match(/\.js$/);
	}).concat(ls(__dirname + "/*.js"));

	TESTS.forEach(function (dir) {
		ls(dir + "*.js").forEach(function (file) {
			files.push(file);
		});
	});

	echo("Linting files...", "\n");

	var failures = {};
	files.forEach(function (file) {
		var passed = jshint(cat(file), OPTIONS);
		process.stdout.write(passed ? "." : "F");

		if (!passed) {
			failures[file] = jshint.data();
		}
	});

	echo("\n");

	if (Object.keys(failures).length === 0) {
		cli.ok("All files passed.");
		return;
	}

	var outputError = function (err) {
		if (!err) {
			return;
		}

		var line = "[L" + err.line + "]";
		while (line.length < 10) {
			line += " ";
		}

		echo(line, err.reason);
		echo("\n");
	};

	for (var key in failures) {
		cli.error(key);
		failures[key].errors.forEach(outputError);
	}

	exit(1);
};

target.test = function () {
	var nodeunit = require("nodeunit").reporters.minimal;
	var files = [];

	TESTS.forEach(function (dir) {
		ls(dir + "*.js").forEach(function (file) {
			files.push(file);
		});
	});

	echo("Running tests...", "\n");
	nodeunit.run(files);
};

target.build = function () {
	echo("Building platform wrappers:");

	var rhino = cat("./src/stable/jshint.js", "./src/platforms/rhino.js");
	rhino = "#!/usr/bin/env rhino\n\n" + rhino;
	rhino.to("./dist/jshint-rhino.js");
	exec("chmod +x dist/jshint-rhino.js");
	cli.ok("Rhino");

	cat("./src/platforms/wsh.js").to("./dist/jshint-wsh.js");
	cli.ok("Windows Script Host");

	cat("./src/platforms/jsc.sh").to("./dist/jshint-jsc.sh");
	cat("./src/platforms/jsc.js").to("./dist/jshint-jsc.js");
	exec("chmod +x dist/jshint-jsc.sh");
	cli.ok("JavaScript Core");
};
<commit_msg>Run CLI tests on ./make.js test<commit_after>#!/usr/bin/env node
/*global ls:true, target:true, find: true, echo: true, cat:true, exit:true, exec: true */

"use strict";

require("shelljs/make");
var cli = require("cli");

var TESTS = [
	"tests/",
	"tests/stable/unit/",
	"tests/stable/regression/",
	"tests/next/unit/",
];

var OPTIONS = JSON.parse(cat("./jshint.json"));

target.all = function () {
	target.lint();
	target.test();
	target.build();
};

target.lint = function () {
	var jshint = require("jshint").JSHINT;
	var files = find("src").filter(function (file) {
		return file.match(/\.js$/);
	}).concat(ls(__dirname + "/*.js"));

	TESTS.forEach(function (dir) {
		ls(dir + "*.js").forEach(function (file) {
			files.push(file);
		});
	});

	echo("Linting files...", "\n");

	var failures = {};
	files.forEach(function (file) {
		var passed = jshint(cat(file), OPTIONS);
		process.stdout.write(passed ? "." : "F");

		if (!passed) {
			failures[file] = jshint.data();
		}
	});

	echo("\n");

	if (Object.keys(failures).length === 0) {
		cli.ok("All files passed.");
		return;
	}

	var outputError = function (err) {
		if (!err) {
			return;
		}

		var line = "[L" + err.line + "]";
		while (line.length < 10) {
			line += " ";
		}

		echo(line, err.reason);
		echo("\n");
	};

	for (var key in failures) {
		cli.error(key);
		failures[key].errors.forEach(outputError);
	}

	exit(1);
};

target.test = function () {
	var nodeunit = require("nodeunit").reporters.minimal;
	var files = [];

	TESTS.forEach(function (dir) {
		ls(dir + "*.js").forEach(function (file) {
			files.push(file);
		});
	});

	echo("Running tests...", "\n");
	nodeunit.run(files);
};

target.build = function () {
	echo("Building platform wrappers:");

	var rhino = cat("./src/stable/jshint.js", "./src/platforms/rhino.js");
	rhino = "#!/usr/bin/env rhino\n\n" + rhino;
	rhino.to("./dist/jshint-rhino.js");
	exec("chmod +x dist/jshint-rhino.js");
	cli.ok("Rhino");

	cat("./src/platforms/wsh.js").to("./dist/jshint-wsh.js");
	cli.ok("Windows Script Host");

	cat("./src/platforms/jsc.sh").to("./dist/jshint-jsc.sh");
	cat("./src/platforms/jsc.js").to("./dist/jshint-jsc.js");
	exec("chmod +x dist/jshint-jsc.sh");
	cli.ok("JavaScript Core");
};
<|endoftext|>


<commit_before>// support for presentations
(function Demo() {
  let lines = [];
  let index = -1;
  let inp; // inp:an <input type=file> used to open the file chooser dialog
  function move(d) {
    if (index + d >= 0 && index + d < lines.length) {
      index += d;
      D.ide.wins[0].loadLine(lines[index]);
    }
  }
  // key display mode:
  let $p; // dom element for the pending key or null if key display mode is off
  const meta = new Set(['Shift', 'Alt', 'Ctrl', 'Cmd', 'Meta', 'Win']);
  function keyInfo(e) { // returns a pair of the key name and an "is complete?" flag
    const be = e.browserEvent;
    const kbs = D.wins[0].me._standaloneKeybindingService;
    const mk = kbs.resolveKeyboardEvent(e);
    const isMeta = meta.has(monaco.KeyCode[e.keyCode]);
    const s = !isMeta || be.altKey || be.shiftKey || be.ctrlKey || be.metaKey ? mk.getLabel() : '';
    return [s, !isMeta]; // s:key name, c:is the key combination complete?
  }
  function loadDemoScript(f) { // f:path to file, ignored if empty
    f && nodeRequire('fs').readFile(f, 'utf8', (err, s) => {
      if (err) { $.err('Cannot load demo file'); return; }
      index = -1;
      lines = s.replace(/^[\ufeff\ufffe]/, '').split(/\r?\n/)
        .filter(x => !/^\s*(?:$|⍝⍝)/.test(x))
        .map(x => `      ${x}`);
    });
  }
  D.el && loadDemoScript(process.env.RIDE_DEMO_SCRIPT);
  const handlers = [];
  $.extend(D.commands, {
    DMN() { move(1); }, // next line
    DMP() { move(-1); }, // prev line
    DMR() { // load demo script
      if (!D.el || D.prf.floating()) return;
      if (!inp) {
        inp = document.createElement('input');
        inp.type = 'file';
        inp.hidden = 1;
        document.body.appendChild(inp);
        inp.onchange = () => { loadDemoScript(inp.files[0].path); };
      }
      inp.value = '';
      inp.click();
    },
    DMK() { // toggle key display mode
      if ($p) {
        // $(document).off('.demo');
        handlers.forEach(h => h.dispose()); handlers.length = 0;
        $('#demo-keys').remove();
        $p = null;
        return;
      }
      $('body').append($('
').append($p = $('').hide()));
      const { me } = D.wins[0];
      handlers.push(me.onKeyDown((e) => {
        const s = keyInfo(e)[0]; $p.text(s).toggle(!!s);
      }));

      // $(document)
      // .on('keydown.demo', (e) => { const s = keyInfo(e)[0]; $p.text(s).toggle(!!s); })
      // .on('keyup.demo', (e) => {
      handlers.push(me.onKeyUp((e) => {
        const h = keyInfo(e);
        const [s, c] = h;
        if (c) {
          $p.hide();
          const $k = $('').text(s).insertBefore($p);
          setTimeout(() => { $k.fadeOut(1000); }, 2000);
        } else {
          $p.text(s).toggle(!!s);
        }
      }));
    },
  });
}());
<commit_msg>fix DMR now working with floating wins<commit_after>// support for presentations
(function Demo() {
  let lines = [];
  let index = -1;
  let inp; // inp:an <input type=file> used to open the file chooser dialog
  function move(d) {
    if (index + d >= 0 && index + d < lines.length) {
      index += d;
      D.ide.wins[0].loadLine(lines[index]);
    }
  }
  // key display mode:
  let $p; // dom element for the pending key or null if key display mode is off
  const meta = new Set(['Shift', 'Alt', 'Ctrl', 'Cmd', 'Meta', 'Win']);
  function keyInfo(e) { // returns a pair of the key name and an "is complete?" flag
    const be = e.browserEvent;
    const kbs = D.wins[0].me._standaloneKeybindingService;
    const mk = kbs.resolveKeyboardEvent(e);
    const isMeta = meta.has(monaco.KeyCode[e.keyCode]);
    const s = !isMeta || be.altKey || be.shiftKey || be.ctrlKey || be.metaKey ? mk.getLabel() : '';
    return [s, !isMeta]; // s:key name, c:is the key combination complete?
  }
  function loadDemoScript(f) { // f:path to file, ignored if empty
    f && nodeRequire('fs').readFile(f, 'utf8', (err, s) => {
      if (err) { $.err('Cannot load demo file'); return; }
      index = -1;
      lines = s.replace(/^[\ufeff\ufffe]/, '').split(/\r?\n/)
        .filter(x => !/^\s*(?:$|⍝⍝)/.test(x))
        .map(x => `      ${x}`);
    });
  }
  D.el && loadDemoScript(process.env.RIDE_DEMO_SCRIPT);
  const handlers = [];
  $.extend(D.commands, {
    DMN() { move(1); }, // next line
    DMP() { move(-1); }, // prev line
    DMR() { // load demo script
      if (!D.el || D.ide.floating) return;
      if (!inp) {
        inp = document.createElement('input');
        inp.type = 'file';
        inp.hidden = 1;
        document.body.appendChild(inp);
        inp.onchange = () => { loadDemoScript(inp.files[0].path); };
      }
      inp.value = '';
      inp.click();
    },
    DMK() { // toggle key display mode
      if ($p) {
        // $(document).off('.demo');
        handlers.forEach(h => h.dispose()); handlers.length = 0;
        $('#demo-keys').remove();
        $p = null;
        return;
      }
      $('body').append($('
').append($p = $('').hide()));
      const { me } = D.wins[0];
      handlers.push(me.onKeyDown((e) => {
        const s = keyInfo(e)[0]; $p.text(s).toggle(!!s);
      }));

      // $(document)
      // .on('keydown.demo', (e) => { const s = keyInfo(e)[0]; $p.text(s).toggle(!!s); })
      // .on('keyup.demo', (e) => {
      handlers.push(me.onKeyUp((e) => {
        const h = keyInfo(e);
        const [s, c] = h;
        if (c) {
          $p.hide();
          const $k = $('').text(s).insertBefore($p);
          setTimeout(() => { $k.fadeOut(1000); }, 2000);
        } else {
          $p.text(s).toggle(!!s);
        }
      }));
    },
  });
}());
<|endoftext|>


<commit_before>import {Pos, containsMark, MarkType} from "../model"

import {TransformResult, Transform} from "./transform"
import {defineStep, Step} from "./step"
import {copyInline, copyStructure} from "./tree"

defineStep("addMark", {
  apply(doc, step) {
    return new TransformResult(copyStructure(doc, step.from, step.to, (node, from, to) => {
      if (!node.type.canContainMark(step.param)) return node
      return copyInline(node, from, to, node => {
        return node.mark(step.param.addToSet(node.marks))
      })
    }))
  },
  invert(step, _oldDoc, map) {
    return new Step("removeMark", step.from, map.map(step.to).pos, null, step.param)
  },
  paramToJSON(param) {
    return param.toJSON()
  },
  paramFromJSON(schema, json) {
    return schema.markFromJSON(json)
  }
})

Transform.prototype.addMark = function(from, to, st) {
  let removed = [], added = [], removing = null, adding = null
  this.doc.inlineNodesBetween(from, to, ({marks}, path, start, end, parent) => {
    if (st.isInSet(marks) || !parent.type.canContainMark(st.type)) {
      adding = removing = null
    } else {
      let rm = containsMark(marks, st.type)
      if (rm) {
        if (removing && removing.param.eq(rm)) {
          removing.to = new Pos(path, end)
        } else {
          removing = new Step("removeMark", new Pos(path, start), new Pos(path, end), null, rm)
          removed.push(removing)
        }
      } else if (removing) {
        removing = null
      }
      if (adding) {
        adding.to = new Pos(path, end)
      } else {
        adding = new Step("addMark", new Pos(path, start), new Pos(path, end), null, st)
        added.push(adding)
      }
    }
  })
  removed.forEach(s => this.step(s))
  added.forEach(s => this.step(s))
  return this
}

defineStep("removeMark", {
  apply(doc, step) {
    return new TransformResult(copyStructure(doc, step.from, step.to, (node, from, to) => {
      return copyInline(node, from, to, node => {
        return node.mark(step.param.removeFromSet(node.marks))
      })
    }))
  },
  invert(step, _oldDoc, map) {
    return new Step("addMark", step.from, map.map(step.to).pos, null, step.param)
  },
  paramToJSON(param) {
    return param.toJSON()
  },
  paramFromJSON(schema, json) {
    return schema.markFromJSON(json)
  }
})

Transform.prototype.removeMark = function(from, to, st = null) {
  let matched = [], step = 0
  this.doc.inlineNodesBetween(from, to, ({marks}, path, start, end) => {
    step++
    let toRemove = null
    if (st instanceof MarkType) {
      let found = containsMark(marks, st)
      if (found) toRemove = [found]
    } else if (st) {
      if (st.isInSet(marks)) toRemove = [st]
    } else {
      toRemove = marks
    }
    if (toRemove && toRemove.length) {
      path = path.slice()
      for (let i = 0; i < toRemove.length; i++) {
        let rm = toRemove[i], found
        for (let j = 0; j < matched.length; j++) {
          let m = matched[j]
          if (m.step == step - 1 && rm.eq(matched[j].style)) found = m
        }
        if (found) {
          found.to = new Pos(path, end)
          found.step = step
        } else {
          matched.push({style: rm, from: new Pos(path, start), to: new Pos(path, end), step: step})
        }
      }
    }
  })
  matched.forEach(m => this.step("removeMark", m.from, m.to, null, m.style))
  return this
}

Transform.prototype.clearMarkup = function(from, to, newParent) {
  let delSteps = [] // Must be accumulated and applied in inverse order
  this.doc.inlineNodesBetween(from, to, ({marks, type}, path, start, end) => {
    if (newParent ? !newParent.canContainType(type) : type != this.doc.type.schema.nodeTypes.text) { // FIXME text type accessor
      path = path.slice()
      let from = new Pos(path, start)
      delSteps.push(new Step("replace", from, new Pos(path, end), from))
      return
    }
    for (let i = 0; i < marks.length; i++) {
      let mark = marks[i]
      if (!newParent || !newParent.canContainMark(mark.type)) {
        path = path.slice()
        this.step("removeMark", new Pos(path, start), new Pos(path, end), null, mark)
      }
    }
  })
  for (let i = delSteps.length - 1; i >= 0; i--) this.step(delSteps[i])
  return this
}
<commit_msg>Take care of some FIXMEs<commit_after>import {Pos, containsMark, MarkType} from "../model"

import {TransformResult, Transform} from "./transform"
import {defineStep, Step} from "./step"
import {copyInline, copyStructure} from "./tree"

defineStep("addMark", {
  apply(doc, step) {
    return new TransformResult(copyStructure(doc, step.from, step.to, (node, from, to) => {
      if (!node.type.canContainMark(step.param)) return node
      return copyInline(node, from, to, node => {
        return node.mark(step.param.addToSet(node.marks))
      })
    }))
  },
  invert(step, _oldDoc, map) {
    return new Step("removeMark", step.from, map.map(step.to).pos, null, step.param)
  },
  paramToJSON(param) {
    return param.toJSON()
  },
  paramFromJSON(schema, json) {
    return schema.markFromJSON(json)
  }
})

Transform.prototype.addMark = function(from, to, st) {
  let removed = [], added = [], removing = null, adding = null
  this.doc.inlineNodesBetween(from, to, ({marks}, path, start, end, parent) => {
    if (st.isInSet(marks) || !parent.type.canContainMark(st.type)) {
      adding = removing = null
    } else {
      let rm = containsMark(marks, st.type)
      if (rm) {
        if (removing && removing.param.eq(rm)) {
          removing.to = new Pos(path, end)
        } else {
          removing = new Step("removeMark", new Pos(path, start), new Pos(path, end), null, rm)
          removed.push(removing)
        }
      } else if (removing) {
        removing = null
      }
      if (adding) {
        adding.to = new Pos(path, end)
      } else {
        adding = new Step("addMark", new Pos(path, start), new Pos(path, end), null, st)
        added.push(adding)
      }
    }
  })
  removed.forEach(s => this.step(s))
  added.forEach(s => this.step(s))
  return this
}

defineStep("removeMark", {
  apply(doc, step) {
    return new TransformResult(copyStructure(doc, step.from, step.to, (node, from, to) => {
      return copyInline(node, from, to, node => {
        return node.mark(step.param.removeFromSet(node.marks))
      })
    }))
  },
  invert(step, _oldDoc, map) {
    return new Step("addMark", step.from, map.map(step.to).pos, null, step.param)
  },
  paramToJSON(param) {
    return param.toJSON()
  },
  paramFromJSON(schema, json) {
    return schema.markFromJSON(json)
  }
})

Transform.prototype.removeMark = function(from, to, st = null) {
  let matched = [], step = 0
  this.doc.inlineNodesBetween(from, to, ({marks}, path, start, end) => {
    step++
    let toRemove = null
    if (st instanceof MarkType) {
      let found = containsMark(marks, st)
      if (found) toRemove = [found]
    } else if (st) {
      if (st.isInSet(marks)) toRemove = [st]
    } else {
      toRemove = marks
    }
    if (toRemove && toRemove.length) {
      path = path.slice()
      for (let i = 0; i < toRemove.length; i++) {
        let rm = toRemove[i], found
        for (let j = 0; j < matched.length; j++) {
          let m = matched[j]
          if (m.step == step - 1 && rm.eq(matched[j].style)) found = m
        }
        if (found) {
          found.to = new Pos(path, end)
          found.step = step
        } else {
          matched.push({style: rm, from: new Pos(path, start), to: new Pos(path, end), step: step})
        }
      }
    }
  })
  matched.forEach(m => this.step("removeMark", m.from, m.to, null, m.style))
  return this
}

Transform.prototype.clearMarkup = function(from, to, newParent) {
  let delSteps = [] // Must be accumulated and applied in inverse order
  this.doc.inlineNodesBetween(from, to, ({marks, type}, path, start, end) => {
    if (newParent ? !newParent.canContainType(type) : !type.isText) {
      path = path.slice()
      let from = new Pos(path, start)
      delSteps.push(new Step("replace", from, new Pos(path, end), from))
      return
    }
    for (let i = 0; i < marks.length; i++) {
      let mark = marks[i]
      if (!newParent || !newParent.canContainMark(mark.type)) {
        path = path.slice()
        this.step("removeMark", new Pos(path, start), new Pos(path, end), null, mark)
      }
    }
  })
  for (let i = delSteps.length - 1; i >= 0; i--) this.step(delSteps[i])
  return this
}
<|endoftext|>


<commit_before>var FILE_PATH = "/Users/pete/iMacros/Macros/jcrawler/{0}";

// Source: http://forum.iopus.com/viewtopic.php?f=11&t=5267
// Note: this may not work depending on Java version(?)
write_file = function(path, data) {
  iimDisplay("Writing file:"+path);
   try {
      var out = new java.io.BufferedWriter(new java.io.OutputStreamWriter(new java.io.FileOutputStream(new java.io.File(path)), "UTF8"));
      out.write(data);
      out.close();
      out=null;
   }
   catch(e) { //catch and report any errors
      alert(""+e);
   }
};

// Source: http://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format/4256130#4256130
String.prototype.format = function() {
  var formatted = this;
  for (var i = 0; i < arguments.length; i++) {
    var regexp = new RegExp('\\{'+i+'\\}', 'gi');
    formatted = formatted.replace(regexp, arguments[i]);
  }
  return formatted;
};

// Source: http://stackoverflow.com/questions/646628/javascript-startswith
if (typeof String.prototype.startsWith != 'function') {
  String.prototype.startsWith = function (str){
    return this.slice(0, str.length) == str;
  };
}

// Source: http://stackoverflow.com/questions/280634/endswith-in-javascript
if (typeof String.prototype.endsWith != 'function') {
  String.prototype.endsWith = function(suffix) {
    return this.indexOf(suffix, this.length - suffix.length) !== -1;
  };
}

// inclusive random range
// Source: http://www.admixweb.com/2010/08/24/javascript-tip-get-a-random-number-between-two-integers/
random_range = function(from, to){
  var val = Math.floor(Math.random() * (to - from + 1) + from);
  if(val > to) { // in case Math.random() can produce 1.0 (does it?)
    val = to;
  }
  return val;
};

// Source: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
function date_string(d){
 function pad(n){return n<10 ? '0'+n : n}
 return d.getUTCFullYear()+''
      + pad(d.getUTCMonth()+1)+''
      + pad(d.getUTCDate())+''
      + pad(d.getUTCHours())+''
      + pad(d.getUTCMinutes())+''
      + pad(d.getUTCSeconds())}

srswor = function(list, n, ignore) {
  if(!ignore) ignore = [];
  for(var i=0; i<ignore.length; i++) {
    var idx = list.indexOf(ignore[i]);
    if(idx >= 0) list.splice(idx, 1);
  }
  if(list.length < n) return list;
  var new_list = [];
  while(new_list.length < n && list.length > 0) {
    var rand_idx = random_range(0, list.length - 1);
    new_list.push(list.splice(rand_idx, 1));
  }
  return new_list;
};

run = function(code, n) {
  var retcode = iimPlay("CODE: "+code);
  if(retcode != 1) {
    alert("BAD CODE:\n"+code+"\n\nretcode:"+retcode);
    return;
  }
  if(n) {
    var extract = iimGetLastExtract(n);
    if(extract == "#EANF#") return false; // "Extraction Anchor Not Found"
    return extract;
  }
};

sleep = function(seconds) { run("WAIT SECONDS="+seconds); };
visit_url = function(url) { run("URL GOTO="+url); };

save_profile = function(link, profile) {
  var raw_profile = run("TAG POS=1 TYPE=DIV ATTR=CLASS:prof1-lay EXTRACT=HTM", 1);
  var filename = date_string(new Date())+"_"+profile+".data";
  var path = FILE_PATH.format("data/mbga/person/"+filename);
  write_file(path, raw_profile);
};

save_group = function(link, group) {
  var raw_group = run("TAG POS=1 TYPE=UL ATTR=CLASS:blk-lay EXTRACT=HTM", 1);
  var filename = date_string(new Date())+"_"+group+".data";
  var path = FILE_PATH.format("data/mbga/group/"+filename);
  write_file(path, raw_group);
};

main = function() {
  //save_profile("http://yahoo-mbga.jp/10086","10086");
  save_group("http://yahoo-mbga.jp/group/31966079", "31966079");
};

main();<commit_msg>reorganize mbga crawler + main<commit_after>var FILE_PATH = "/Users/pete/iMacros/Macros/jcrawler/{0}";

// Source: http://forum.iopus.com/viewtopic.php?f=11&t=5267
// Note: this may not work depending on Java version(?)
write_file = function(path, data) {
  iimDisplay("Writing file:"+path);
   try {
      var out = new java.io.BufferedWriter(new java.io.OutputStreamWriter(new java.io.FileOutputStream(new java.io.File(path)), "UTF8"));
      out.write(data);
      out.close();
      out=null;
   }
   catch(e) { //catch and report any errors
      alert(""+e);
   }
};

// Source: http://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format/4256130#4256130
String.prototype.format = function() {
  var formatted = this;
  for (var i = 0; i < arguments.length; i++) {
    var regexp = new RegExp('\\{'+i+'\\}', 'gi');
    formatted = formatted.replace(regexp, arguments[i]);
  }
  return formatted;
};

// Source: http://stackoverflow.com/questions/646628/javascript-startswith
if (typeof String.prototype.startsWith != 'function') {
  String.prototype.startsWith = function (str){
    return this.slice(0, str.length) == str;
  };
}

// Source: http://stackoverflow.com/questions/280634/endswith-in-javascript
if (typeof String.prototype.endsWith != 'function') {
  String.prototype.endsWith = function(suffix) {
    return this.indexOf(suffix, this.length - suffix.length) !== -1;
  };
}

// inclusive random range
// Source: http://www.admixweb.com/2010/08/24/javascript-tip-get-a-random-number-between-two-integers/
random_range = function(from, to){
  var val = Math.floor(Math.random() * (to - from + 1) + from);
  if(val > to) { // in case Math.random() can produce 1.0 (does it?)
    val = to;
  }
  return val;
};

// Source: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
function date_string(d){
 function pad(n){return n<10 ? '0'+n : n}
 return d.getUTCFullYear()+''
      + pad(d.getUTCMonth()+1)+''
      + pad(d.getUTCDate())+''
      + pad(d.getUTCHours())+''
      + pad(d.getUTCMinutes())+''
      + pad(d.getUTCSeconds())}

srswor = function(list, n, ignore) {
  if(!ignore) ignore = [];
  for(var i=0; i<ignore.length; i++) {
    var idx = list.indexOf(ignore[i]);
    if(idx >= 0) list.splice(idx, 1);
  }
  if(list.length < n) return list;
  var new_list = [];
  while(new_list.length < n && list.length > 0) {
    var rand_idx = random_range(0, list.length - 1);
    new_list.push(list.splice(rand_idx, 1));
  }
  return new_list;
};

run = function(code, n) {
  var retcode = iimPlay("CODE: "+code);
  if(retcode != 1) {
    alert("BAD CODE:\n"+code+"\n\nretcode:"+retcode);
    return;
  }
  if(n) {
    var extract = iimGetLastExtract(n);
    if(extract == "#EANF#") return false; // "Extraction Anchor Not Found"
    return extract;
  }
};

sleep = function(seconds) { run("WAIT SECONDS="+seconds); };
visit_url = function(url) { run("URL GOTO="+url); };

save_profile = function(id) {
  var raw_profile = run("TAG POS=1 TYPE=DIV ATTR=CLASS:prof1-lay EXTRACT=HTM", 1);
  var filename = date_string(new Date())+"_"+id+".data";
  var path = FILE_PATH.format("data/mbga/person/"+filename);
  write_file(path, raw_profile);
};

save_group = function(id) {
  var raw_group = run("TAG POS=1 TYPE=UL ATTR=CLASS:blk-lay EXTRACT=HTM", 1);
  var filename = date_string(new Date())+"_"+id+".data";
  var path = FILE_PATH.format("data/mbga/group/"+filename);
  write_file(path, raw_group);
};

visit_profile = function(id) {

};

visit_group = function(id) {

};

extract_profiles = function() {

};

extract_groups = function() {

};

main = function() {
  //save_profile("http://yahoo-mbga.jp/10086","10086");
  //save_group("http://yahoo-mbga.jp/group/31966079", "31966079");

  var queue = []; // TODO seed nodes
  var visited_groups = [];
  var visited_profiles = [];
  while(queue.length > 0){
    var item = queue.shift();
    if(item["type"] === "profile") {
      if(visited_profiles.indexOf(item["id"]) < 0) continue;
      visit_profile(item["id"]);
      save_profile(item["id"]);
      visited_profiles.push(item["id"]);
      queue.concat(extract_groups());
    }
    else {
      if(visited_groups.indexOf(item["id"]) < 0) continue;
      visit_group(item["id"]);
      save_group(item["id"]);
      visited_groups.push(item["id"]);
      queue.concat(extract_profiles());
    }
  }
};

main();<|endoftext|>


<commit_before>import React from 'react';

export default React.createClass({
  fields: {},
  invalidFields: {},

  getInitialState() {
    return {valid: true};
  },

  getDefaultProps() {
    return {values: {}};
  },

  validate() {
    return new Promise((resolve) => {
      this.invalidFields = {};
      for (let fieldName in this.fields) {
        for (let field of this.fields[fieldName]) {
          if (field && !field.validate()) {
            this.invalidFields[fieldName] = field;
          }
        }
      }
      this.setState({
        valid: Object.keys(this.invalidFields).length === 0
      }, resolve);
    });
  },

  handleSubmit(e) {
    e.preventDefault();
    return this.validate()
      .then(() => {
        if (this.props.onSubmit) {
          this.props.onSubmit(e, {
            valid: this.state.valid,
            values: this.values()
          });
        }
      });
  },

  getField(fieldName) {
    return this.fields[fieldName].sort((a, b) => {
      return b.state.timestamp - a.state.timestamp;
    })[0];
  },

  getCheckboxValues(fieldName) {
    let fieldValues = [];
    for (let field of this.fields[fieldName]) {
      if (field.state.value && field.state.checked) {
        fieldValues.push(field.state.value);
      }
    }
    if (fieldValues.length === 1) {
      fieldValues = fieldValues[0];
    }
    return fieldValues;
  },

  values() {
    let values = {};
    for (let fieldName in this.fields) {
      let field = this.getField(fieldName);
      switch (field.state.type) {
        case 'checkbox': {
          let fieldValues = this.getCheckboxValues(fieldName);
          if (fieldValues.length) {
            values[fieldName] = fieldValues;
          }
          break;
        }
        default: {
          if (field && field.state.value) {
            values[fieldName] = field.state.value;
          }
        }
      }
    }
    return values;
  },

  addPropsToChildren(children, props) {
    return React.Children.map(children, (child) => {
      let childProps = {};
      if (child.props) {
        childProps.children = this.addPropsToChildren(child.props.children, props);
        if (child.type.displayName === 'Field') {
          const formValues = this.props.values[child.props.name] || {};
          const values = {
            initialValue: formValues.value,
            message: formValues.message
          };
          childProps = Object.assign(childProps, values, props);
        }
        child = React.cloneElement(child, childProps);
      }
      return child;
    });
  },

  children() {
    let fields = {};
    const ref = {
      ref: (field) => {
        if (field) {
          if (!fields[field.props.name]) {
            fields[field.props.name] = [];
          }
          fields[field.props.name].push(field);
        }
      }
    };
    const children = this.addPropsToChildren(this.props.children, ref);
    this.fields = fields;
    return children;
  },

  render() {
    return (
      <form {...this.props} onSubmit={this.handleSubmit}>
        {this.children()}
      </form>
    );
  }
});

<commit_msg>Remove values prop from form when rendering<commit_after>import React from 'react';

export default React.createClass({
  fields: {},
  invalidFields: {},

  getInitialState() {
    return {valid: true};
  },

  getDefaultProps() {
    return {values: {}};
  },

  validate() {
    return new Promise((resolve) => {
      this.invalidFields = {};
      for (let fieldName in this.fields) {
        for (let field of this.fields[fieldName]) {
          if (field && !field.validate()) {
            this.invalidFields[fieldName] = field;
          }
        }
      }
      this.setState({
        valid: Object.keys(this.invalidFields).length === 0
      }, resolve);
    });
  },

  handleSubmit(e) {
    e.preventDefault();
    return this.validate()
      .then(() => {
        if (this.props.onSubmit) {
          this.props.onSubmit(e, {
            valid: this.state.valid,
            values: this.values()
          });
        }
      });
  },

  getField(fieldName) {
    return this.fields[fieldName].sort((a, b) => {
      return b.state.timestamp - a.state.timestamp;
    })[0];
  },

  getCheckboxValues(fieldName) {
    let fieldValues = [];
    for (let field of this.fields[fieldName]) {
      if (field.state.value && field.state.checked) {
        fieldValues.push(field.state.value);
      }
    }
    if (fieldValues.length === 1) {
      fieldValues = fieldValues[0];
    }
    return fieldValues;
  },

  values() {
    let values = {};
    for (let fieldName in this.fields) {
      let field = this.getField(fieldName);
      switch (field.state.type) {
        case 'checkbox': {
          let fieldValues = this.getCheckboxValues(fieldName);
          if (fieldValues.length) {
            values[fieldName] = fieldValues;
          }
          break;
        }
        default: {
          if (field && field.state.value) {
            values[fieldName] = field.state.value;
          }
        }
      }
    }
    return values;
  },

  addPropsToChildren(children, props) {
    return React.Children.map(children, (child) => {
      let childProps = {};
      if (child.props) {
        childProps.children = this.addPropsToChildren(child.props.children, props);
        if (child.type.displayName === 'Field') {
          const formValues = this.props.values[child.props.name] || {};
          const values = {
            initialValue: formValues.value,
            message: formValues.message
          };
          childProps = Object.assign(childProps, values, props);
        }
        child = React.cloneElement(child, childProps);
      }
      return child;
    });
  },

  children() {
    let fields = {};
    const ref = {
      ref: (field) => {
        if (field) {
          if (!fields[field.props.name]) {
            fields[field.props.name] = [];
          }
          fields[field.props.name].push(field);
        }
      }
    };
    const children = this.addPropsToChildren(this.props.children, ref);
    this.fields = fields;
    return children;
  },

  render() {
    let formProps = Object.assign({}, this.props);
    delete formProps.values;

    return (
      <form {...formProps} onSubmit={this.handleSubmit}>
        {this.children()}
      </form>
    );
  }
});

<|endoftext|>


<commit_before>import * as Loop from 'gameboard/loop';

import Base from 'flockn/base';
import Graphics from 'flockn/graphics';
import Scene from 'flockn/scene';
import Color from 'flockn/types/color';
import Viewport from 'flockn/viewport';

import {addable, renderable, updateable} from 'flockn/mixins';

var root = window;

// Game is the entry point for all games made with flockn.
// Any number of `Scene` instances can be attached to a `Game` instance
class Game extends Base {
  constructor(descriptor) {
    // The new operator does not need to be set explicitly.
    // If it isn't we return an instance of `Game`
    if (!this || !this instanceof Game) {
      return new Game(descriptor);
    }

    // Extend the `Base` class
    super('Game', descriptor);

    descriptor.call(this);

    Graphics.trigger('initialize', this);

    // `this.container` is a string, which is the id of the element.
    // If it's not given, it should create a new element. This should be handled by the renderer.
    this.container = null;

    // By default, the width and height of a `Game` instance will be as large as the inside of the browser window.
    this.width = root.innerWidth;
    this.height = root.innerHeight;
    this.color = new Color(255, 255, 255);

    // Set the viewport object
    this.viewport = Viewport;

    // `this.activeScene` is set to `null` by default, but will change once a scene will be shown
    this.activeScene = null;

    // A `Game` instance is the root element so the descriptor needs to be called directly,
    // because it won't be added to anywhere else
    this.call();

    // Mix in `renderable` and `updateable`
    renderable.call(this);
    updateable.call(this);

    // Bind the game loop to the `update` event
    Loop.on('update', (dt) => {
      // Deltatime should not be a millisecond value, but a second one.
      // It should be a value between 0 - 1
      this.trigger('update', dt / 1000);
    });

    // Bind the game loop to the `render` event
    Loop.on('render', () => {
      this.trigger('render');
    });

    // Add a `resize` event to each `Game` instance
    root.addEventListener('resize', () => {
      var newWidth = root.innerWidth;
      var newHeight = root.innerHeight;

      this.trigger('resize', newWidth, newHeight);

      // Trigger resize event for the current scene
      this.activeScene.trigger('resize', newWidth, newHeight);
    }, false);

    // Add an `orientationchange` event to each `Game` instance
    root.addEventListener('orientationchange', () => {
      this.trigger('orientationchange');
    }, false);
  }

  addScene() {
    // When adding a scene, the dimension of scenes should be
    // exactly as large as the `Game` instance itself
    this.queue.push(addable(Scene, this.children, function (child) {
      child.width = this.width;
      child.height = this.height;
    }).apply(this, arguments));
  }

  showScene(name) {
    // TODO: Add transitions

    // Set the `activeScene` property
    this.activeScene = name;

    // Call resize event
    this.children.byName(this.activeScene).trigger('resize', root.innerWidth, root.innerHeight);

    // Trigger the `show` event
    this.trigger('show', this.activeScene, this.children[this.activeScene]);
  }

  preload(assets) {

  }

  run(name) {
    // Start the game loop
    Loop.run();

    if (!name) {
      // If there's only no name, take the first scene
      if (this.children.length >= 1) {
        name = this.children[0].name;
      }
    }

    // Show the scene if a parameter has been specified
    if (name) {
      this.showScene(name);
    }
  }
}

export default Game;
<commit_msg>Fixes resize trigger<commit_after>import * as Loop from 'gameboard/loop';

import Base from 'flockn/base';
import Graphics from 'flockn/graphics';
import Scene from 'flockn/scene';
import Color from 'flockn/types/color';
import Viewport from 'flockn/viewport';

import {addable, renderable, updateable} from 'flockn/mixins';

var root = window;

// Game is the entry point for all games made with flockn.
// Any number of `Scene` instances can be attached to a `Game` instance
class Game extends Base {
  constructor(descriptor) {
    // The new operator does not need to be set explicitly.
    // If it isn't we return an instance of `Game`
    if (!this || !this instanceof Game) {
      return new Game(descriptor);
    }

    // Extend the `Base` class
    super('Game', descriptor);

    descriptor.call(this);

    Graphics.trigger('initialize', this);

    // `this.container` is a string, which is the id of the element.
    // If it's not given, it should create a new element. This should be handled by the renderer.
    this.container = null;

    // By default, the width and height of a `Game` instance will be as large as the inside of the browser window.
    this.width = root.innerWidth;
    this.height = root.innerHeight;
    this.color = new Color(255, 255, 255);

    // Set the viewport object
    this.viewport = Viewport;

    // `this.activeScene` is set to `null` by default, but will change once a scene will be shown
    this.activeScene = null;

    // A `Game` instance is the root element so the descriptor needs to be called directly,
    // because it won't be added to anywhere else
    this.call();

    // Mix in `renderable` and `updateable`
    renderable.call(this);
    updateable.call(this);

    // Bind the game loop to the `update` event
    Loop.on('update', (dt) => {
      // Deltatime should not be a millisecond value, but a second one.
      // It should be a value between 0 - 1
      this.trigger('update', dt / 1000);
    });

    // Bind the game loop to the `render` event
    Loop.on('render', () => {
      this.trigger('render');
    });

    // Add a `resize` event to each `Game` instance
    root.addEventListener('resize', () => {
      var newWidth = root.innerWidth;
      var newHeight = root.innerHeight;

      this.trigger('resize', newWidth, newHeight);

      // Trigger resize event for the current scene
      var currentScene = this.children.byName(this.activeScene);

      if (currentScene) {
        currentScene.trigger('resize', root.innerWidth, root.innerHeight);
      }
    }, false);

    // Add an `orientationchange` event to each `Game` instance
    root.addEventListener('orientationchange', () => {
      this.trigger('orientationchange');
    }, false);
  }

  addScene() {
    // When adding a scene, the dimension of scenes should be
    // exactly as large as the `Game` instance itself
    this.queue.push(addable(Scene, this.children, function (child) {
      child.width = this.width;
      child.height = this.height;
    }).apply(this, arguments));
  }

  showScene(name) {
    // TODO: Add transitions

    // Set the `activeScene` property
    this.activeScene = name;

    // Call resize event
    var currentScene = this.children.byName(this.activeScene);

    if (currentScene) {
      currentScene.trigger('resize', root.innerWidth, root.innerHeight);
    }

    // Trigger the `show` event
    this.trigger('show', this.activeScene, this.children[this.activeScene]);
  }

  preload(assets) {

  }

  run(name) {
    // Start the game loop
    Loop.run();

    if (!name) {
      // If there's only no name, take the first scene
      if (this.children.length >= 1) {
        name = this.children[0].name;
      }
    }

    // Show the scene if a parameter has been specified
    if (name) {
      this.showScene(name);
    }
  }
}

export default Game;
<|endoftext|>


<commit_before>let User = require(`${__dirname}/game/model/user.js`);
let Status = require(`${__dirname}/game/model/status.js`);

class Game {
    // TODO management of attack point
    constructor(users, maxHp) {
        this.users = users;
    };

    findUser(name) {
        let targets = this.users.filter((u) => u.name === name);
        return targets.length === 0 ? null : targets.pop();
    }
}

module.exports = {
    Game: Game,
    User: User,
    Status: Status
}
<commit_msg>Add max hp<commit_after>let User = require(`${__dirname}/game/model/user.js`);
let Status = require(`${__dirname}/game/model/status.js`);

class Game {
    // TODO management of attack point
    constructor(users, maxHp) {
        this.users = users;
        this.maxHp = maxHp;
    };

    findUser(name) {
        let targets = this.users.filter((u) => u.name === name);
        return targets.length === 0 ? null : targets.pop();
    }
}

module.exports = {
    Game: Game,
    User: User,
    Status: Status
}
<|endoftext|>


<commit_before>// @flow
import * as React from 'react'
import type { Props as GridProps } from './withBase'
import Base from './base'

function Grid(props: GridProps) {
  return <Base {...props} base={24} />
}

export default Grid
<commit_msg>feat(grid): allow modifying base prop (#274)<commit_after>// @flow
import * as React from 'react'
import type { Props as GridProps } from './withBase'
import Base from './base'

function Grid(props: GridProps) {
  return <Base base={24} {...props} />
}

export default Grid
<|endoftext|>


<commit_before>/*
 * Axelor Business Solutions
 *
 * Copyright (C) 2005-2016 Axelor (<http://axelor.com>).
 *
 * This program is free software: you can redistribute it and/or  modify
 * it under the terms of the GNU Affero General Public License, version 3,
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
(function() {

"use strict";

var ui = angular.module('axelor.ui');

function getStylePopup(element, styles) {

	return function($popup, $button) {

		var $list = $('
').addClass('wysiwyg-plugin-list').attr('unselectable', 'on');

		$.each(styles, function(format, name) {
			var $link = $('').attr('href', '#').html(name).click(
					function(event) {
						$(element).wysiwyg('shell').format(format).closePopup();
						event.stopPropagation();
						event.preventDefault();
						return false;
					});
			$list.append($link);
		});

		$popup.append($list);
	};
}

function getFontNamePopup(element, fonts) {

	return function($popup, $button) {

		var $list = $('
').addClass('wysiwyg-plugin-list').attr('unselectable', 'on');

		$.each(fonts, function(font, name) {
			var $link = $('').attr('href', '#').html(name).click(
					function(event) {
						try {
							document.execCommand('styleWithCSS', false, false);
							$(element).wysiwyg('shell').fontName(font).closePopup();
						} finally {
							document.execCommand('styleWithCSS', false, true);
						}
						event.stopPropagation();
						event.preventDefault();
						return false;
					});
			$list.append($link);
		});

		$popup.append($list);
	};
}

function getFontSizePopup(element, sizes) {

	return function($popup, $button) {

		var $list = $('
').addClass('wysiwyg-plugin-list').attr('unselectable', 'on');

		$.each(sizes, function(size, name) {
			var $link = $('').attr('href', '#').html(name).click(
					function(event) {
						$(element).focus();
						try {
							document.execCommand('styleWithCSS', false, false);
							$(element).wysiwyg('shell').fontSize(size).closePopup();
						} finally {
							document.execCommand('styleWithCSS', false, true);
						}
						event.stopPropagation();
						event.preventDefault();
						return false;
					});
			$list.append($link);
		});

		$popup.append($list);
	};
}

function getButtons(scope, element) {

	var lite = scope.field.lite;

	return {
		style: lite ? false : {
			title: _t('Style'),
			image: '\uf1dd',
			popup: getStylePopup(element, {
				'
' 			: _t('Normal'),
				'
' 		: '
' + _t('Formatted') + '
',
				'
'	: '
' + _t('Blockquote') + '
',
				'
': '
' + _t('Header 1') + '
',
				'
': '
' + _t('Header 2') + '
',
				'
': '
' + _t('Header 3') + '
',
				'
': '
' + _t('Header 4') + '
',
				'
': '
' + _t('Header 5') + '
',
				'
': '
' + _t('Header 6') + '
'
		    })
		},
		fontName: lite ? false : {
			title: _t('Font'),
			image: '\uf031',
			popup: getFontNamePopup(element, {
				'"Times New Roman", Times, serif': 'Times New Roman',
				'Arial, Helvetica, sans-serif': 'Arial',
				'"Courier New", Courier, monospace': 'Courier New',
				'Comic Sans, Comic Sans MS, cursive': 'Comic Sans',
				'Impact, fantasy': 'Impact',
		    })
		},
		fontSize: lite ? false : {
			title: _t('Font size'),
			image: '\uf035',
			popup: getFontSizePopup(element, {
				'1': '' + _t('Smaller') + '',
				'2': '' + _t('Small') + '',
				'3': '' + _t('Medium') + '',
				'4': '' + _t('Large') + '',
				'5': '' + _t('Larger') + ''
		    })
		},
		d1: lite ? false : {
			html: $('')
		},
		bold: {
	        title: _t('Bold (Ctrl+B)'),
	        image: '\uf032'
	    },
	    italic: {
	        title: _t('Italic (Ctrl+I)'),
	        image: '\uf033'
	    },
	    underline: {
	        title: _t('Underline (Ctrl+U)'),
	        image: '\uf0cd'
	    },
	    strikethrough: {
	        title: _t('Strikethrough (Ctrl+S)'),
	        image: '\uf0cc'
	    },
	    removeformat: {
	        title: _t('Remove format'),
	        image: '\uf12d'
	    },
	    d2: {
			html: $('')
		},
	    forecolor: lite ? false : {
	        title: _t('Text color'),
	        image: '\uf1fc'
	    },
	    highlight: lite ? false : {
	        title: _t('Background color'),
	        image: '\uf043'
	    },
	    d3: lite ? false : {
			html: $('')
		},
	    alignleft: {
	        title: _t('Left'),
	        image: '\uf036'
	    },
	    aligncenter: {
	        title: _t('Center'),
	        image: '\uf037'
	    },
	    alignright: {
	        title: _t('Right'),
	        image: '\uf038'
	    },
	    alignjustify: {
	        title: _t('Justify'),
	        image: '\uf039'
	    },
	    d4: {
			html: $('')
		},
	    orderedList: {
	        title: _t('Ordered list'),
	        image: '\uf0cb'
	    },
	    unorderedList: {
	        title: _t('Unordered list'),
	        image: '\uf0ca'
	    },
	    d6: lite ? false : {
			html: $('')
		},
	    indent: lite ? false : {
	        title: _t('Indent'),
	        image: '\uf03c'
	    },
	    outdent: lite ? false : {
	        title: _t('Outdent'),
	        image: '\uf03b'
	    },
	    d7: lite ? false : {
			html: $('')
		},
		insertimage: lite ? false : {
            title: _t('Insert image'),
            image: '\uf030'
		},
		insertlink: lite ? false : {
            title: _t('Insert link'),
            image: '\uf08e'
		},
		d8: lite ? false : {
			html: $('')
		},
		normalize: lite ? false : {
	    	title: _t('Normalize'),
	    	image: '\uf0d0',
	    	click: function () {
	    		scope.normalize();
	    	}
	    },
		showCode: lite ? false : {
			title: _t('Code'),
			image: '\uf121',
			click: function () {
				scope.toggleCode();
			}
		}
	};
}

ui.formInput('Html', {

	css: "html-item",

	init: function(scope) {

		scope.parse = function(value) {
			return value ? value : null;
		};
	},

	link_editable: function(scope, element, attrs, model) {
		this._super(scope, element, attrs, model);
		var textElement = element.find('textarea');
		var buttons = getButtons(scope, textElement);

		var props = scope.field,
			minSize = +props.minSize,
			maxSize = +props.maxSize,
			height = +(scope.field.height) || null;

		if (height) {
			height = Math.max(100, height);
		}

		function isParagraph(node) {
			return node && /^DIV|^P|^LI|^H[1-7]/.test(node.nodeName.toUpperCase());
		}

		function findParagraph(node) {
			if (!node) return null;
			if (node.classList && node.classList.contains('wysiwyg-editor')) return null;
			if (isParagraph(node)) return node;
			return findParagraph(node.parentNode);
		}

		textElement.wysiwyg({
			toolbar: 'top',
			buttons: buttons,
			submit: {
                title: _t('Submit'),
                image: '\uf00c'
            },
            selectImage: _t('Click or drop image'),
            placeholderUrl: 'www.example.com',
            maxImageSize: [600, 200],
			hijackContextmenu: false,
			onKeyPress: function(key, character, shiftKey, altKey, ctrlKey, metaKey) {
				if (key !== 13 || shiftKey) {
					return;
				}
		    	var parent = findParagraph(document.getSelection().anchorNode);
			    if (!parent) {
			    	document.execCommand('formatBlock', false, '
');
			    }
			}
		});

		var shell = textElement.wysiwyg('shell');
		var shellElement = $(shell.getElement());
		var shellActive = true;

		shellElement.addClass('html-content');

		if (scope.field.height) {
			shellElement.parent().height(height).resizable({
				handles: 's',
				resize: function () {
					shellElement.parent().width('');
				}
			});
		}

		function onChange(e) {

			var value = shellActive ? shell.getHTML() : textElement.val();

			var old = scope.getValue() || null;
			var txt = scope.parse(value) || null;

			if (old === txt) {
				return;
			}

			scope.setValue(value, true);
			scope.applyLater();
		}

		scope.$render_editable = function () {
			var value = scope.getValue() || "";
			scope.text = scope.format(value);

			var current = shellActive ? shell : textElement;
			var getter = shellActive ? 'getHTML' : 'val';
			var setter = shellActive ? 'setHTML' : 'val';

			var html = current[getter]();
			if (value !== html) {
				current[setter](value);
			}
		};

		textElement.on('input paste change blur', _.debounce(onChange, 100));

		textElement.on("focus", _.once(function (e) {

		    // Chrome and Edge supports this
			document.execCommand('defaultParagraphSeparator', false, 'p');

			// firefox uses attributes for some commands
			document.execCommand('styleWithCSS', false, true);
			document.execCommand('insertBrOnReturn', false, false);
		}));

		scope.toggleCode = function () {

			shellActive = !shellActive;

			element.parent().find('.wysiwyg-toolbar-icon')
				.toggleClass('disabled', !shellActive)
				.last().removeClass('disabled');

			if (shellActive) {
				textElement.hide();
				shellElement.show();
				shell.setHTML(textElement.val());
			} else {
				var height = Math.max(100, shellElement.outerHeight());
				shellElement.hide();
				textElement.show();

				if (!scope.field.height) {
					textElement.height(height);
				}
			}
		};

		scope.normalize = function () {

    		var html = shell.getHTML();
    		var div = $('
').html(html);

    		div.find('p').css({
    			'margin-top': 0,
    			'margin-bottom': '1em'});

    		div.find('ol,ul').each(function() {
    			var el = $(this);
    			if (el.parents('ol,ul').size()) return;
    			el.css({
	    			'margin-top': 0,
	    			'margin-bottom': '1em'});
    		});

    		div.find('blockquote').each(function() {
    			var el = $(this);
    			el.css({
	    			'margin': el.parents('blockquote').size() ? '0 0 0 2em' : '0 0 1em 2em',
	    			'border': 'none',
	    			'padding': 0
	    		});
    		});

    		shellElement.focus();
    		shell.setHTML(div[0].innerHTML);

    		div.remove();
		};

		scope.validate = function(value) {
			if (_.isEmpty(value)) {
				return true;
			}
			var length = value.length,
				valid = true;

			if (minSize) {
				valid = length >= minSize;
			}
			if(valid && maxSize) {
				valid = length <= maxSize;
			}

			return valid;
		};

	},

	template_readonly:
	'
'+
		'

'+
	'
',
	template_editable:
	'
'+
		'<textarea class="html-editor html-content"></textarea>'+
	'
'

});

ui.directive('uiBindTemplate', ['$interpolate', function($interpolate){

	function expand(scope, template) {
		if (!template || !template.match(/{{.*?}}/)) {
			return template;
		}
		return $interpolate(template)(scope.locals());
	}

	return {
		terminal: true,
		scope: {
			locals: "&",
			text: "=text",
			live: "&"
		},
		link: function(scope, element, attrs) {

			var template = null;

			function update() {
				var output = expand(scope, template) || "";
				element.html(output);
			}

			scope.$watch("text", function(text, old) {

				if (text === template) {
					return;
				}
				template = text;
				update();
			});

			var live = false;
			scope.$watch("live()", function(value) {
				if (live || !value) {
					return;
				}
				live = true;
				scope.$watch("locals()", function(value) {
					update();
				}, true);
			});
		}
	};
}]);

})();

<commit_msg>Remove trailing comma<commit_after>/*
 * Axelor Business Solutions
 *
 * Copyright (C) 2005-2016 Axelor (<http://axelor.com>).
 *
 * This program is free software: you can redistribute it and/or  modify
 * it under the terms of the GNU Affero General Public License, version 3,
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
(function() {

"use strict";

var ui = angular.module('axelor.ui');

function getStylePopup(element, styles) {

	return function($popup, $button) {

		var $list = $('
').addClass('wysiwyg-plugin-list').attr('unselectable', 'on');

		$.each(styles, function(format, name) {
			var $link = $('').attr('href', '#').html(name).click(
					function(event) {
						$(element).wysiwyg('shell').format(format).closePopup();
						event.stopPropagation();
						event.preventDefault();
						return false;
					});
			$list.append($link);
		});

		$popup.append($list);
	};
}

function getFontNamePopup(element, fonts) {

	return function($popup, $button) {

		var $list = $('
').addClass('wysiwyg-plugin-list').attr('unselectable', 'on');

		$.each(fonts, function(font, name) {
			var $link = $('').attr('href', '#').html(name).click(
					function(event) {
						try {
							document.execCommand('styleWithCSS', false, false);
							$(element).wysiwyg('shell').fontName(font).closePopup();
						} finally {
							document.execCommand('styleWithCSS', false, true);
						}
						event.stopPropagation();
						event.preventDefault();
						return false;
					});
			$list.append($link);
		});

		$popup.append($list);
	};
}

function getFontSizePopup(element, sizes) {

	return function($popup, $button) {

		var $list = $('
').addClass('wysiwyg-plugin-list').attr('unselectable', 'on');

		$.each(sizes, function(size, name) {
			var $link = $('').attr('href', '#').html(name).click(
					function(event) {
						$(element).focus();
						try {
							document.execCommand('styleWithCSS', false, false);
							$(element).wysiwyg('shell').fontSize(size).closePopup();
						} finally {
							document.execCommand('styleWithCSS', false, true);
						}
						event.stopPropagation();
						event.preventDefault();
						return false;
					});
			$list.append($link);
		});

		$popup.append($list);
	};
}

function getButtons(scope, element) {

	var lite = scope.field.lite;

	return {
		style: lite ? false : {
			title: _t('Style'),
			image: '\uf1dd',
			popup: getStylePopup(element, {
				'
' 			: _t('Normal'),
				'
' 		: '
' + _t('Formatted') + '
',
				'
'	: '
' + _t('Blockquote') + '
',
				'
': '
' + _t('Header 1') + '
',
				'
': '
' + _t('Header 2') + '
',
				'
': '
' + _t('Header 3') + '
',
				'
': '
' + _t('Header 4') + '
',
				'
': '
' + _t('Header 5') + '
',
				'
': '
' + _t('Header 6') + '
'
		    })
		},
		fontName: lite ? false : {
			title: _t('Font'),
			image: '\uf031',
			popup: getFontNamePopup(element, {
				'"Times New Roman", Times, serif': 'Times New Roman',
				'Arial, Helvetica, sans-serif': 'Arial',
				'"Courier New", Courier, monospace': 'Courier New',
				'Comic Sans, Comic Sans MS, cursive': 'Comic Sans',
				'Impact, fantasy': 'Impact'
		    })
		},
		fontSize: lite ? false : {
			title: _t('Font size'),
			image: '\uf035',
			popup: getFontSizePopup(element, {
				'1': '' + _t('Smaller') + '',
				'2': '' + _t('Small') + '',
				'3': '' + _t('Medium') + '',
				'4': '' + _t('Large') + '',
				'5': '' + _t('Larger') + ''
		    })
		},
		d1: lite ? false : {
			html: $('')
		},
		bold: {
	        title: _t('Bold (Ctrl+B)'),
	        image: '\uf032'
	    },
	    italic: {
	        title: _t('Italic (Ctrl+I)'),
	        image: '\uf033'
	    },
	    underline: {
	        title: _t('Underline (Ctrl+U)'),
	        image: '\uf0cd'
	    },
	    strikethrough: {
	        title: _t('Strikethrough (Ctrl+S)'),
	        image: '\uf0cc'
	    },
	    removeformat: {
	        title: _t('Remove format'),
	        image: '\uf12d'
	    },
	    d2: {
			html: $('')
		},
	    forecolor: lite ? false : {
	        title: _t('Text color'),
	        image: '\uf1fc'
	    },
	    highlight: lite ? false : {
	        title: _t('Background color'),
	        image: '\uf043'
	    },
	    d3: lite ? false : {
			html: $('')
		},
	    alignleft: {
	        title: _t('Left'),
	        image: '\uf036'
	    },
	    aligncenter: {
	        title: _t('Center'),
	        image: '\uf037'
	    },
	    alignright: {
	        title: _t('Right'),
	        image: '\uf038'
	    },
	    alignjustify: {
	        title: _t('Justify'),
	        image: '\uf039'
	    },
	    d4: {
			html: $('')
		},
	    orderedList: {
	        title: _t('Ordered list'),
	        image: '\uf0cb'
	    },
	    unorderedList: {
	        title: _t('Unordered list'),
	        image: '\uf0ca'
	    },
	    d6: lite ? false : {
			html: $('')
		},
	    indent: lite ? false : {
	        title: _t('Indent'),
	        image: '\uf03c'
	    },
	    outdent: lite ? false : {
	        title: _t('Outdent'),
	        image: '\uf03b'
	    },
	    d7: lite ? false : {
			html: $('')
		},
		insertimage: lite ? false : {
            title: _t('Insert image'),
            image: '\uf030'
		},
		insertlink: lite ? false : {
            title: _t('Insert link'),
            image: '\uf08e'
		},
		d8: lite ? false : {
			html: $('')
		},
		normalize: lite ? false : {
	    	title: _t('Normalize'),
	    	image: '\uf0d0',
	    	click: function () {
	    		scope.normalize();
	    	}
	    },
		showCode: lite ? false : {
			title: _t('Code'),
			image: '\uf121',
			click: function () {
				scope.toggleCode();
			}
		}
	};
}

ui.formInput('Html', {

	css: "html-item",

	init: function(scope) {

		scope.parse = function(value) {
			return value ? value : null;
		};
	},

	link_editable: function(scope, element, attrs, model) {
		this._super(scope, element, attrs, model);
		var textElement = element.find('textarea');
		var buttons = getButtons(scope, textElement);

		var props = scope.field,
			minSize = +props.minSize,
			maxSize = +props.maxSize,
			height = +(scope.field.height) || null;

		if (height) {
			height = Math.max(100, height);
		}

		function isParagraph(node) {
			return node && /^DIV|^P|^LI|^H[1-7]/.test(node.nodeName.toUpperCase());
		}

		function findParagraph(node) {
			if (!node) return null;
			if (node.classList && node.classList.contains('wysiwyg-editor')) return null;
			if (isParagraph(node)) return node;
			return findParagraph(node.parentNode);
		}

		textElement.wysiwyg({
			toolbar: 'top',
			buttons: buttons,
			submit: {
                title: _t('Submit'),
                image: '\uf00c'
            },
            selectImage: _t('Click or drop image'),
            placeholderUrl: 'www.example.com',
            maxImageSize: [600, 200],
			hijackContextmenu: false,
			onKeyPress: function(key, character, shiftKey, altKey, ctrlKey, metaKey) {
				if (key !== 13 || shiftKey) {
					return;
				}
		    	var parent = findParagraph(document.getSelection().anchorNode);
			    if (!parent) {
			    	document.execCommand('formatBlock', false, '
');
			    }
			}
		});

		var shell = textElement.wysiwyg('shell');
		var shellElement = $(shell.getElement());
		var shellActive = true;

		shellElement.addClass('html-content');

		if (scope.field.height) {
			shellElement.parent().height(height).resizable({
				handles: 's',
				resize: function () {
					shellElement.parent().width('');
				}
			});
		}

		function onChange(e) {

			var value = shellActive ? shell.getHTML() : textElement.val();

			var old = scope.getValue() || null;
			var txt = scope.parse(value) || null;

			if (old === txt) {
				return;
			}

			scope.setValue(value, true);
			scope.applyLater();
		}

		scope.$render_editable = function () {
			var value = scope.getValue() || "";
			scope.text = scope.format(value);

			var current = shellActive ? shell : textElement;
			var getter = shellActive ? 'getHTML' : 'val';
			var setter = shellActive ? 'setHTML' : 'val';

			var html = current[getter]();
			if (value !== html) {
				current[setter](value);
			}
		};

		textElement.on('input paste change blur', _.debounce(onChange, 100));

		textElement.on("focus", _.once(function (e) {

		    // Chrome and Edge supports this
			document.execCommand('defaultParagraphSeparator', false, 'p');

			// firefox uses attributes for some commands
			document.execCommand('styleWithCSS', false, true);
			document.execCommand('insertBrOnReturn', false, false);
		}));

		scope.toggleCode = function () {

			shellActive = !shellActive;

			element.parent().find('.wysiwyg-toolbar-icon')
				.toggleClass('disabled', !shellActive)
				.last().removeClass('disabled');

			if (shellActive) {
				textElement.hide();
				shellElement.show();
				shell.setHTML(textElement.val());
			} else {
				var height = Math.max(100, shellElement.outerHeight());
				shellElement.hide();
				textElement.show();

				if (!scope.field.height) {
					textElement.height(height);
				}
			}
		};

		scope.normalize = function () {

    		var html = shell.getHTML();
    		var div = $('
').html(html);

    		div.find('p').css({
    			'margin-top': 0,
    			'margin-bottom': '1em'});

    		div.find('ol,ul').each(function() {
    			var el = $(this);
    			if (el.parents('ol,ul').size()) return;
    			el.css({
	    			'margin-top': 0,
	    			'margin-bottom': '1em'});
    		});

    		div.find('blockquote').each(function() {
    			var el = $(this);
    			el.css({
	    			'margin': el.parents('blockquote').size() ? '0 0 0 2em' : '0 0 1em 2em',
	    			'border': 'none',
	    			'padding': 0
	    		});
    		});

    		shellElement.focus();
    		shell.setHTML(div[0].innerHTML);

    		div.remove();
		};

		scope.validate = function(value) {
			if (_.isEmpty(value)) {
				return true;
			}
			var length = value.length,
				valid = true;

			if (minSize) {
				valid = length >= minSize;
			}
			if(valid && maxSize) {
				valid = length <= maxSize;
			}

			return valid;
		};

	},

	template_readonly:
	'
'+
		'

'+
	'
',
	template_editable:
	'
'+
		'<textarea class="html-editor html-content"></textarea>'+
	'
'

});

ui.directive('uiBindTemplate', ['$interpolate', function($interpolate){

	function expand(scope, template) {
		if (!template || !template.match(/{{.*?}}/)) {
			return template;
		}
		return $interpolate(template)(scope.locals());
	}

	return {
		terminal: true,
		scope: {
			locals: "&",
			text: "=text",
			live: "&"
		},
		link: function(scope, element, attrs) {

			var template = null;

			function update() {
				var output = expand(scope, template) || "";
				element.html(output);
			}

			scope.$watch("text", function(text, old) {

				if (text === template) {
					return;
				}
				template = text;
				update();
			});

			var live = false;
			scope.$watch("live()", function(value) {
				if (live || !value) {
					return;
				}
				live = true;
				scope.$watch("locals()", function(value) {
					update();
				}, true);
			});
		}
	};
}]);

})();

<|endoftext|>