<commit_before>var RichText = require('../../services/RichText')
var TimeText = require('../../services/TimeText')
var truncate = require('html-truncate')

module.exports = function ($scope, $state, $rootScope, $modal, $dialog, $analytics, growl, Post, User, UserCache, CurrentUser) {
  'ngInject'

  $scope.singlePost = $state.current.data && $state.current.data.singlePost
  $scope.isCommentsCollapsed = !$scope.singlePost
  $scope.voteTooltipText = ''
  $scope.followersNotMe = []
  $scope.isFollowing = false
  $scope.joinPostText = ''
  $scope.onlyAuthorFollowing = false

  var currentUser = CurrentUser.get()
  var voteText = "click to  me."
  var unvoteText = "click to un- me."
  var post = $scope.post

  $scope.community = Post.relevantCommunity(post, currentUser)

  var userEventResponse = function () {
    var responder = _.filter(post.responders, responder => responder.id === currentUser.id)[0]
    if (responder) {
      return responder.response
    } else {
      return ''
    }
  }

  $scope.eventResponse = userEventResponse()
  $scope.eventYeses = () => _.filter(post.responders, er => er.response === 'yes')
  $scope.eventMaybes = () => _.filter(post.responders, er => er.response === 'maybe')
  $scope.eventNos = () => _.filter(post.responders, er => er.response === 'no')

  var rlResult = []
  var rlYeses = []
  var rlMaybes = []
  var rlNos = []

  var yesHeader = {header: 'Going', name: -1}
  var maybeHeader = {header: 'Maybe', name: -2}
  var noHeader = {header: 'Can\'t Go', name: -3}

  $scope.responderList = () => {
    console.log('responderList')
    rlResult.length = 0
    rlYeses.length = 0
    rlMaybes.length = 0
    rlNos.length = 0

    rlYeses = rlYeses.concat($scope.eventYeses())
    rlMaybes = rlMaybes.concat($scope.eventMaybes())
    rlNos = rlNos.concat($scope.eventNos())

    if (rlYeses.length > 0) {
      console.log('yeses > 0')
      rlResult.push(yesHeader)
      rlResult = rlResult.concat(rlYeses)
    }
    if (rlMaybes.length > 0) {
      console.log('maybes > 0')
      rlResult.push(maybeHeader)
      rlResult = rlResult.concat(rlMaybes)
    }
    if (rlNos.length > 0) {
      console.log('nos > 0')
      rlResult.push(noHeader)
      rlResult = rlResult.concat(rlNos)
    }
    console.log('list: ', JSON.stringify(rlResult))
    return rlResult
  }

  $scope.isPostOwner = function () {
    return CurrentUser.is(post.user && post.user.id)
  }

  $scope.markFulfilled = function () {
    var modalInstance = $modal.open({
      templateUrl: '/ui/app/fulfillModal.tpl.html',
      controller: 'FulfillmentCtrl',
      keyboard: false,
      backdrop: 'static',
      scope: $scope
    })

    modalInstance.result.then(() => $analytics.eventTrack('Post: Fulfill', {post_id: post.id}))
  }

  // Voting is the same thing as "liking"
  $scope.vote = function () {
    post.myVote = !post.myVote
    post.votes += (post.myVote ? 1 : -1)
    $scope.voteTooltipText = post.myVote ? unvoteText : voteText

    Post.vote({id: post.id}, function () {
      $analytics.eventTrack('Post: Like', {
        post_id: post.id,
        state: (post.myVote ? 'on' : 'off')
      })
    }, function (resp) {
      if (_.contains([401, 403], resp.status)) {
        $scope.$emit('unauthorized', {context: 'like'})
      }
    })
  }

  $scope.toggleComments = function () {
    if ($scope.isCommentsCollapsed) {
      $analytics.eventTrack('Post: Comments: Show', {post_id: post.id})
    }
    $scope.isCommentsCollapsed = !$scope.isCommentsCollapsed
  }

  $scope.toggleFollow = function () {
    var user = currentUser
    if (!user) return

    if (!$scope.isFollowing) {
      $analytics.eventTrack('Post: Join', {post_id: post.id})
      post.followers.push({
        id: user.id,
        name: user.name,
        avatar_url: user.avatar
      })
      Post.follow({id: post.id})
      UserCache.followedPosts.clear(user.id)
    } else {
      $analytics.eventTrack('Post: Leave', {post_id: post.id})
      post.followers = _.without(post.followers, _.findWhere(post.followers, {id: user.id}))
      Post.follow({id: post.id})
      UserCache.followedPosts.remove(user.id, post.id)
    }
  }

  $scope['delete'] = function () {
    $dialog.confirm({
      message: 'Are you sure you want to remove "' + post.name + '"? This cannot be undone.'
    }).then(function () {
      $scope.removeFn({postToRemove: post})
      new Post(post).$remove({})
    })
  }

  $scope.showMore = function () {
    setText(true)
  }

  $scope.openFollowers = function (isOpen) {
    if (isOpen) {
      $analytics.eventTrack('Followers: Viewed List of Followers', {num_followers: $scope.followersNotMe.length})
    }
  }

  $scope.openResponders = function (isOpen) {
    if (isOpen) {
      $analytics.eventTrack('Responders: Viewed List of Responders', {num_responders: post.responders.length})
    }
  }

  $scope.complain = function () {
    Post.complain({id: post.id}, function () {
      growl.addSuccessMessage('Thank you for reporting this. Moderators will address it within 24 hours.')
    })
  }

  $scope.postImage = function () {
    return _.find(post.media || [], m => m.type === 'image')
  }

  $scope.docs = function () {
    return _.filter(post.media || [], m => m.type === 'gdoc')
  }

  var setText = function (fullLength) {
    var text = post.description
    if (!text) text = ''

    text = RichText.present(text)

    if (!fullLength && angular.element(text).text().trim().length > 140) {
      text = truncate(text, 140)
      $scope.truncated = true
    } else {
      $scope.truncated = false
    }

    $scope.description = text
    $scope.hasDescription = angular.element(text).text().trim().length > 0
  }

  $scope.$watchCollection('post.followers', function () {
    var meInFollowers = (currentUser && _.findWhere(post.followers, {id: currentUser.id}))

    if (meInFollowers) {
      $scope.followersNotMe = _.without(post.followers, meInFollowers)
      $scope.isFollowing = true
    } else {
      $scope.followersNotMe = post.followers
      $scope.isFollowing = false
    }

    // If the only person following the post is the author we can hide the following status in the post
    var firstFollower = _.first(post.followers)
    $scope.onlyAuthorFollowing = (post.followers.length === 1 && firstFollower.name === post.user.name)
  })

  $scope.canEdit = currentUser && (post.user.id === currentUser.id || currentUser.canModerate(post.communities[0]))
  $scope.voteTooltipText = post.myVote ? unvoteText : voteText
  setText($scope.startExpanded)

  var now = new Date()
  $scope.showUpdateTime = (now - new Date(post.updated_at)) < (now - new Date(post.created_at)) * 0.8

  $scope.truncate = truncate

  $scope.showTime = function () {
    var start = new Date(post.start_time)
    var end = post.end_time && new Date(post.end_time)
    return TimeText.range(start, end)
  }

  $scope.showFullTime = function () {
    var start = new Date(post.start_time)
    var end = post.end_time && new Date(post.end_time)
    return TimeText.rangeFullText(start, end)
  }

  $scope.changeEventResponse = function (response) {
    var user = currentUser
    if (!user) return

    Post.respond({id: post.id, response: response})

    var meInResponders = _.findWhere(post.responders, {id: user.id})
    post.responders = _.without(post.responders, meInResponders)

    if ($scope.eventResponse === response) {
      $scope.eventResponse = ''
      $analytics.eventTrack('Event: Unrespond', {post_id: post.id})
    } else {
      $scope.eventResponse = response
      post.responders.push({id: user.id, name: user.name, avatar_url: user.avatar_url, response: response})
      $analytics.eventTrack('Event: Respond', {post_id: post.id, response: response})
    }
  }
}
<commit_msg>simplify respondList<commit_after>var RichText = require('../../services/RichText')
var TimeText = require('../../services/TimeText')
var truncate = require('html-truncate')

module.exports = function ($scope, $state, $rootScope, $modal, $dialog, $analytics, growl, Post, User, UserCache, CurrentUser) {
  'ngInject'

  $scope.singlePost = $state.current.data && $state.current.data.singlePost
  $scope.isCommentsCollapsed = !$scope.singlePost
  $scope.voteTooltipText = ''
  $scope.followersNotMe = []
  $scope.isFollowing = false
  $scope.joinPostText = ''
  $scope.onlyAuthorFollowing = false

  var currentUser = CurrentUser.get()
  var voteText = "click to  me."
  var unvoteText = "click to un- me."
  var post = $scope.post

  $scope.community = Post.relevantCommunity(post, currentUser)

  var userEventResponse = function () {
    var responder = _.filter(post.responders, responder => responder.id === currentUser.id)[0]
    if (responder) {
      return responder.response
    } else {
      return ''
    }
  }

  $scope.eventResponse = userEventResponse()
  $scope.eventYeses = () => _.filter(post.responders, er => er.response === 'yes')
  $scope.eventMaybes = () => _.filter(post.responders, er => er.response === 'maybe')
  $scope.eventNos = () => _.filter(post.responders, er => er.response === 'no')

  var rlResult = []

  var yesHeader = {header: 'Going', name: -1}
  var maybeHeader = {header: 'Maybe', name: -2}
  var noHeader = {header: 'Can\'t Go', name: -3}

  $scope.responderList = () => {
    console.log('responderList')
    rlResult.length = 0

    var yeses = $scope.eventYeses()
    var maybes = $scope.eventMaybes()
    var nos = $scope.eventNos()

    if (yeses.length > 0) {
      console.log('yeses > 0')
      rlResult.push(yesHeader)
      rlResult = rlResult.concat(yeses)
    }
    if (maybes.length > 0) {
      console.log('maybes > 0')
      rlResult.push(maybeHeader)
      rlResult = rlResult.concat(maybes)
    }
    if (nos.length > 0) {
      console.log('nos > 0')
      rlResult.push(noHeader)
      rlResult = rlResult.concat(nos)
    }
    console.log('list: ', JSON.stringify(rlResult))
    return rlResult
  }

  $scope.isPostOwner = function () {
    return CurrentUser.is(post.user && post.user.id)
  }

  $scope.markFulfilled = function () {
    var modalInstance = $modal.open({
      templateUrl: '/ui/app/fulfillModal.tpl.html',
      controller: 'FulfillmentCtrl',
      keyboard: false,
      backdrop: 'static',
      scope: $scope
    })

    modalInstance.result.then(() => $analytics.eventTrack('Post: Fulfill', {post_id: post.id}))
  }

  // Voting is the same thing as "liking"
  $scope.vote = function () {
    post.myVote = !post.myVote
    post.votes += (post.myVote ? 1 : -1)
    $scope.voteTooltipText = post.myVote ? unvoteText : voteText

    Post.vote({id: post.id}, function () {
      $analytics.eventTrack('Post: Like', {
        post_id: post.id,
        state: (post.myVote ? 'on' : 'off')
      })
    }, function (resp) {
      if (_.contains([401, 403], resp.status)) {
        $scope.$emit('unauthorized', {context: 'like'})
      }
    })
  }

  $scope.toggleComments = function () {
    if ($scope.isCommentsCollapsed) {
      $analytics.eventTrack('Post: Comments: Show', {post_id: post.id})
    }
    $scope.isCommentsCollapsed = !$scope.isCommentsCollapsed
  }

  $scope.toggleFollow = function () {
    var user = currentUser
    if (!user) return

    if (!$scope.isFollowing) {
      $analytics.eventTrack('Post: Join', {post_id: post.id})
      post.followers.push({
        id: user.id,
        name: user.name,
        avatar_url: user.avatar
      })
      Post.follow({id: post.id})
      UserCache.followedPosts.clear(user.id)
    } else {
      $analytics.eventTrack('Post: Leave', {post_id: post.id})
      post.followers = _.without(post.followers, _.findWhere(post.followers, {id: user.id}))
      Post.follow({id: post.id})
      UserCache.followedPosts.remove(user.id, post.id)
    }
  }

  $scope['delete'] = function () {
    $dialog.confirm({
      message: 'Are you sure you want to remove "' + post.name + '"? This cannot be undone.'
    }).then(function () {
      $scope.removeFn({postToRemove: post})
      new Post(post).$remove({})
    })
  }

  $scope.showMore = function () {
    setText(true)
  }

  $scope.openFollowers = function (isOpen) {
    if (isOpen) {
      $analytics.eventTrack('Followers: Viewed List of Followers', {num_followers: $scope.followersNotMe.length})
    }
  }

  $scope.openResponders = function (isOpen) {
    if (isOpen) {
      $analytics.eventTrack('Responders: Viewed List of Responders', {num_responders: post.responders.length})
    }
  }

  $scope.complain = function () {
    Post.complain({id: post.id}, function () {
      growl.addSuccessMessage('Thank you for reporting this. Moderators will address it within 24 hours.')
    })
  }

  $scope.postImage = function () {
    return _.find(post.media || [], m => m.type === 'image')
  }

  $scope.docs = function () {
    return _.filter(post.media || [], m => m.type === 'gdoc')
  }

  var setText = function (fullLength) {
    var text = post.description
    if (!text) text = ''

    text = RichText.present(text)

    if (!fullLength && angular.element(text).text().trim().length > 140) {
      text = truncate(text, 140)
      $scope.truncated = true
    } else {
      $scope.truncated = false
    }

    $scope.description = text
    $scope.hasDescription = angular.element(text).text().trim().length > 0
  }

  $scope.$watchCollection('post.followers', function () {
    var meInFollowers = (currentUser && _.findWhere(post.followers, {id: currentUser.id}))

    if (meInFollowers) {
      $scope.followersNotMe = _.without(post.followers, meInFollowers)
      $scope.isFollowing = true
    } else {
      $scope.followersNotMe = post.followers
      $scope.isFollowing = false
    }

    // If the only person following the post is the author we can hide the following status in the post
    var firstFollower = _.first(post.followers)
    $scope.onlyAuthorFollowing = (post.followers.length === 1 && firstFollower.name === post.user.name)
  })

  $scope.canEdit = currentUser && (post.user.id === currentUser.id || currentUser.canModerate(post.communities[0]))
  $scope.voteTooltipText = post.myVote ? unvoteText : voteText
  setText($scope.startExpanded)

  var now = new Date()
  $scope.showUpdateTime = (now - new Date(post.updated_at)) < (now - new Date(post.created_at)) * 0.8

  $scope.truncate = truncate

  $scope.showTime = function () {
    var start = new Date(post.start_time)
    var end = post.end_time && new Date(post.end_time)
    return TimeText.range(start, end)
  }

  $scope.showFullTime = function () {
    var start = new Date(post.start_time)
    var end = post.end_time && new Date(post.end_time)
    return TimeText.rangeFullText(start, end)
  }

  $scope.changeEventResponse = function (response) {
    var user = currentUser
    if (!user) return

    Post.respond({id: post.id, response: response})

    var meInResponders = _.findWhere(post.responders, {id: user.id})
    post.responders = _.without(post.responders, meInResponders)

    if ($scope.eventResponse === response) {
      $scope.eventResponse = ''
      $analytics.eventTrack('Event: Unrespond', {post_id: post.id})
    } else {
      $scope.eventResponse = response
      post.responders.push({id: user.id, name: user.name, avatar_url: user.avatar_url, response: response})
      $analytics.eventTrack('Event: Respond', {post_id: post.id, response: response})
    }
  }
}
<|endoftext|>


<commit_before>import React from 'react';
import { storiesOf } from '@storybook/react';

import { grommet, Box, Button, Grommet } from 'grommet';

const ColoredButton = props => (
  <Grommet theme={grommet}>
    <Box align="center" pad="large" gap="small">
      <Button
        primary
        color="dark-1"
        label="Submit dark-1"
        onClick={() => {}}
        {...props}
      />
      <Button
        primary
        color="#111111"
        label="Submit #111111"
        onClick={() => {}}
        {...props}
      />
      <Button
        primary
        color="#777"
        label="Submit #777"
        onClick={() => {}}
        {...props}
      />
    </Box>
  </Grommet>
);

storiesOf('Button', module).add('Colored', () => <ColoredButton />);
<commit_msg>cleanup redundant story (#2956)<commit_after><|endoftext|>


<commit_before>$("document").ready(function(){

	$("form.add_inst_email").submit(function(event) {
        event.preventDefault();
        event.stopImmediatePropagation();
        var form = $(this);
        var msg = gettext('Are you sure you want to add this e-mail as an election admin?');
        if ($(this).attr('id') == 'add_inst_mngt_email'){
            msg = gettext('Are you sure you want to add this e-mail as an institution admin?')
        }
		if (confirm(msg)){
            var email = form.find('input[type=email]').val();
            var url = form.attr('action');
            $.ajax({
                type: "POST",
                url: url,
                data: {'email': email},
                success: function (data) {
                    form.parents('div.div_form').removeClass('has-error');
                    form.parents('div.div_form').addClass('has-success');
                    form.parents('div.div_form').find('span.add_field_result').text(gettext('Email successfully saved.'));
                    $('#institution_users').load($('#institution_users').attr('data-url'));
                },
                error: function (error) {
                    form.parents('div.div_form').removeClass('has-success');
                    form.parents('div.div_form').addClass('has-error');
                    form.parents('div.div_form').find('span.add_field_result').text(gettext('Please, correct the provided value'));
                }
            });
            form.find('input[type=email]').val('');
		}
		return false;
	});

    $('.remove_institution_user').click(function(event) {
        event.preventDefault();
        event.stopImmediatePropagation();
		if (confirm(gettext('Are you sure you want to delete this user?'))){
            var url = $(this).attr('href');
            var element = $(this);
            $.ajax({
                type: "POST",
                url: url,
                success: function (data) {
                    element.parents('tr').remove();
                },
                error: function (error) {
                    form.parents('div.div_form').addClass('has-error');
                    form.parents('div.div_form').find('span.add_field_result').text(gettext('Please, correct the provided value'));
                }
            });
		}
		return false;
    });

    $('#inst_details').on('click', '#edit_inst_button', function(event){
        $('#readonly_inst').addClass('hidden');
        $('#edit_inst').addClass('panel-body');
        $('#edit_inst').removeClass('hidden');
    });

    $('#inst_details').on('click', '#save_inst_data', function(event){
        var url = $('#form_edit_inst').attr('action');
        var inst_data = {}
        $('p.inst_data').each(function(){
            inst_data[$(this).children('.form-control').attr('name')] = $(this).children('.form-control').val();
        });
        $.ajax({
            type: "POST",
            url: url,
            data: inst_data,
            success: function (data) {
                $('#inst_details').load($('#inst_details').attr('data-url'));
            },
            error: function (error) {

            }

        });
        return false;
    });

    $("#institution_users").on("click", ".date_expires_at", function(){
        $(".date_expires_at").datepicker({
        format: "dd/mm/yyyy",
        startDate: "now",
        autoclose: true,
        todayHighlight: true
        })
        .on('changeDate', function(e){

            var expires_at = $(this);
            var expires_at_text = expires_at.parent().children('.date');
            var url= expires_at.data('url');

            data = {
                'expires_at' : expires_at.datepicker('getFormattedDate'),
            }

            $.ajax({
                type: "POST",
                url: url,
                dataType: "json",
                data: data,

                success: function (data) {

                    expires_at
                        .removeClass('text-danger')
                        .addClass('text-success');

                    expires_at_text
                        .text(expires_at.datepicker('getFormattedDate'))
                        .removeClass('text-danger')
                        .addClass('text-success');
                },

                error: function (error) {

                    expires_at
                        .removeClass('text-danger')
                        .addClass('text-danger');

                    expires_at_text
                        .removeClass('text-danger')
                        .addClass('text-danger');
                },
            });
        });
    });

    var table;
    function draw_election_list () {
        table = $('#list').DataTable({
            "language": {
                "lengthMenu": gettext("Display _MENU_ records per page"),
                "zeroRecords": gettext("Nothing found - sorry"),
                "info": gettext("Showing page _PAGE_ of _PAGES_"),
                "infoEmpty": gettext("No records available"),
                "infoFiltered": gettext("(filtered from _MAX_ total records)"),
                "search": gettext("Search:"),
                "Previous": gettext("Previous"),
                "next": gettext("Next"),
                "paginate": {
                    "next": gettext("Next"),
                    "previous": gettext("Previous"),
                }
            }
        });
    }

    $('.slice-institutions').on('click', '.get-filtered', function (e) {
        if (! $.fn.dataTable.isDataTable( '#list' ) ) {
            draw_election_list();
        }
        var url = $(this).data('url');
        var institution_name = $(this).parents('tr').data('institution');
        var election_type = $(this).data('type');
        table.clear();
        $.getJSON(url, function(data) {
            $.each( data.elections, function( i, item ) {
                started_at = (isNaN(Date.parse(item.started_at))) ? '' : new Date(item.started_at);
                ended_at = (isNaN(Date.parse(item.ended_at))) ? '' : new Date(item.ended_at);
                $('.modal-title').text(institution_name + ' - ' + election_type);
                table.row.add([
                    '' + item.name + '',
                    started_at,
                    ended_at
                ]).draw();
            });
        });
    });

    $('select[name="year"]').on('change', function() {
        var url = $('.get-by-year').data('url');
        var year = $('select[name=year] option:selected').val();
        $('.slice-institutions').load($('.slice-institutions').attr('data-url')+ year);
    });

})
<commit_msg>Change js Date usage<commit_after>$("document").ready(function(){

	$("form.add_inst_email").submit(function(event) {
        event.preventDefault();
        event.stopImmediatePropagation();
        var form = $(this);
        var msg = gettext('Are you sure you want to add this e-mail as an election admin?');
        if ($(this).attr('id') == 'add_inst_mngt_email'){
            msg = gettext('Are you sure you want to add this e-mail as an institution admin?')
        }
		if (confirm(msg)){
            var email = form.find('input[type=email]').val();
            var url = form.attr('action');
            $.ajax({
                type: "POST",
                url: url,
                data: {'email': email},
                success: function (data) {
                    form.parents('div.div_form').removeClass('has-error');
                    form.parents('div.div_form').addClass('has-success');
                    form.parents('div.div_form').find('span.add_field_result').text(gettext('Email successfully saved.'));
                    $('#institution_users').load($('#institution_users').attr('data-url'));
                },
                error: function (error) {
                    form.parents('div.div_form').removeClass('has-success');
                    form.parents('div.div_form').addClass('has-error');
                    form.parents('div.div_form').find('span.add_field_result').text(gettext('Please, correct the provided value'));
                }
            });
            form.find('input[type=email]').val('');
		}
		return false;
	});

    $('.remove_institution_user').click(function(event) {
        event.preventDefault();
        event.stopImmediatePropagation();
		if (confirm(gettext('Are you sure you want to delete this user?'))){
            var url = $(this).attr('href');
            var element = $(this);
            $.ajax({
                type: "POST",
                url: url,
                success: function (data) {
                    element.parents('tr').remove();
                },
                error: function (error) {
                    form.parents('div.div_form').addClass('has-error');
                    form.parents('div.div_form').find('span.add_field_result').text(gettext('Please, correct the provided value'));
                }
            });
		}
		return false;
    });

    $('#inst_details').on('click', '#edit_inst_button', function(event){
        $('#readonly_inst').addClass('hidden');
        $('#edit_inst').addClass('panel-body');
        $('#edit_inst').removeClass('hidden');
    });

    $('#inst_details').on('click', '#save_inst_data', function(event){
        var url = $('#form_edit_inst').attr('action');
        var inst_data = {}
        $('p.inst_data').each(function(){
            inst_data[$(this).children('.form-control').attr('name')] = $(this).children('.form-control').val();
        });
        $.ajax({
            type: "POST",
            url: url,
            data: inst_data,
            success: function (data) {
                $('#inst_details').load($('#inst_details').attr('data-url'));
            },
            error: function (error) {

            }

        });
        return false;
    });

    $("#institution_users").on("click", ".date_expires_at", function(){
        $(".date_expires_at").datepicker({
        format: "dd/mm/yyyy",
        startDate: "now",
        autoclose: true,
        todayHighlight: true
        })
        .on('changeDate', function(e){

            var expires_at = $(this);
            var expires_at_text = expires_at.parent().children('.date');
            var url= expires_at.data('url');

            data = {
                'expires_at' : expires_at.datepicker('getFormattedDate'),
            }

            $.ajax({
                type: "POST",
                url: url,
                dataType: "json",
                data: data,

                success: function (data) {

                    expires_at
                        .removeClass('text-danger')
                        .addClass('text-success');

                    expires_at_text
                        .text(expires_at.datepicker('getFormattedDate'))
                        .removeClass('text-danger')
                        .addClass('text-success');
                },

                error: function (error) {

                    expires_at
                        .removeClass('text-danger')
                        .addClass('text-danger');

                    expires_at_text
                        .removeClass('text-danger')
                        .addClass('text-danger');
                },
            });
        });
    });

    var table;
    function draw_election_list () {
        table = $('#list').DataTable({
            "language": {
                "lengthMenu": gettext("Display _MENU_ records per page"),
                "zeroRecords": gettext("Nothing found - sorry"),
                "info": gettext("Showing page _PAGE_ of _PAGES_"),
                "infoEmpty": gettext("No records available"),
                "infoFiltered": gettext("(filtered from _MAX_ total records)"),
                "search": gettext("Search:"),
                "Previous": gettext("Previous"),
                "next": gettext("Next"),
                "paginate": {
                    "next": gettext("Next"),
                    "previous": gettext("Previous"),
                }
            }
        });
    }

    $('.slice-institutions').on('click', '.get-filtered', function (e) {
        if (! $.fn.dataTable.isDataTable( '#list' ) ) {
            draw_election_list();
        }
        var url = $(this).data('url');
        var institution_name = $(this).parents('tr').data('institution');
        var election_type = $(this).data('type');
        table.clear();
        $.getJSON(url, function(data) {
            $.each( data.elections, function( i, item ) {
                if (isNaN(Date.parse(item.started_at))) {
                    started_at = '';
                } else {
                    d = new Date(item.started_at);
                    started_at = d.getDate() + '/' + (d.getMonth() + 1) + '/' + d.getFullYear() +
                    ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
                }
                if (isNaN(Date.parse(item.ended_at))) {
                    ended_at = '';
                } else {
                    d = new Date(item.ended_at);
                    ended_at = d.getDate() + '/' + (d.getMonth() + 1) + '/' + d.getFullYear() +
                    ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
                }

                $('.modal-title').text(institution_name + ' - ' + election_type);
                table.row.add([
                    '' + item.name + '',
                    started_at,
                    ended_at
                ]).draw();
            });
        });
    });

    $('select[name="year"]').on('change', function() {
        var url = $('.get-by-year').data('url');
        var year = $('select[name=year] option:selected').val();
        $('.slice-institutions').load($('.slice-institutions').attr('data-url')+ year);
    });

})
<|endoftext|>


<commit_before>import { Trans } from "@lingui/macro";
import { i18nMark } from "@lingui/react";

import browserInfo from "browser-info";
import classNames from "classnames";
import { Modal } from "reactjs-components";
import PropTypes from "prop-types";
import React from "react";
import { Icon } from "@dcos/ui-kit";
import { SystemIcons } from "@dcos/ui-kit/dist/packages/icons/dist/system-icons-enum";
import { iconSizeXs } from "@dcos/ui-kit/dist/packages/design-tokens/build/js/designTokens";

import ClickToSelect from "../ClickToSelect";
import MetadataStore from "../../stores/MetadataStore";
import ModalHeading from "../modals/ModalHeading";

const METHODS_TO_BIND = ["onClose"];
const osTypes = {
  Windows: "windows",
  "OS X": "darwin",
  Linux: "linux"
};

class CliInstallModal extends React.Component {
  constructor() {
    super(...arguments);

    let selectedOS = browserInfo().os;
    if (!Object.keys(osTypes).includes(selectedOS)) {
      selectedOS = "Linux";
    }

    this.state = { selectedOS };

    METHODS_TO_BIND.forEach(method => {
      this[method] = this[method].bind(this);
    });
  }

  handleSelectedOSChange(selectedOS) {
    this.setState({ selectedOS });
  }

  onClose() {
    this.props.onClose();
  }

  getSubHeader() {
    if (!this.props.subHeaderContent) {
      return false;
    }

    return (

        {this.props.subHeaderContent}

    );
  }

  getCliInstructions() {
    const hostname = global.location.hostname;
    const protocol = global.location.protocol.replace(/[^\w]/g, "");
    let port = "";
    if (global.location.port) {
      port = ":" + global.location.port;
    }
    const clusterUrl = `${protocol}://${hostname}${port}`;
    const { selectedOS } = this.state;

    const downloadUrl = `https://downloads.dcos.io/binaries/cli/${
      osTypes[selectedOS]
    }/x86-64/latest/dcos`;
    if (selectedOS === "Windows") {
      return this.getWindowsInstallInstruction(clusterUrl, downloadUrl);
    }

    const instructions = [
      `[ -d /usr/local/bin ] || sudo mkdir -p /usr/local/bin`,
      `curl ${downloadUrl} -o dcos`,
      `sudo mv dcos /usr/local/bin`,
      `sudo chmod +x /usr/local/bin/dcos`,
      `dcos cluster setup ${clusterUrl}`,
      `dcos`
    ].filter(instruction => instruction !== undefined);

    return (

        <Trans render="p" className="short-bottom">
          Copy and paste the code snippet into the terminal:
        </Trans>

          <ClickToSelect>

              {instructions.join(" && \n")}

          </ClickToSelect>

    );
  }

  getWindowsInstallInstruction(clusterUrl, downloadUrl) {
    const steps = [
      `cd path/to/download/directory`,
      `dcos cluster setup ${clusterUrl}`,
      `dcos`
    ]
      .filter(instruction => instruction !== undefined)
      .map((instruction, index) => {
        const helpText =
          index === 0
            ? i18nMark("In Command Prompt, enter")
            : i18nMark("Enter");

        return (

            <Trans render="p" className="short-bottom" id={helpText} />

              <ClickToSelect>

                  {instruction}

              </ClickToSelect>

        );
      });

    return (

        <Trans render="li">
          Download and install:{" "}

            <Icon
              shape={SystemIcons.Download}
              size={iconSizeXs}
              color="currentColor"
            />
            Download dcos.exe
          .
        </Trans>
        {steps}

    );
  }

  getOSButtons() {
    const { selectedOS } = this.state;

    return Object.keys(osTypes).map((name, index) => {
      const classSet = classNames({
        "button button-outline": true,
        active: name === selectedOS
      });

      return (
        <button
          className={classSet}
          key={index}
          onClick={this.handleSelectedOSChange.bind(this, name)}
        >
          {name}
        </button>
      );
    });
  }

  getContent() {
    return (

        <Trans render="p">
          Choose your operating system and follow the instructions. For any
          issues or questions, please refer to our{" "}

            documentation
          .
        </Trans>

{this.getOSButtons()}

        {this.getCliInstructions()}

    );
  }

  render() {
    const { footer, open, showFooter, title } = this.props;
    const header = (
      <ModalHeading>
        <Trans id={title} render="span" />
      </ModalHeading>
    );

    return (
      <Modal
        header={header}
        footer={footer}
        modalClass="modal"
        onClose={this.onClose}
        open={open}
        showHeader={true}
        showFooter={showFooter}
        subHeader={this.getSubHeader()}
      >
        {this.getContent()}
      </Modal>
    );
  }
}

CliInstallModal.propTypes = {
  title: PropTypes.string.isRequired,
  subHeaderContent: PropTypes.string,
  showFooter: PropTypes.bool.isRequired,
  footer: PropTypes.node,
  onClose: PropTypes.func.isRequired
};

module.exports = CliInstallModal;
<commit_msg>fix(CliInstallModal): hard-code version<commit_after>import { Trans } from "@lingui/macro";
import { i18nMark } from "@lingui/react";

import browserInfo from "browser-info";
import classNames from "classnames";
import { Modal } from "reactjs-components";
import PropTypes from "prop-types";
import React from "react";
import { Icon } from "@dcos/ui-kit";
import { SystemIcons } from "@dcos/ui-kit/dist/packages/icons/dist/system-icons-enum";
import { iconSizeXs } from "@dcos/ui-kit/dist/packages/design-tokens/build/js/designTokens";

import ClickToSelect from "../ClickToSelect";
import MetadataStore from "../../stores/MetadataStore";
import ModalHeading from "../modals/ModalHeading";

const METHODS_TO_BIND = ["onClose"];
const osTypes = {
  Windows: "windows",
  "OS X": "darwin",
  Linux: "linux"
};

class CliInstallModal extends React.Component {
  constructor() {
    super(...arguments);

    let selectedOS = browserInfo().os;
    if (!Object.keys(osTypes).includes(selectedOS)) {
      selectedOS = "Linux";
    }

    this.state = { selectedOS };

    METHODS_TO_BIND.forEach(method => {
      this[method] = this[method].bind(this);
    });
  }

  handleSelectedOSChange(selectedOS) {
    this.setState({ selectedOS });
  }

  onClose() {
    this.props.onClose();
  }

  getSubHeader() {
    if (!this.props.subHeaderContent) {
      return false;
    }

    return (

        {this.props.subHeaderContent}

    );
  }

  getCliInstructions() {
    const hostname = global.location.hostname;
    const protocol = global.location.protocol.replace(/[^\w]/g, "");
    let port = "";
    if (global.location.port) {
      port = ":" + global.location.port;
    }
    const clusterUrl = `${protocol}://${hostname}${port}`;
    const { selectedOS } = this.state;

    const downloadUrl = `https://downloads.dcos.io/binaries/cli/${
      osTypes[selectedOS]
    }/x86-64/dcos-1.13/dcos`;
    if (selectedOS === "Windows") {
      return this.getWindowsInstallInstruction(clusterUrl, downloadUrl);
    }

    const instructions = [
      `[ -d /usr/local/bin ] || sudo mkdir -p /usr/local/bin`,
      `curl ${downloadUrl} -o dcos`,
      `sudo mv dcos /usr/local/bin`,
      `sudo chmod +x /usr/local/bin/dcos`,
      `dcos cluster setup ${clusterUrl}`,
      `dcos`
    ].filter(instruction => instruction !== undefined);

    return (

        <Trans render="p" className="short-bottom">
          Copy and paste the code snippet into the terminal:
        </Trans>

          <ClickToSelect>

              {instructions.join(" && \n")}

          </ClickToSelect>

    );
  }

  getWindowsInstallInstruction(clusterUrl, downloadUrl) {
    const steps = [
      `cd path/to/download/directory`,
      `dcos cluster setup ${clusterUrl}`,
      `dcos`
    ]
      .filter(instruction => instruction !== undefined)
      .map((instruction, index) => {
        const helpText =
          index === 0
            ? i18nMark("In Command Prompt, enter")
            : i18nMark("Enter");

        return (

            <Trans render="p" className="short-bottom" id={helpText} />

              <ClickToSelect>

                  {instruction}

              </ClickToSelect>

        );
      });

    return (

        <Trans render="li">
          Download and install:{" "}

            <Icon
              shape={SystemIcons.Download}
              size={iconSizeXs}
              color="currentColor"
            />
            Download dcos.exe
          .
        </Trans>
        {steps}

    );
  }

  getOSButtons() {
    const { selectedOS } = this.state;

    return Object.keys(osTypes).map((name, index) => {
      const classSet = classNames({
        "button button-outline": true,
        active: name === selectedOS
      });

      return (
        <button
          className={classSet}
          key={index}
          onClick={this.handleSelectedOSChange.bind(this, name)}
        >
          {name}
        </button>
      );
    });
  }

  getContent() {
    return (

        <Trans render="p">
          Choose your operating system and follow the instructions. For any
          issues or questions, please refer to our{" "}

            documentation
          .
        </Trans>

{this.getOSButtons()}

        {this.getCliInstructions()}

    );
  }

  render() {
    const { footer, open, showFooter, title } = this.props;
    const header = (
      <ModalHeading>
        <Trans id={title} render="span" />
      </ModalHeading>
    );

    return (
      <Modal
        header={header}
        footer={footer}
        modalClass="modal"
        onClose={this.onClose}
        open={open}
        showHeader={true}
        showFooter={showFooter}
        subHeader={this.getSubHeader()}
      >
        {this.getContent()}
      </Modal>
    );
  }
}

CliInstallModal.propTypes = {
  title: PropTypes.string.isRequired,
  subHeaderContent: PropTypes.string,
  showFooter: PropTypes.bool.isRequired,
  footer: PropTypes.node,
  onClose: PropTypes.func.isRequired
};

module.exports = CliInstallModal;
<|endoftext|>


<commit_before>const crypto = require('crypto');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const OpenStreetMapStrategy = require('passport-openstreetmap').Strategy;

const User = require('./models/user');

function userSetup(app, csrfProtection) {
  // Passport module setup
  app.use(passport.initialize());
  app.use(passport.session());
  if (process.env.OPENSTREETMAP_CONSUMER_KEY && process.env.OPENSTREETMAP_CONSUMER_SECRET) {
    passport.use(
      new OpenStreetMapStrategy({
        consumerKey: process.env.OPENSTREETMAP_CONSUMER_KEY,
        consumerSecret: process.env.OPENSTREETMAP_CONSUMER_SECRET,
        callbackURL: "http://names.georeactor.com/auth/openstreetmap/callback"
      }, (token, tokenSecret, profile, done) => {
        var osm_user_name = profile._xml2js.user['@'].display_name;
        console.log(osm_user_name);
        User.find({ osm_id: osm_user_name }, (err, user) => {
          if (err) {
            return done(err, null);
          }
          var u = new User({
            osm_id: osm_user_name,
            user_id: osm_user_name,
            name: 'unset'
          });
          u.save((err) => {
            done(err, u);
          });
        });
      })
    );
  }

  passport.serializeUser(function(user, done) {
    done(null, user);
  });
  passport.deserializeUser(function(obj, done) {
    done(null, obj);
  });

  // user registration form
  app.get('/register', csrfProtection, (req, res) => {
    res.render('register', {
      user: req.user,
      csrfToken: req.csrfToken()
    });
  });

  // user login form
  app.get('/login', csrfProtection, (req, res) => {
    res.render('login', {
      csrfToken: req.csrfToken()
    });
  });

  app.post('/login', csrfProtection, (req, res) => {
    res.redirect('/projects');
  });

  app.get('/logout', (req, res) => {
    req.logout();
    res.redirect('/?loggedout');
  });

  // respond to user POST
  app.post('/register', csrfProtection, (req, res) => {
    if (!req.user) {
      return res.redirect('/login');
    }

    User.findById(req.user._id, (err, u) => {
      if (err) {
        return res.json(err);
      }

      u.name = req.body.name;
      u.preferLanguage = req.body.preferLanguage;
      u.readLanguages = req.body.readLanguages;
      u.writeLanguages = req.body.writeLanguages;
      u.save((err) => {
        if (err) {
          return res.json(err);
        }
        res.redirect('/projects');
      });
    });
  });

  // OSM OAuth
  app.get('/auth/openstreetmap', passport.authenticate('openstreetmap'));
  app.get('/auth/openstreetmap/callback',
    passport.authenticate('openstreetmap', { failureRedirect: '/login?fail=true' }), (req, res) => {
      if (req.user.name === 'unset') {
        res.redirect('/register');
      } else {
        res.redirect('/projects');
      }
    });
}

module.exports = userSetup;
<commit_msg>fix web login<commit_after>const crypto = require('crypto');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const OpenStreetMapStrategy = require('passport-openstreetmap').Strategy;

const User = require('./models/user');

function userSetup(app, csrfProtection) {
  // Passport module setup
  app.use(passport.initialize());
  app.use(passport.session());
  if (process.env.OPENSTREETMAP_CONSUMER_KEY && process.env.OPENSTREETMAP_CONSUMER_SECRET) {
    passport.use(
      new OpenStreetMapStrategy({
        consumerKey: process.env.OPENSTREETMAP_CONSUMER_KEY,
        consumerSecret: process.env.OPENSTREETMAP_CONSUMER_SECRET,
        callbackURL: "http://names.georeactor.com/auth/openstreetmap/callback"
      }, (token, tokenSecret, profile, done) => {
        var osm_user_name = profile._xml2js.user['@'].display_name;
        User.find({ osm_id: osm_user_name }, (err, user) => {
          if (err) {
            return done(err, null);
          }
          if (user) {
            return done(err, user);
          }
          var u = new User({
            osm_id: osm_user_name,
            user_id: osm_user_name,
            name: 'unset'
          });
          u.save((err) => {
            done(err, u);
          });
        });
      })
    );
  }

  passport.serializeUser(function(user, done) {
    done(null, user);
  });
  passport.deserializeUser(function(obj, done) {
    done(null, obj);
  });

  // user registration form
  app.get('/register', csrfProtection, (req, res) => {
    res.render('register', {
      user: req.user,
      csrfToken: req.csrfToken()
    });
  });

  // user login form
  app.get('/login', csrfProtection, (req, res) => {
    res.render('login', {
      csrfToken: req.csrfToken()
    });
  });

  app.post('/login', csrfProtection, (req, res) => {
    res.redirect('/projects');
  });

  app.get('/logout', (req, res) => {
    req.logout();
    res.redirect('/?loggedout');
  });

  // respond to user POST
  app.post('/register', csrfProtection, (req, res) => {
    if (!req.user) {
      return res.redirect('/login');
    }

    User.findById(req.user._id, (err, u) => {
      if (err) {
        return res.json(err);
      }

      u.name = req.body.name;
      u.preferLanguage = req.body.preferLanguage;
      u.readLanguages = req.body.readLanguages;
      u.writeLanguages = req.body.writeLanguages;
      u.save((err) => {
        if (err) {
          return res.json(err);
        }
        res.redirect('/projects');
      });
    });
  });

  // OSM OAuth
  app.get('/auth/openstreetmap', passport.authenticate('openstreetmap'));
  app.get('/auth/openstreetmap/callback',
    passport.authenticate('openstreetmap', { failureRedirect: '/login?fail=true' }), (req, res) => {
      if (req.user.name === 'unset') {
        res.redirect('/register');
      } else {
        res.redirect('/projects');
      }
    });
}

module.exports = userSetup;
<|endoftext|>


<commit_before>import React from 'react';
import { expect } from 'chai';
import { mount } from 'enzyme';
import Incident from '../js/components/Incident';
import styles from '../js/components/Incident.css';
const moment = require('moment');

describe('<Incident />', function () {
  const incident = {
    id: '23103810',
    date: moment('2016-02-03'),
    address: '530 S. State',
    description: 'Hello world!'
  };

  it('should initially not be showing text', function () {
    const wrapper = mount(<Incident incident={incident} />);
    expect(wrapper.state().showText).to.eql(false);
  });

  it('should have a div with incident class', function () {
    const wrapper = mount(<Incident incident={incident} />);
    expect(styles.incident).to.not.be.empty;
    expect(wrapper.closest(`div.${styles.incident}`)).to.have.length(1);
  });

  it('should change the text state on clicking the GridTile', function () {
    const wrapper = mount(<Incident incident={incident} />);
    wrapper.find('GridTile').simulate('click');
    expect(wrapper.state().showText).to.eql(true);
  });

  it('should change the text state back to default on clicking the textual incident', function () {
    const wrapper = mount(<Incident incident={incident} />);
    wrapper.find('GridTile').simulate('click');
    wrapper.find(`.${styles.incidentInfo}`).simulate('click');
    expect(wrapper.state().showText).to.eql(false);
  });
});
<commit_msg>Add test for friendly incident date<commit_after>import React from 'react';
import { expect } from 'chai';
import { mount } from 'enzyme';
import Incident from '../js/components/Incident';
import styles from '../js/components/Incident.css';
const moment = require('moment');

describe('<Incident />', function () {
  const incident = {
    id: '23103810',
    date: moment('2016-02-03'),
    address: '530 S. State',
    description: 'Hello world!'
  };

  it('should initially not be showing text', function () {
    const wrapper = mount(<Incident incident={incident} />);
    expect(wrapper.state().showText).to.eql(false);
  });

  it('should have a div with incident class', function () {
    const wrapper = mount(<Incident incident={incident} />);
    expect(styles.incident).to.not.be.empty;
    expect(wrapper.closest(`div.${styles.incident}`)).to.have.length(1);
  });

  it('should change the text state on clicking the GridTile', function () {
    const wrapper = mount(<Incident incident={incident} />);
    wrapper.find('GridTile').simulate('click');
    expect(wrapper.state().showText).to.eql(true);
  });

  it('should change the text state back to default on clicking the textual incident', function () {
    const wrapper = mount(<Incident incident={incident} />);
    wrapper.find('GridTile').simulate('click');
    expect(wrapper.state().showText).to.eql(true);
    wrapper.find(`.${styles.incidentInfo}`).simulate('click');
    expect(wrapper.state().showText).to.eql(false);
  });

  it('should contain friendly date', function () {
    const wrapper = mount(<Incident incident={incident} />);
    wrapper.find('GridTile').simulate('click');
    expect(wrapper.find(`.${styles.incidentInfo}`).text()).to.contain('Wed, Feb 3, 2016 12:00 AM');
  });
});
<|endoftext|>


<commit_before>app.controller('fichasCtrl', function($scope, $rootScope, $route, $location, $timeout, $document, SweetAlert, $mdDialog, Fichas){
	// Inicializar variables utilizadas en todo el codigo y que provienen de la sesion del usuario
	$rootScope.currentRoute='Tus Fichas';
	$scope.fichas = [];
	Fichas.all($rootScope.user.id).then(function(fichas) {
		$scope.fichas = fichas;
		console.log(fichas)
	});

	$scope.buscar = function(ev) {
		Fichas.search($scope.busqueda.ficha)
		.then(function(fichas) {
			$scope.fichas = fichas;
		})
		.catch(function (error) {
			SweetAlert.swal("Ooops..", "Ocurrio un error: "+error.data, "error");
		});
	};

	$scope.borrar = function(ficha) {
		var ficha = ficha;
		SweetAlert.swal({
			title: "Estas seguro de querer eliminar a "+ficha.nombre+"?",
			text: "No vas a poder recuperarlo",
			type: "warning",
			showCancelButton: true,
			confirmButtonColor: "#692B8D",
			confirmButtonText: "Si, eliminalo!",
			closeOnConfirm: false
		},function(isConfirmed) {
			if(isConfirmed){
				Fichas.delete(ficha.id).then(function (s) {
					SweetAlert.swal({
						title: "Eliminado!",
						text: ''+ficha.nombre+' ha sido eliminado correctamente',
						type: "success",
						showCancelButton: false,
						confirmButtonColor: "#692B8D",
						confirmButtonText: "Ok!",
						closeOnConfirm: true
					},
					function(){
						console.log("EXITO");
						$route.reload();
					});
		        })
		        .catch(function (error) {
		        	SweetAlert.swal("Ooops..", "Ocurrio un error: "+error.data, "error");
		        });
			}
		});
	}

	//Modal
	$scope.showAgregarFicha = function(ev) {
		$mdDialog.show({
			controller: function($scope){
				$scope.ficha = {};
				$scope.ficha.materiales = [];
				$scope.ficha.areadedesarrollo = "corporalidad";
				$scope.ficha.foto = 'img/fpo_avatar_multi.png';
				// Modal Actions
				$scope.cancel = function(){
					$mdDialog.cancel();
				};

				$scope.save = function(){

					$mdDialog.hide($scope.ficha);
				};

				$scope.add = function($event){
					$event.preventDefault();
				   	$event.stopPropagation();
					$scope.ficha.materiales.push({material: ''});
				}

				$scope.del = function(i, $event){
					$event.preventDefault();
				   	$event.stopPropagation();
					$scope.ficha.materiales.splice(i,1);
				}
			},
			templateUrl: '/dialogs/agregarFichaReme.html',
			parent: angular.element(document.body),
			targetEvent: ev,
			clickOutsideToClose:true,
			fullscreen: 'false' // Only for -xs, -sm breakpoints.
		})
		.then(function(ficha) {
			ficha.seccion = $rootScope.user.seccion;
			var materiales = "";
			ficha.materiales.forEach(function(material) {
				materiales += material.material +'
';
			});
			ficha.materiales = materiales;
			ficha.autor = $rootScope.user.id;

			console.log(ficha);
			Fichas.new(ficha).then(function (ficha) {
				SweetAlert.swal({
					title: "Exito!",
					text: ''+ficha.nombreactividad+' Fue Agregado Correctamente',
					type: "success",
					showCancelButton: false,
					confirmButtonColor: "#692B8D",
					confirmButtonText: "Ok!",
					closeOnConfirm: true
				},
				function(){
					console.log("EXITO");
					$route.reload();
				});
	        })
	        .catch(function (error) {
	        	console.log(error);
	        	SweetAlert.swal("Ooops..", "Ocurrio un error: "+error.data, "error");
	        });
		}, function() {

		});

	}//end modal

	$scope.parseArea = function(seccion, area){
		var nuevaarea = "";
		switch (seccion) {
			case 'manada':
				switch(area){
					case "corporalidad":
						nuevaarea = "Bagheera (Corporalidad)";
					case "creatividad":
						nuevaarea = "Kaa (Creatividad)";
					case "caracter":
						nuevaarea = "Baloo (Carácter)";
					case "afectividad":
						nuevaarea = "Rikki-Tikki-Tavi (Afectividad)";
					case "sociabilidad":
						nuevaarea = "Kotick (Sociabilidad)";
					case "espiritualidad":
						nuevaarea = "Francisco de Asís (Espiritualidad)";
				};
				break;
			case 'tropa':
				switch(area){
					case "corporalidad":
						nuevaarea = "Pez (Corporalidad)";
					case "creatividad":
						nuevaarea = "Ave (Creatividad)";
					case "caracter":
						nuevaarea = "Tortuga (Carácter)";
					case "afectividad":
						nuevaarea = "Flor (Afectividad)";
					case "sociabilidad":
						nuevaarea = "Abeja (Sociabilidad)";
					case "espiritualidad":
						nuevaarea = "Árbol (Espiritualidad)";
				};
				break;
			case 'comunidad':
				switch(area){
					case "corporalidad":
						nuevaarea = "Delfín (Corporalidad)";
					case "creatividad":
						nuevaarea = "Ave (Creatividad)";
					case "caracter":
						nuevaarea = "Caballo (Carácter)";
					case "afectividad":
						nuevaarea = "Flor (Afectividad)";
					case "sociabilidad":
						nuevaarea = "Abeja (Sociabilidad)";
					case "espiritualidad":
						nuevaarea = "Árbol (Espiritualidad)";
				};
				break;
			case 'clan':
				switch(area){
					case "corporalidad":
						nuevaarea = "Corporalidad";
					case "creatividad":
						nuevaarea = "Creatividad";
					case "caracter":
						nuevaarea = "Carácter";
					case "afectividad":
						nuevaarea = "Afectividad";
					case "sociabilidad":
						nuevaarea = "Sociabilidad";
					case "espiritualidad":
						nuevaarea = "Espiritualidad";
				};
				break;

			return nuevaarea
		}

	};//end parseArea
});//end fichasCtrl

app.controller('fichaCtrl',function($scope,$rootScope, $route, $location, SweetAlert, $routeParams, Fichas){

	Fichas.get($routeParams.id).then(function(ficha) {
		// body...
		$scope.ficha = ficha[0];
		console.log($scope.ficha);
		$rootScope.currentRoute=$scope.ficha.nombreactividad;
	});
	// console.log($scope.ficha);

	$scope.save = function(){
		if ($scope.ficha.myImage == 'img/fpo_avatar_multi.png') {
			$scope.ficha.foto = 'img/fpo_avatar_multi.png';
		}
		// 'Exito', ''+ficha.nombre+' Fue Agregad'+s+' Correctamente'
		$scope.ficha.user_id = $rootScope.user.id
		Fichas.update($scope.ficha).then(function (ficha) {
			SweetAlert.swal({
			   title: "Exito!",
			   text: ''+$scope.ficha.nombreactividad+' Fue Editado Correctamente',
			   type: "success",
			   showCancelButton: false,
			   confirmButtonColor: "#692B8D",
			   confirmButtonText: "Ok!",
			   closeOnConfirm: true},
			function(){
				$location.path('/ficha/'+$scope.ficha.id);
			});
        })
        .catch(function (error) {
        	console.log(error)
        	SweetAlert.swal("Ooops..", "Ocurrio un error: "+error.data, "error");
        });
	};
}); // end fichaCtrl

<commit_msg>Update fichasRemeCtrls.js<commit_after>app.controller('fichasCtrl', function($scope, $rootScope, $route, $location, $timeout, $document, SweetAlert, $mdDialog, Fichas){
	// Inicializar variables utilizadas en todo el codigo y que provienen de la sesion del usuario
	$rootScope.currentRoute='Tus Fichas';
	$scope.fichas = [];
	Fichas.all($rootScope.user.id).then(function(fichas) {
		$scope.fichas = fichas;
		console.log(fichas)
	});

	$scope.buscar = function(ev) {
		Fichas.search($scope.busqueda.ficha)
		.then(function(fichas) {
			$scope.fichas = fichas;
		})
		.catch(function (error) {
			SweetAlert.swal("Ooops..", "Ocurrio un error: "+error.data, "error");
		});
	};

	$scope.borrar = function(ficha) {
		var ficha = ficha;
		SweetAlert.swal({
			title: "Estas seguro de querer eliminar a "+ficha.nombre+"?",
			text: "No vas a poder recuperarlo",
			type: "warning",
			showCancelButton: true,
			confirmButtonColor: "#692B8D",
			confirmButtonText: "Si, eliminalo!",
			closeOnConfirm: false
		},function(isConfirmed) {
			if(isConfirmed){
				Fichas.delete(ficha.id).then(function (s) {
					SweetAlert.swal({
						title: "Eliminado!",
						text: ''+ficha.nombre+' ha sido eliminado correctamente',
						type: "success",
						showCancelButton: false,
						confirmButtonColor: "#692B8D",
						confirmButtonText: "Ok!",
						closeOnConfirm: true
					},
					function(){
						console.log("EXITO");
						$route.reload();
					});
		        })
		        .catch(function (error) {
		        	SweetAlert.swal("Ooops..", "Ocurrio un error: "+error.data, "error");
		        });
			}
		});
	}

	//Modal
	$scope.showAgregarFicha = function(ev) {
		$mdDialog.show({
			controller: function($scope){
				$scope.ficha = {};
				$scope.ficha.materiales = [];
				$scope.ficha.areadedesarrollo = "corporalidad";
				$scope.ficha.foto = 'img/fpo_avatar_multi.png';
				// Modal Actions
				$scope.cancel = function(){
					$mdDialog.cancel();
				};

				$scope.save = function(){

					$mdDialog.hide($scope.ficha);
				};

				$scope.add = function($event){
					$event.preventDefault();
				   	$event.stopPropagation();
					$scope.ficha.materiales.push({material: ''});
				}

				$scope.del = function(i, $event){
					$event.preventDefault();
				   	$event.stopPropagation();
					$scope.ficha.materiales.splice(i,1);
				}
			},
			templateUrl: '/dialogs/agregarFichaReme.html',
			parent: angular.element(document.body),
			targetEvent: ev,
			clickOutsideToClose:true,
			fullscreen: 'false' // Only for -xs, -sm breakpoints.
		})
		.then(function(ficha) {
			ficha.seccion = $rootScope.user.seccion;
			var materiales = "";
			ficha.materiales.forEach(function(material) {
				materiales += material.material +'
';
			});
			ficha.materiales = materiales;
			ficha.autor = $rootScope.user.id;

			console.log(ficha);
			Fichas.new(ficha).then(function (ficha) {
				SweetAlert.swal({
					title: "Exito!",
					text: ''+ficha.nombreactividad+' Fue Agregado Correctamente',
					type: "success",
					showCancelButton: false,
					confirmButtonColor: "#692B8D",
					confirmButtonText: "Ok!",
					closeOnConfirm: true
				},
				function(){
					console.log("EXITO");
					$route.reload();
				});
	        })
	        .catch(function (error) {
	        	console.log(error);
	        	SweetAlert.swal("Ooops..", "Ocurrio un error: "+error.data, "error");
	        });
		}, function() {

		});

	}//end modal

	$scope.parseArea = function(seccion, area){
		var nuevaarea = "";
		switch (seccion) {
			case 'manada':
				switch(area){
					case "corporalidad":
						nuevaarea = "Bagheera (Corporalidad)";
					case "creatividad":
						nuevaarea = "Kaa (Creatividad)";
					case "caracter":
						nuevaarea = "Baloo (Carácter)";
					case "afectividad":
						nuevaarea = "Rikki-Tikki-Tavi (Afectividad)";
					case "sociabilidad":
						nuevaarea = "Kotick (Sociabilidad)";
					case "espiritualidad":
						nuevaarea = "Francisco de Asís (Espiritualidad)";
				};
				break;
			case 'tropa':
				switch(area){
					case "corporalidad":
						nuevaarea = "Pez (Corporalidad)";
					case "creatividad":
						nuevaarea = "Ave (Creatividad)";
					case "caracter":
						nuevaarea = "Tortuga (Carácter)";
					case "afectividad":
						nuevaarea = "Flor (Afectividad)";
					case "sociabilidad":
						nuevaarea = "Abeja (Sociabilidad)";
					case "espiritualidad":
						nuevaarea = "Árbol (Espiritualidad)";
				};
				break;
			case 'comunidad':
				switch(area){
					case "corporalidad":
						nuevaarea = "Delfín (Corporalidad)";
					case "creatividad":
						nuevaarea = "Ave (Creatividad)";
					case "caracter":
						nuevaarea = "Caballo (Carácter)";
					case "afectividad":
						nuevaarea = "Flor (Afectividad)";
					case "sociabilidad":
						nuevaarea = "Abeja (Sociabilidad)";
					case "espiritualidad":
						nuevaarea = "Árbol (Espiritualidad)";
				};
				break;
			case 'clan':
				switch(area){
					case "corporalidad":
						nuevaarea = "Corporalidad";
					case "creatividad":
						nuevaarea = "Creatividad";
					case "caracter":
						nuevaarea = "Carácter";
					case "afectividad":
						nuevaarea = "Afectividad";
					case "sociabilidad":
						nuevaarea = "Sociabilidad";
					case "espiritualidad":
						nuevaarea = "Espiritualidad";
				};
				break;

			return nuevaarea;
		}

	};//end parseArea
});//end fichasCtrl

app.controller('fichaCtrl',function($scope,$rootScope, $route, $location, SweetAlert, $routeParams, Fichas){

	Fichas.get($routeParams.id).then(function(ficha) {
		// body...
		$scope.ficha = ficha[0];
		console.log($scope.ficha);
		$rootScope.currentRoute=$scope.ficha.nombreactividad;
	});
	// console.log($scope.ficha);

	$scope.save = function(){
		if ($scope.ficha.myImage == 'img/fpo_avatar_multi.png') {
			$scope.ficha.foto = 'img/fpo_avatar_multi.png';
		}
		// 'Exito', ''+ficha.nombre+' Fue Agregad'+s+' Correctamente'
		$scope.ficha.user_id = $rootScope.user.id
		Fichas.update($scope.ficha).then(function (ficha) {
			SweetAlert.swal({
			   title: "Exito!",
			   text: ''+$scope.ficha.nombreactividad+' Fue Editado Correctamente',
			   type: "success",
			   showCancelButton: false,
			   confirmButtonColor: "#692B8D",
			   confirmButtonText: "Ok!",
			   closeOnConfirm: true},
			function(){
				$location.path('/ficha/'+$scope.ficha.id);
			});
        })
        .catch(function (error) {
        	console.log(error)
        	SweetAlert.swal("Ooops..", "Ocurrio un error: "+error.data, "error");
        });
	};
}); // end fichaCtrl

<|endoftext|>


<commit_before>import React from 'react';
import { shallow } from 'enzyme';
import Parallax from '../src/Parallax';
import mocker from './helper/mocker';

describe('<Parallax />', () => {
  let wrapper;
  const parallaxMock = jest.fn();
  const restore = mocker('parallax', parallaxMock);

  afterAll(() => {
    restore();
  });

  test('should render a Parallax', () => {
    wrapper = shallow(<Parallax />);
    expect(wrapper).toMatchSnapshot();
  });
});
<commit_msg>Modifying spec accordingly<commit_after>import React from 'react';
import { shallow, mount } from 'enzyme';
import Parallax from '../src/Parallax';
import mocker from './helper/new-mocker';

describe('<Parallax />', () => {
  test('should render a Parallax', () => {
    expect(shallow(<Parallax />)).toMatchSnapshot();
  });

  describe('initialises', () => {
    const parallaxInitMock = jest.fn();
    const parallaxInstanceDestroyMock = jest.fn();
    const parallaxMock = {
      init: (el, options) => {
        parallaxInitMock(options);
        return {
          destroy: parallaxInstanceDestroyMock
        };
      }
    };
    const restore = mocker('Parallax', parallaxMock);

    beforeEach(() => {
      parallaxInitMock.mockClear();
      parallaxInstanceDestroyMock.mockClear();
    });

    afterAll(() => {
      restore();
    });

    test('calls Parallax', () => {
      mount(<Parallax />);

      expect(parallaxInitMock).toHaveBeenCalledTimes(1);
    });

    test('should call Parallax with the given options', () => {
      const options = { responsiveThreshold: 200 };

      mount(<Parallax options={options} />);
      expect(parallaxInitMock).toHaveBeenCalledWith(options);
    });
  });
});
<|endoftext|>


<commit_before>var app = angular.module("QuickInbox", []);

app.controller("AppCtrl", function($scope, $http, $timeout, $compile, QuickInboxService) {

    $scope.feedbacks = [];
    var poll_server = true;

    function feed_request() {
        if(poll_server) {
            $.ajax({
                type: 'GET'
              , dataType: 'json'
              , async: false
              , url: '/hosted/quick_inbox'
              , success: function(data) {
                    $scope.feedbacks = data;
                    $scope.$apply($scope.feedbacks);
                    setTimeout(function() {
                        console.log(poll_server);
                        feed_request();
                        QuickInboxService.info_block_behavior();
                        $('.widget-list').jScrollPane();
                    }, 10000);
                }
            });
        }

        $('#quickInboxWidget').unbind('mouseenter.widget').bind('mouseenter.widget', function() {
            poll_server = false;
            console.log("inbox polling is stopping");
        });

        $('#quickInboxWidget').unbind('mouseleave.widget').bind('mouseleave.widget', function() {
            poll_server = true;
            feed_request();
            console.log("inbox polling is starting");
        });

    }

    feed_request();

    $scope.publish = function(id) {
        console.log("Publishing! " + id);
    }

    $scope.feature = function(id) {
        console.log("Featuring! " + id);
    }

    $scope.delete = function(id) {
        console.log('Deleting Feedback id of ' + id);
    }

    $scope.info_block = function(data) {

        var template, subcontent_check = data['subcontent']; ;

        if(subcontent_check) {
            template = '
';
            template += $scope.metadata_block(data);
            template += $scope.media_block(data);
            template += '
';
        }

        return template;
    }

    $scope.metadata_block = function(data) {
        if(data.hasOwnProperty('metadata')) {
            var meta = data['metadata'];

            var template = '
'
            for(var i=0; i < meta.length; i++) {
                template += '
'
                template += '
' + meta[i].key + ' : ' + meta[i].value + '
'
                template += '
'
            }
            template += '
';
            return template;
        }
    }

    $scope.media_block = function(data) {
        if(data.hasOwnProperty('media')) {
            var meta = data['media'];

            var template = '
';
            for(var i=0; i < meta.length; i++) {

                template += '
';

                if(meta[i].type == 'video') {
                    template += '

';
                }

                template += '
x
';
                //this should refer to pic or youtube link location...
                template += '

';
                template += '
';

            }
            template += '
';

            return template;
        }

    }

});

app.service('QuickInboxService', function($rootScope) {

    var shared_service = {};
    shared_service.message;

    shared_service.info_block_behavior = function(cb) {
        $('.delete-block').bind('click', function(e) {
            console.log('Delete Media Id: ' + $(this).attr('mid'));
        })
    }

    return shared_service;
});
<commit_msg>wwqqwq<commit_after>var app = angular.module("QuickInbox", []);

app.controller("AppCtrl", function($scope, $http, $timeout, $compile, QuickInboxService) {

    $scope.feedbacks = [];
    var poll_server = true;

    function feed_request() {
        if(poll_server) {
            $.ajax({
                type: 'GET'
              , dataType: 'json'
              , async: false
              , url: '/hosted/quick_inbox'
              , success: function(data) {
                    $scope.feedbacks = data;
                    $scope.$apply($scope.feedbacks);
                    setTimeout(function() {
                        feed_request();
                        QuickInboxService.info_block_behavior();
                        $('.widget-list').jScrollPane();
                    }, 10000);
                }
            });
        }

        $('#quickInboxWidget').unbind('mouseenter.widget').bind('mouseenter.widget', function() {
            poll_server = false;
            console.log("inbox polling is stopping");
        });

        $('#quickInboxWidget').unbind('mouseleave.widget').bind('mouseleave.widget', function() {
            poll_server = true;
            feed_request();
            console.log("inbox polling is starting");
        });

    }

    feed_request();

    $scope.publish = function(id) {
        console.log("Publishing! " + id);
    }

    $scope.feature = function(id) {
        console.log("Featuring! " + id);
    }

    $scope.delete = function(id) {
        console.log('Deleting Feedback id of ' + id);
    }

    $scope.info_block = function(data) {

        var template, subcontent_check = data['subcontent']; ;

        if(subcontent_check) {
            template = '
';
            template += $scope.metadata_block(data);
            template += $scope.media_block(data);
            template += '
';
        }

        return template;
    }

    $scope.metadata_block = function(data) {
        if(data.hasOwnProperty('metadata')) {
            var meta = data['metadata'];

            var template = '
'
            for(var i=0; i < meta.length; i++) {
                template += '
'
                template += '
' + meta[i].key + ' : ' + meta[i].value + '
'
                template += '
'
            }
            template += '
';
            return template;
        }
    }

    $scope.media_block = function(data) {
        if(data.hasOwnProperty('media')) {
            var meta = data['media'];

            var template = '
';
            for(var i=0; i < meta.length; i++) {

                template += '
';

                if(meta[i].type == 'video') {
                    template += '

';
                }

                template += '
x
';
                //this should refer to pic or youtube link location...
                template += '

';
                template += '
';

            }
            template += '
';

            return template;
        }

    }

});

app.service('QuickInboxService', function($rootScope) {

    var shared_service = {};
    shared_service.message;

    shared_service.info_block_behavior = function(cb) {
        $('.delete-block').unbind('click.delete-block').bind('click.delete-block', function(e) {
            console.log('Delete Media Id: ' + $(this).attr('mid'));
        })
    }

    return shared_service;
});
<|endoftext|>


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

// TODO 1 : create variables for prompt and fs by calling require in each respective module:
var
    prmpt = require('prompt'),
    fs = require('fs');

// TODO 2 : create a welcomeMessage variable and log the welcomeMessage:
var welcomeMessage = "Magic Eight Ball"
console.log(welcomeMessage);

// TODO 3 : create two variables, the answers array and the file path to the answers.json:
var answers = [];
var file = __dirname + '/answers.json';

fs.readFile(file, 'utf8', function (err, data) {
  if (err) { return onErr(err); }

  data = JSON.parse(data);

  // TODO 4 : Loop through the data.answers objects, and push answer-records into the answers array:
  for (index in data.answers) {
      answers.push(data.answers[index].value);
  }

  // TODO 5 : Invoke the promptForQuestion() function:
  promptForQuestion();
});

var properties = [
	{
    name: 'input',
    validator: /^[A-Z].+(\?)$/,
    message: '\nAsk the magic eight ball a question>',
    required: true,
    warning: 'Whoa now, that doesn\'t seem like a proper question:\nWe must be polite to the magic eight ball,\nso please make certain you start your question with a capital and end it with a question mark.\nFor example, \"Will I win the lottery?\". Try again.'
	}
];

function promptForQuestion() {
	prmpt.start();

	prmpt.get(properties, function (err, input) {
		if (err) { return onErr(err); }

    // TODO 7 : Invoke the showResponse() function, passing in a random index from the answers array:
		showResponse(randomNumberBetween(0, answers.length-1));
	});
}

// TODO 6 : Create the showResponse() function:
function showResponse(index) {
	console.log('The Magic Eight Ball responds: ' + answers[index]);
}

function onErr(err) {
	console.log(err);
	return 1;
}

function randomNumberBetween(min,max)
{
    return Math.floor(Math.random()*(max-min+1)+min);
}
 <commit_msg>* update app<commit_after>#!/usr/bin/env node

// TODO 1 : create variables for prompt and fs by calling require in each respective module:
var
    prmpt = require('prompt'),
    fs = require('fs');

// TODO 2 : create a welcomeMessage variable and log the welcomeMessage:
var welcomeMessage = "Magic Eight Ball";
console.log(welcomeMessage);

// TODO 3 : create two variables, the answers array and the file path to the answers.json:
var answers = [];
var file = __dirname + '/answers.json';

fs.readFile(file, 'utf8', function (err, data) {
  if (err) { return onErr(err); }

  data = JSON.parse(data);

  // TODO 4 : Loop through the data.answers objects, and push answer-records into the answers array:
  for (index in data.answers) {
      answers.push(data.answers[index].value);
  }

  // TODO 5 : Invoke the promptForQuestion() function:
  promptForQuestion();
});

var properties = [
	{
    name: 'input',
    validator: /^[A-Z].+(\?)$/,
    message: '\nAsk the magic eight ball a question>',
    required: true,
    warning: 'Whoa now, that doesn\'t seem like a proper question:\nWe must be polite to the magic eight ball,\nso please make certain you start your question with a capital and end it with a question mark.\nFor example, \"Will I win the lottery?\". Try again.'
	}
];

function promptForQuestion() {
	prmpt.start();

	prmpt.get(properties, function (err, input) {
		if (err) { return onErr(err); }

    // TODO 7 : Invoke the showResponse() function, passing in a random index from the answers array:
		showResponse(randomNumberBetween(0, answers.length-1));
	});
}

// TODO 6 : Create the showResponse() function:
function showResponse(index) {
	console.log('The Magic Eight Ball responds: ' + answers[index]);
}

function onErr(err) {
	console.log(err);
	return 1;
}

function randomNumberBetween(min,max)
{
    return Math.floor(Math.random()*(max-min+1)+min);
}
 <|endoftext|>


<commit_before>/*
 *  Copyright (c) 2016 pro!vision GmbH and Contributors
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

"use strict";

var fs = require("fs");
var walk = require("klaw");
var fse = require("fs-extra");
var clientlib = require("../lib/clientlib");
var fileExists = require("../lib/clientlib").fileExists;
var path = require("path");
var assert = require('assert');

var clientLibConf = require("./clientlib.config");

var resultDir = path.join(__dirname, "result");
var expectedDir = path.join(__dirname, "expected");

describe("Test output", function() {

  // cleanup result folder
  beforeEach(function(){
    fse.removeSync(resultDir);
    fs.mkdirSync(resultDir);
  });

  it("should create files correctly", function(done) {

    var libs = clientLibConf.libs;
    delete clientLibConf.libs;

    clientlib(libs, clientLibConf, function() {

      var items = []; // files, directories, symlinks, etc
      walk(expectedDir)
        .on("data", function (item) {
          items.push(item.path)
        })
        .on("end", function () {

          items.forEach(function(expectedFile) {
            var subFilePath = path.relative(expectedDir, expectedFile);
            if (!subFilePath) {
              return;
            }

            var resultFile = path.join(resultDir, subFilePath);

            assert.ok(fileExists(resultFile), "file does not exist in result: " + subFilePath);

            if (!fs.lstatSync(expectedFile).isDirectory()) {
              var result = fs.readFileSync(resultFile, "utf-8");
              var expected = fs.readFileSync(expectedFile, "utf-8");

              assert.equal(result, expected, "content of " + subFilePath + " is not expected");
            }

          });

          done();
        });
    });
  });
});
<commit_msg>Fix failing tests (on windows) caused by newline issue between *nix and windows<commit_after>/*
 *  Copyright (c) 2016 pro!vision GmbH and Contributors
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

"use strict";

var fs = require("fs");
var walk = require("klaw");
var fse = require("fs-extra");
var clientlib = require("../lib/clientlib");
var fileExists = require("../lib/clientlib").fileExists;
var path = require("path");
var assert = require('assert');

var clientLibConf = require("./clientlib.config");

var resultDir = path.join(__dirname, "result");
var expectedDir = path.join(__dirname, "expected");

describe("Test output", function() {

  // cleanup result folder
  beforeEach(function(){
    fse.removeSync(resultDir);
    fs.mkdirSync(resultDir);
  });

  it("should create files correctly", function(done) {

    var libs = clientLibConf.libs;
    delete clientLibConf.libs;

    clientlib(libs, clientLibConf, function() {

      var items = []; // files, directories, symlinks, etc
      walk(expectedDir)
        .on("data", function (item) {
          items.push(item.path)
        })
        .on("end", function () {

          items.forEach(function(expectedFile) {
            var subFilePath = path.relative(expectedDir, expectedFile);
            if (!subFilePath) {
              return;
            }

            var resultFile = path.join(resultDir, subFilePath);

            assert.ok(fileExists(resultFile), "file does not exist in result: " + subFilePath);

            if (!fs.lstatSync(expectedFile).isDirectory()) {
              var result = fs.readFileSync(resultFile, "utf-8").replace(/\r\n/g, "\n");
              var expected = fs.readFileSync(expectedFile, "utf-8").replace(/\r\n/g, "\n");

              assert.equal(result, expected, "content of " + subFilePath + " is not expected");
            }

          });

          done();
        });
    });
  });
});
<|endoftext|>


<commit_before>// https://github.com/DevExpress/testcafe
// https://devexpress.github.io/testcafe/documentation/test-api/
// https://github.com/helen-dikareva/axe-testcafe
import axeCheck from 'axe-testcafe'

/**
* @external AxeResult
*/
/**
 * @external TestcafeTest
*/
/**
 * @param {external.TestcafeTest} t Testcafe test object
 * @returns {Promise<external:AxeResult>} Axe accessibility result
 */
function axeCheckWithConfig (t) {
  // https://github.com/dequelabs/axe-core/blob/develop/doc/API.md#api-name-axerun
  return axeCheck(
    t,
    // context: https://github.com/dequelabs/axe-core/blob/develop/doc/API.md#context-parameter
    {
      exclude: ['.carbon-wrap > a.carbon-img']
    },
    // https://github.com/dequelabs/axe-core/blob/develop/doc/API.md#options-parameter
    {
      rules: {
        // 'meta-viewport': {enabled: false}
      }
    }
    // https://github.com/dequelabs/axe-core/blob/develop/doc/API.md#results-object
    // , (err, results) {}
  )
}

fixture`TestCafe Axe accessibility tests (Main page)`
  .page`http://localhost:4000/home/`

test('Main page', async t => {
  await axeCheckWithConfig(t)
})
<commit_msg>- Testing: Exclude bootstrap docs and codefund from accessibility tests (beyond immediate control)<commit_after>// https://github.com/DevExpress/testcafe
// https://devexpress.github.io/testcafe/documentation/test-api/
// https://github.com/helen-dikareva/axe-testcafe
import axeCheck from 'axe-testcafe'

/**
* @external AxeResult
*/
/**
 * @external TestcafeTest
*/
/**
 * @param {external.TestcafeTest} t Testcafe test object
 * @returns {Promise<external:AxeResult>} Axe accessibility result
 */
function axeCheckWithConfig (t) {
  // https://github.com/dequelabs/axe-core/blob/develop/doc/API.md#api-name-axerun
  return axeCheck(
    t,
    // context: https://github.com/dequelabs/axe-core/blob/develop/doc/API.md#context-parameter
    {
      exclude: [
        // Ignore bootstrap docs (should be fixed by them)
        ['.bs-docs-footer'],
        // Ignore codefund
        ['*[class|="cf"]']
      ]
    },
    // https://github.com/dequelabs/axe-core/blob/develop/doc/API.md#options-parameter
    {
      rules: {
        // 'meta-viewport': {enabled: false}
      }
    }
    // https://github.com/dequelabs/axe-core/blob/develop/doc/API.md#results-object
    // , (err, results) {}
  )
}

fixture`TestCafe Axe accessibility tests (Main page)`
  .page`http://localhost:4000/home/`

test('Main page', async t => {
  await axeCheckWithConfig(t)
})
<|endoftext|>


<commit_before>var Behavior = require('../lib/index');
var _ = require('lodash');
/*
var dinning;
var dinningAllowed;
var dinningExceptions = [
    'chewing gum',
    'getting drunk',
    'laughing at your mother in law'
];*/

describe('Behavior', function () {

    describe('when instantiating', function () {

        describe('when arguments are missing', function () {

            describe('when no "exceptions" argument was given', function () {

                var someBehavior;

                beforeEach(function () {
                    someBehavior = new Behavior(false);
                });

                it('should set an empty exceptions array', function () {
                    expect(_.isArray(someBehavior.exceptions) && someBehavior.exceptions.length == 0).toBe(true);
                });
            });

            describe('when no "allowed" argument was given', function () {

                var someBehavior;

                beforeEach(function () {
                    someBehavior = new Behavior();
                });

                it('should be allowed', function () {
                    expect(_.isBoolean(someBehavior.allowed) && someBehavior.allowed).toBe(true);
                });
            });
        });

        describe('when arguments were given', function () {

            describe('when the "exceptions" argument was given', function () {

                describe('when the given "exceptions" argument is a string', function () {

                    var someBehavior;
                    var someBehaviorException = '';

                    beforeEach(function () {
                        someBehavior = new Behavior(undefined,someBehaviorException);
                    });

                   it('should store an "exceptions" array with the given string', function () {
                        expect(_.isArray(someBehavior.exceptions) && _.contains(someBehavior.exceptions,someBehaviorException)).toBe(true);
                   });

                });

                describe('when the given "exceptions" argument is an array', function () {

                    var someBehavior;
                    var someBehaviorExceptions = [
                        'an exception'
                    ];

                    beforeEach(function () {
                        someBehavior = new Behavior(undefined,someBehaviorExceptions);
                    });

                    it('should store it', function () {
                        expect(someBehavior.exceptions).toEqual(someBehaviorExceptions);
                    });
                })
            });

            describe('when allowed was given', function () {

                var someBehavior;
                var someBehaviorAllowed = false;

                beforeEach(function () {
                    someBehavior = new Behavior(someBehaviorAllowed);
                });

                it('should store it', function () {
                    expect(someBehavior.allowed).toEqual(someBehaviorAllowed);
                });
            })
        });
    });

    describe('when allowed', function () {

        var honesty;
        var honestyAllowed = true;
        var honestyExceptions = [
            'lying'
        ];

        beforeEach(function () {
            honesty = new Behavior(honestyAllowed,honestyExceptions);
        });

        describe('when an exempted value is given', function () {

            var honestyExemption;

            beforeEach(function () {
                honestyExemption = honestyExceptions[0];
            });

            it('should return false', function () {
                var result = honesty.isAllowed(honestyExemption);
                expect(result).toBe(false);
            });

        });

        describe('when a non-exempted value is given', function () {

            var honestyNonExemption;

            beforeEach(function () {
                honestyNonExemption = 'being a nice person';
            });

            it('should return true', function () {
                var result = honesty.isAllowed(honestyNonExemption);
                expect(result).toBe(true);
            });

        })
    });

    describe('when not allowed', function () {

        var honesty;
        var honestyAllowed = false;
        var honestyExceptions = [
            'tell the truth'
        ];

        beforeEach(function () {
            honesty = new Behavior(honestyAllowed,honestyExceptions);
        });

        describe('when an exempted value is given', function () {

            var honestyExemption;

            beforeEach(function () {
                honestyExemption = honestyExceptions[0];
            });

            it('should return true', function () {
                var result = honesty.isAllowed(honestyExemption);
                expect(result).toBe(true);
            });

        });

        describe('when a non-exempted value is given', function () {

            var honestyNonExemption;

            beforeEach(function () {
                honestyNonExemption = 'being a nice person';
            });

            it('should return false', function () {
                var result = honesty.isAllowed(honestyNonExemption);
                expect(result).toBe(false);
            });

        })
    });

});
<commit_msg>Cleans test file<commit_after>var Behavior = require('../lib/index');
var _ = require('lodash');

describe('Behavior', function () {

    describe('when instantiating', function () {

        describe('when arguments are missing', function () {

            describe('when no "exceptions" argument was given', function () {

                var someBehavior;

                beforeEach(function () {
                    someBehavior = new Behavior(false);
                });

                it('should set an empty exceptions array', function () {
                    expect(_.isArray(someBehavior.exceptions) && someBehavior.exceptions.length == 0).toBe(true);
                });
            });

            describe('when no "allowed" argument was given', function () {

                var someBehavior;

                beforeEach(function () {
                    someBehavior = new Behavior();
                });

                it('should be allowed', function () {
                    expect(_.isBoolean(someBehavior.allowed) && someBehavior.allowed).toBe(true);
                });
            });
        });

        describe('when arguments were given', function () {

            describe('when the "exceptions" argument was given', function () {

                describe('when the given "exceptions" argument is a string', function () {

                    var someBehavior;
                    var someBehaviorException = '';

                    beforeEach(function () {
                        someBehavior = new Behavior(undefined,someBehaviorException);
                    });

                   it('should store an "exceptions" array with the given string', function () {
                        expect(_.isArray(someBehavior.exceptions) && _.contains(someBehavior.exceptions,someBehaviorException)).toBe(true);
                   });

                });

                describe('when the given "exceptions" argument is an array', function () {

                    var someBehavior;
                    var someBehaviorExceptions = [
                        'an exception'
                    ];

                    beforeEach(function () {
                        someBehavior = new Behavior(undefined,someBehaviorExceptions);
                    });

                    it('should store it', function () {
                        expect(someBehavior.exceptions).toEqual(someBehaviorExceptions);
                    });
                })
            });

            describe('when allowed was given', function () {

                var someBehavior;
                var someBehaviorAllowed = false;

                beforeEach(function () {
                    someBehavior = new Behavior(someBehaviorAllowed);
                });

                it('should store it', function () {
                    expect(someBehavior.allowed).toEqual(someBehaviorAllowed);
                });
            })
        });
    });

    describe('when allowed', function () {

        var honesty;
        var honestyAllowed = true;
        var honestyExceptions = [
            'lying'
        ];

        beforeEach(function () {
            honesty = new Behavior(honestyAllowed,honestyExceptions);
        });

        describe('when an exempted value is given', function () {

            var honestyExemption;

            beforeEach(function () {
                honestyExemption = honestyExceptions[0];
            });

            it('should return false', function () {
                var result = honesty.isAllowed(honestyExemption);
                expect(result).toBe(false);
            });

        });

        describe('when a non-exempted value is given', function () {

            var honestyNonExemption;

            beforeEach(function () {
                honestyNonExemption = 'being a nice person';
            });

            it('should return true', function () {
                var result = honesty.isAllowed(honestyNonExemption);
                expect(result).toBe(true);
            });

        })
    });

    describe('when not allowed', function () {

        var honesty;
        var honestyAllowed = false;
        var honestyExceptions = [
            'tell the truth'
        ];

        beforeEach(function () {
            honesty = new Behavior(honestyAllowed,honestyExceptions);
        });

        describe('when an exempted value is given', function () {

            var honestyExemption;

            beforeEach(function () {
                honestyExemption = honestyExceptions[0];
            });

            it('should return true', function () {
                var result = honesty.isAllowed(honestyExemption);
                expect(result).toBe(true);
            });

        });

        describe('when a non-exempted value is given', function () {

            var honestyNonExemption;

            beforeEach(function () {
                honestyNonExemption = 'being a nice person';
            });

            it('should return false', function () {
                var result = honesty.isAllowed(honestyNonExemption);
                expect(result).toBe(false);
            });

        })
    });

});
<|endoftext|>