<commit_before>import * as AsyncWorker from "../util/AsyncWorker.js";

//!!! ...unfinished... (2022/09/14) Test importScripts.
let tensorflowJsURL = "https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@3.19.0/dist/tf.min.js";
importScripts( tensorflowJsURL ); // Load tensorflow.js library in global scope.

/**
 * @return {Promise}
 *   Return a promise which will be resolved as specified value after specified
 * milliseconds.
 */
function delayedValue( milliseconds, value ) {
  return new Promise( ( resolve /*, reject*/ ) => {
    setTimeout( () => resolve( value ), milliseconds );
  } );
}

/**
 * The implementation of a neural network web worker.
 *
 */
class AsyncWorker_Body_tester extends AsyncWorker.Body {

  /** */
  constructor() {
    super(); // register callback from Worker_Proxy.
  }

  /** @override */
  async* disposeResources() {
    yield *super.disposeResources();
  }

  /**
   */
  async* initWorker( workerId ) {
    this.workerId = workerId;

    // Load libraries dynamically in global scope.
    {
      // [ globalThis.Pool,
      //   globalThis.Recyclable,
      //   globalThis.ValueMax,
      // ] = await Promise.all( [
      //   import( "../util/Pool.js" ),
      //   import( "../util/Recyclable.js" ),
      //   import( "../util/ValueMax.js" ),
      // ] );
    }

    return { value: true };
  }

  /**
   * @param {number} intervalMilliseconds
   *   How long to generate the next value.
   *
   * @param {number} valueBegin
   *   The first value in the sequence.
   *
   * @param {number} valueCountTotal
   *   There will be so many value be generated.
   *
   * @param {number} valueCountPerBoost
   *   Every so many value, generate so many values without delay intervalMilliseconds.
   */
  async* number_sequence(
    intervalMilliseconds,
    [ valueBegin, valueCountTotal, valueCountPerBoost ]
  ) {

    let bBoost = ( Math.random() < 0.5 );

    let countInBlock = 0;
    let value = valueBegin;
    for ( let i = 0; i < ( valueCountTotal - 1 ); ++i ) {

      if ( bBoost ) {
        yield { value: value }; // No delay.

      } else {
        yield delayedValue( intervalMilliseconds, { value: value } );
      }

      // Counting how many number has been generated in the boost (non-boost) block.
      ++countInBlock;
      if ( countInBlock == valueCountPerBoost ) {
        bBoost = !bBoost; // Toogle between boost and non-boost.
        countInBlock = 0;
      }

      ++value;
    }

    // Generate the final value by return;
    return { value: value };
  }

}

AsyncWorker_Body_tester.Singleton = new AsyncWorker_Body_tester(); // Create worker body.
<commit_msg>importScripts<commit_after>import * as AsyncWorker from "../util/AsyncWorker.js";

/**
 * @return {Promise}
 *   Return a promise which will be resolved as specified value after specified
 * milliseconds.
 */
function delayedValue( milliseconds, value ) {
  return new Promise( ( resolve /*, reject*/ ) => {
    setTimeout( () => resolve( value ), milliseconds );
  } );
}

/**
 * The implementation of a neural network web worker.
 *
 */
class AsyncWorker_Body_tester extends AsyncWorker.Body {

  /** */
  constructor() {
    super(); // register callback from Worker_Proxy.
  }

  /** @override */
  async* disposeResources() {
    yield *super.disposeResources();
  }

  /**
   */
  async* initWorker( workerId ) {
    this.workerId = workerId;

    //!!! ...unfinished... (2022/09/14) Test importScripts.
    let tensorflowJsURL = "https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@3.19.0/dist/tf.min.js";
    importScripts( tensorflowJsURL ); // Load tensorflow.js library in global scope.

    // Load libraries dynamically in global scope.
    {
      // [ globalThis.Pool,
      //   globalThis.Recyclable,
      //   globalThis.ValueMax,
      // ] = await Promise.all( [
      //   import( "../util/Pool.js" ),
      //   import( "../util/Recyclable.js" ),
      //   import( "../util/ValueMax.js" ),
      // ] );
    }

    return { value: true };
  }

  /**
   * @param {number} intervalMilliseconds
   *   How long to generate the next value.
   *
   * @param {number} valueBegin
   *   The first value in the sequence.
   *
   * @param {number} valueCountTotal
   *   There will be so many value be generated.
   *
   * @param {number} valueCountPerBoost
   *   Every so many value, generate so many values without delay intervalMilliseconds.
   */
  async* number_sequence(
    intervalMilliseconds,
    [ valueBegin, valueCountTotal, valueCountPerBoost ]
  ) {

    let bBoost = ( Math.random() < 0.5 );

    let countInBlock = 0;
    let value = valueBegin;
    for ( let i = 0; i < ( valueCountTotal - 1 ); ++i ) {

      if ( bBoost ) {
        yield { value: value }; // No delay.

      } else {
        yield delayedValue( intervalMilliseconds, { value: value } );
      }

      // Counting how many number has been generated in the boost (non-boost) block.
      ++countInBlock;
      if ( countInBlock == valueCountPerBoost ) {
        bBoost = !bBoost; // Toogle between boost and non-boost.
        countInBlock = 0;
      }

      ++value;
    }

    // Generate the final value by return;
    return { value: value };
  }

}

AsyncWorker_Body_tester.Singleton = new AsyncWorker_Body_tester(); // Create worker body.
<|endoftext|>


<commit_before>doinnothin = (function(sw, $) {

	var times = [];

	var btn = $('#go').click(function(e) {
		e.preventDefault();
		if(sw.running()) {
			sw.stop();
			var stats = sw.stats();
			times.push(stats);
			btn.attr('value', 'I\'m doin\' nothin\'');
			$('#time').text('');
			eventManager.trigger('timer-stopped', e, {stats: stats});
		} else {
			sw.reset();
			sw.start();
			btn.attr('value', 'I\'m doin\' somethin\'');
			updateCounter();

			eventManager.trigger('timer-started', e, {});
		}
	});

	function updateCounter() {
		if(sw.running()) {
			$('#time').text('So far... ' + sw.currentSeconds() + 's');
			setTimeout(updateCounter, 10);
		}
	}

	$('#total a').click(function(e) {
		e.preventDefault();
		$('#total span').text(ret.totalMinutes() + ' minutes');
	});

	$('#save a').click(function(e) {
		e.preventDefault();
		if(times.length) {
			$.post('/save', { start: times[0].started, times: times }, function(result) {
				$('#save a').addClass('saved');
			});
		}
	});

	var ret = {
		times: times,
		totalSeconds: function() {
			return times.map(function(x) {
				return x.seconds;
			}).reduce(function(x, y) {
				return x + (y || 0);
			});
		},
		totalMilliseconds: function() {
			return times.map(function(x) {
				return x.milliseconds;
			}).reduce(function(x, y) {
				return x + (y || 0);
			});
		},
		totalMinutes: function() {
			return ret.totalSeconds() / 60;
		}
	};

	return ret;

})(stopwatch, jQuery);

window.localDB = (function() {

	var pageStorage = (function() {
		var db = {};
		return {
			getItem: function(key) {
				if(!key) return;
				return db[key];
			},
			setItem: function(key, value) {
				if(!key) return;
				db[key] = value;
			},
			removeItem: function(key) {
				if(!key || !db[key]) return;
				return db[key];
			},
			clear: function() {
				db = {};
			}
		};
	})();

	function get(key, storage) {
		var s = storage.getItem(key);
		if(s) {
			return JSON.parse(s);
		}
		return undefined;
	}

	function getStorage(type) {
		type = type || 'localStorage';
		switch(type) {
			case 'sessionStorage':
				return sessionStorage;
			case 'pageStorage':
				return pageStorage;
			default:
				return localStorage;
		};
	}

	function set(key, value, storage) {
		storage.setItem(key, JSON.stringify(value));
	}

	function del(key, storage) {
		storage.removeItem(key);
	}

	return {
		getItem: function(key, type) {
			if(!key) return;
			var storage = getStorage(type);
			return get(key, storage);
		},
		setItem: function(key, value, type) {
			if(!key) return;
			var storage = getStorage(type);
			set(key, value, storage);
		},
		removeItem: function(key, type) {
			if(!key) return;
			var storage = getStorage(type);
			del(key, type);
		},
		clear: function(type) {
			var storage = getStorage(type);
			storage.clear();
		}
	};

})();<commit_msg>adding cookieStorage and pageStorage<commit_after>doinnothin = (function(sw, $) {

	var times = [];

	var btn = $('#go').click(function(e) {
		e.preventDefault();
		if(sw.running()) {
			sw.stop();
			var stats = sw.stats();
			times.push(stats);
			btn.attr('value', 'I\'m doin\' nothin\'');
			$('#time').text('');
			eventManager.trigger('timer-stopped', e, {stats: stats});
		} else {
			sw.reset();
			sw.start();
			btn.attr('value', 'I\'m doin\' somethin\'');
			updateCounter();

			eventManager.trigger('timer-started', e, {});
		}
	});

	function updateCounter() {
		if(sw.running()) {
			$('#time').text('So far... ' + sw.currentSeconds() + 's');
			setTimeout(updateCounter, 10);
		}
	}

	$('#total a').click(function(e) {
		e.preventDefault();
		$('#total span').text(ret.totalMinutes() + ' minutes');
	});

	$('#save a').click(function(e) {
		e.preventDefault();
		if(times.length) {
			$.post('/save', { start: times[0].started, times: times }, function(result) {
				$('#save a').addClass('saved');
			});
		}
	});

	var ret = {
		times: times,
		totalSeconds: function() {
			return times.map(function(x) {
				return x.seconds;
			}).reduce(function(x, y) {
				return x + (y || 0);
			});
		},
		totalMilliseconds: function() {
			return times.map(function(x) {
				return x.milliseconds;
			}).reduce(function(x, y) {
				return x + (y || 0);
			});
		},
		totalMinutes: function() {
			return ret.totalSeconds() / 60;
		}
	};

	return ret;

})(stopwatch, jQuery);

window.cookieMonster = (function() {
	if(!Array.prototype.filter) {
		Array.prototype.filter = function(fn) {
			var ret = [];
			for(var i=0,l=this.length; i<l; i++) {
				if(fn(this[i], i)) ret.push(this[i]);
			}
			return ret;
		};
	};
	return {
		add: function(key, value) {
			document.cookie = key + '=' + JSON.stringify(value);
		},
		get: function(key) {
			var cookies = document.cookie.split('; ')
				.filter(function(x) {
					return x.split('=')[0] == key;
				}).map(function(x) {
					var s = x.split('=')[1];
					return JSON.parse(s);
				});

			if(cookies && cookies.length > 0) {
				return cookies[0];
			}
			return;
		},
		remove: function(key, value) {
			document.cookie = key + '=' + JSON.stringify(value) + ';expires=' + 'Thu, 01-Jan-70 00:00:01 GMT;';
		}
	};
})();

window.localDB = (function() {

	var pageStorage = (function() {
		var db = {};
		return {
			getItem: function(key) {
				if(!key) return;
				return db[key];
			},
			setItem: function(key, value) {
				if(!key) return;
				db[key] = value;
			},
			removeItem: function(key) {
				if(!key || !db[key]) return;
				delete db[key];
			},
			clear: function() {
				db = {};
			}
		};
	})();

	var cookieStorage = (function() {
		cookieMonster.add('cookieStorage', {});
		function getDB() {
			return cookieMonster.get('cookieStorage');
		};
		return {
			getItem: function(key) {
				if(!key) return;
				var db = getDB();
				return db[key];
			},
			setItem: function(key, value) {
				if(!key) return;
				var db = getDB();
				db[key] = value;
				cookieMonster.add('cookieStorage', db);
			},
			removeItem: function(key) {
				if(!key) return;

			},
			clear: function() {

			}
		};
	})();

	function get(key, storage) {
		var s = storage.getItem(key);
		if(s) {
			return JSON.parse(s);
		}
		return undefined;
	}

	function getStorage(type) {
		type = type || 'localStorage';
		switch(type) {
			case 'sessionStorage':
				return sessionStorage;
			case 'pageStorage':
				return pageStorage;
			case 'cookieStorage':
				return cookieStorage;
			default:
				return localStorage;
		};
	}

	function set(key, value, storage) {
		storage.setItem(key, JSON.stringify(value));
	}

	function del(key, storage) {
		storage.removeItem(key);
	}

	return {
		getItem: function(key, type) {
			if(!key) return;
			var storage = getStorage(type);
			return get(key, storage);
		},
		setItem: function(key, value, type) {
			if(!key) return;
			var storage = getStorage(type);
			set(key, value, storage);
		},
		removeItem: function(key, type) {
			if(!key) return;
			var storage = getStorage(type);
			del(key, type);
		},
		clear: function(type) {
			var storage = getStorage(type);
			storage.clear();
		}
	};

})();
<|endoftext|>


<commit_before><commit_msg>fixed issue in firefox while load wheel<commit_after><|endoftext|>


<commit_before>import {savecopy} from "../exporter/native/copy"
import {journalDialogTemplate} from "./templates"
import {addAlert, csrfToken} from "../common/common"

let setRights = function(orginalDocId,CopyDocId,user,access_rights){
    let that = this
	let collaborators = [],
    rights = []
	access_rights.forEach(function(item,index){
	    if (item.document_id==orginalDocId){
	        collaborators[collaborators.length]=item.user_id
	    }

	})
	collaborators[collaborators.length]=user.id
	let postData = {
        'documentId': CopyDocId,
        'collaborators[]': collaborators,
    }
    jQuery.ajax({
        url: '/document/submitright/',
        data: postData,
        type: 'POST',
        dataType: 'json',
        crossDomain: false, // obviates need for sameOrigin test
        beforeSend: function(xhr, settings) {
            xhr.setRequestHeader("X-CSRFToken", csrfToken)
        },
        success: function (response) {
            addAlert('success', gettext(
                'Access rights have been saved'))
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log(jqXHR.responseText)
        }
    })
}

/** get the list of ojournal in ojs.
 * @function selectJournal
 * @param
*/

export let selectJournal = function(editor) {
        let list = null
        let diaButtons = {}
        let userProfile = {}
        let data1 = new window.FormData()
        data1.append('id', editor.user.id)
        jQuery.ajax({
            url: '/document/profile/',
            data: data1,
            type: 'POST',
            cache: false,
            contentType: false,
            processData: false,
            crossDomain: false, // obviates need for sameOrigin test
            beforeSend: function(xhr, settings) {
                xhr.setRequestHeader("X-CSRFToken", csrfToken)
            },
            success: function(result) {
                userProfile = result['user']
            },
            error: function() {
                addAlert('error', 'can not get the user information')
            }
        })

        diaButtons[gettext("Submit")] = function() {
            savecopy(editor.doc, editor.bibDB.bibDB, editor.imageDB.db,
                editor.bibDB.bibDB, editor.imageDB.db, editor.user,
                function(doc, docInfo, newBibEntries){
            		setRights(editor.doc.id,doc.id,editor.user,editor.doc.access_rights)
                    let dataToOjs = new window.FormData()
                    dataToOjs.append('username', userProfile["username"])
                    dataToOjs.append('title', editor.doc.title)
                    dataToOjs.append('first_name', userProfile["first_name"])
                    dataToOjs.append('last_name', userProfile["last_name"])
                    dataToOjs.append('email', userProfile["email"])
                    dataToOjs.append('affiliation', "sample affiliation")
                    dataToOjs.append('author_url', "sample author_url")
                    dataToOjs.append('journal_id', jQuery("input[type='radio'][name='journalList']:checked").val())
                    dataToOjs.append('file_name', editor.doc.title)
                    dataToOjs.append('article_url', window.location.origin+"/document/" + doc.id)

                    jQuery.ajax({
                        url: window.ojsUrl+'/index.php/index/gateway/plugin/RestApiGatewayPlugin/articles',
                        data: dataToOjs,
                        type: 'POST',
                        cache: false,
                        contentType: false,
                        processData: false,
                        crossDomain: false, // obviates need for sameOrigin test
                        beforeSend: function(xhr, settings) {
                            xhr.setRequestHeader("X-CSRFToken", csrfToken)
                        },
                        success: function() {
                            addAlert('success','The paper was submitted to ojs')
                        },
                        error: function() {
                            addAlert('error', 'submission was not successful')
                        }
                    })
                })
            jQuery(this).dialog("close")

        }

        diaButtons[gettext("Cancel")] = function() {
            jQuery(this).dialog("close")
        }
        jQuery.ajax({
                type: "GET",
                dataType: "json",
                url: window.ojsUrl + '/index.php/index/gateway/plugin/RestApiGatewayPlugin/journals',
                success: function (result) {
                    list =result['journals']
                    let journal = null
                        jQuery(journalDialogTemplate({journals: list})).dialog({
                        autoOpen: true,
                        height: list.length*100,
                        width: 300,
                        modal: true,
                        buttons: diaButtons,
                        create: function() {
                            let theDialog = jQuery(this).closest(".ui-dialog")
                            theDialog.find(".ui-button:first-child").addClass(
                               "fw-button fw-dark")
                            theDialog.find(".ui-button:last").addClass(
                                "fw-button fw-orange")
                        },
                    })
                }
        })

}

/*submit the review*/
export let reviewSubmit = function(editor){
 let userProfile = {}
        let data1 = new window.FormData()
        data1.append('id', editor.user.id)
        jQuery.ajax({
            url: '/document/profile/',
            data: data1,
            type: 'POST',
            cache: false,
            contentType: false,
            processData: false,
            crossDomain: false, // obviates need for sameOrigin test
            beforeSend: function(xhr, settings) {
                xhr.setRequestHeader("X-CSRFToken", csrfToken)
            },
            success: function(result) {
                userProfile = result['user']
            },
            error: function() {
                addAlert('error', 'can not get the user information')
            }
        })
        let dataToOjs = new window.FormData()
        dataToOjs.append('email', userProfile["email"])
        dataToOjs.append('doc_id', editor.doc.id)
        jQuery.ajax({
            url: window.ojsUrl+'/index.php/index/gateway/plugin/RestApiGatewayPlugin/articles',
            data: dataToOjs,
            type: 'POST',
            cache: false,
            contentType: false,
            processData: false,
            crossDomain: false, // obviates need for sameOrigin test
            beforeSend: function(xhr, settings) {
               xhr.setRequestHeader("X-CSRFToken", csrfToken)
            },
            success: function() {
               addAlert('success','The editor will be informed about finishing your review')
               },
            error: function() {
               addAlert('error', 'There is error while sending the signal of finishing review, please try it again')
            }
        })
}
<commit_msg>adding the url for review submit<commit_after>import {savecopy} from "../exporter/native/copy"
import {journalDialogTemplate} from "./templates"
import {addAlert, csrfToken} from "../common/common"

let setRights = function(orginalDocId,CopyDocId,user,access_rights){
    let that = this
	let collaborators = [],
    rights = []
	access_rights.forEach(function(item,index){
	    if (item.document_id==orginalDocId){
	        collaborators[collaborators.length]=item.user_id
	    }

	})
	collaborators[collaborators.length]=user.id
	let postData = {
        'documentId': CopyDocId,
        'collaborators[]': collaborators,
    }
    jQuery.ajax({
        url: '/document/submitright/',
        data: postData,
        type: 'POST',
        dataType: 'json',
        crossDomain: false, // obviates need for sameOrigin test
        beforeSend: function(xhr, settings) {
            xhr.setRequestHeader("X-CSRFToken", csrfToken)
        },
        success: function (response) {
            addAlert('success', gettext(
                'Access rights have been saved'))
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log(jqXHR.responseText)
        }
    })
}

/** get the list of ojournal in ojs.
 * @function selectJournal
 * @param
*/

export let selectJournal = function(editor) {
        let list = null
        let diaButtons = {}
        let userProfile = {}
        let data1 = new window.FormData()
        data1.append('id', editor.user.id)
        jQuery.ajax({
            url: '/document/profile/',
            data: data1,
            type: 'POST',
            cache: false,
            contentType: false,
            processData: false,
            crossDomain: false, // obviates need for sameOrigin test
            beforeSend: function(xhr, settings) {
                xhr.setRequestHeader("X-CSRFToken", csrfToken)
            },
            success: function(result) {
                userProfile = result['user']
            },
            error: function() {
                addAlert('error', 'can not get the user information')
            }
        })

        diaButtons[gettext("Submit")] = function() {
            savecopy(editor.doc, editor.bibDB.bibDB, editor.imageDB.db,
                editor.bibDB.bibDB, editor.imageDB.db, editor.user,
                function(doc, docInfo, newBibEntries){
            		setRights(editor.doc.id,doc.id,editor.user,editor.doc.access_rights)
                    let dataToOjs = new window.FormData()
                    dataToOjs.append('username', userProfile["username"])
                    dataToOjs.append('title', editor.doc.title)
                    dataToOjs.append('first_name', userProfile["first_name"])
                    dataToOjs.append('last_name', userProfile["last_name"])
                    dataToOjs.append('email', userProfile["email"])
                    dataToOjs.append('affiliation', "sample affiliation")
                    dataToOjs.append('author_url', "sample author_url")
                    dataToOjs.append('journal_id', jQuery("input[type='radio'][name='journalList']:checked").val())
                    dataToOjs.append('file_name', editor.doc.title)
                    dataToOjs.append('article_url', window.location.origin+"/document/" + doc.id)

                    jQuery.ajax({
                        url: window.ojsUrl+'/index.php/index/gateway/plugin/RestApiGatewayPlugin/articles',
                        data: dataToOjs,
                        type: 'POST',
                        cache: false,
                        contentType: false,
                        processData: false,
                        crossDomain: false, // obviates need for sameOrigin test
                        beforeSend: function(xhr, settings) {
                            xhr.setRequestHeader("X-CSRFToken", csrfToken)
                        },
                        success: function() {
                            addAlert('success','The paper was submitted to ojs')
                        },
                        error: function() {
                            addAlert('error', 'submission was not successful')
                        }
                    })
                })
            jQuery(this).dialog("close")

        }

        diaButtons[gettext("Cancel")] = function() {
            jQuery(this).dialog("close")
        }
        jQuery.ajax({
                type: "GET",
                dataType: "json",
                url: window.ojsUrl + '/index.php/index/gateway/plugin/RestApiGatewayPlugin/journals',
                success: function (result) {
                    list =result['journals']
                    let journal = null
                        jQuery(journalDialogTemplate({journals: list})).dialog({
                        autoOpen: true,
                        height: list.length*100,
                        width: 300,
                        modal: true,
                        buttons: diaButtons,
                        create: function() {
                            let theDialog = jQuery(this).closest(".ui-dialog")
                            theDialog.find(".ui-button:first-child").addClass(
                               "fw-button fw-dark")
                            theDialog.find(".ui-button:last").addClass(
                                "fw-button fw-orange")
                        },
                    })
                }
        })

}

/*submit the review*/
export let reviewSubmit = function(editor){
 let userProfile = {}
        let data1 = new window.FormData()
        data1.append('id', editor.user.id)
        jQuery.ajax({
            url: '/document/profile/',
            data: data1,
            type: 'POST',
            cache: false,
            contentType: false,
            processData: false,
            crossDomain: false, // obviates need for sameOrigin test
            beforeSend: function(xhr, settings) {
                xhr.setRequestHeader("X-CSRFToken", csrfToken)
            },
            success: function(result) {
                userProfile = result['user']
            },
            error: function() {
                addAlert('error', 'can not get the user information')
            }
        })
        let dataToOjs = new window.FormData()
        dataToOjs.append('email', userProfile["email"])
        dataToOjs.append('doc_id', editor.doc.id)
        dataToOjs.append('review_round', "1")
        jQuery.ajax({
            url: window.ojsUrl+'/index.php/index/gateway/plugin/RestApiGatewayPlugin/articleReviews',
            data: dataToOjs,
            type: 'POST',
            cache: false,
            contentType: false,
            processData: false,
            crossDomain: false, // obviates need for sameOrigin test
            beforeSend: function(xhr, settings) {
               xhr.setRequestHeader("X-CSRFToken", csrfToken)
            },
            success: function() {
               addAlert('success','The editor will be informed about finishing your review')
               },
            error: function() {
               addAlert('error', 'There is error while sending the signal of finishing review, please try it again')
            }
        })
}
<|endoftext|>


<commit_before>const _ = require('underscore');
const ProvinceCard = require('../../provincecard.js');

class TeachingsOfTheElements extends ProvinceCard {
    setupCardAbilities(ability) {
        this.persistentEffect({
            match: this,
            effect: ability.effects.modifyProvinceStrength(() => this.getNoOfClaimedRings())
        });
    }

    getNoOfClaimedRings() {
        let claimedRings = _.size(this.controller.getClaimedRings());
        let otherPlayer = this.game.getOtherPlayer(this.controller);
        if(otherPlayer) {
            claimedRings += _.size(otherPlayer.getClaimedRings());
        }
        return claimedRings;
    }
}

TeachingsOfTheElements.id = 'teachings-of-the-elements';

module.exports = TeachingsOfTheElements;
<commit_msg>Teaching of the Elements bugfix (#2349)<commit_after>const ProvinceCard = require('../../provincecard.js');

class TeachingsOfTheElements extends ProvinceCard {
    setupCardAbilities(ability) {
        this.persistentEffect({
            match: this,
            effect: ability.effects.modifyProvinceStrength(() => this.getNoOfClaimedRings())
        });
    }

    getNoOfClaimedRings() {
        let claimedRings = Object.values(this.game.rings).filter(ring => ring.isConsideredClaimed());
        return claimedRings.length;
    }
}

TeachingsOfTheElements.id = 'teachings-of-the-elements';

module.exports = TeachingsOfTheElements;
<|endoftext|>


<commit_before>hqDefine("reports/js/filters/main", [
    'jquery',
    'knockout',
    'hqwebapp/js/main',
    'reports/js/standard_hq_report',
    'reports/js/filters/select2s',
    'reports/js/filters/phone_number',
    'reports/js/filters/button_group',
    'reports/js/filters/schedule_instance',
    'locations/js/location_drilldown',
    'reports/js/filters/advanced_forms_options',
    'reports/js/filters/drilldown_options',
    'reports_core/js/choice_list_utils',
    'select2-3.5.2-legacy/select2',
], function(
    $,
    ko,
    hqMain,
    standardHQReportModule,
    select2Filter,
    phoneNumberFilter,
    buttonGroup,
    scheduleInstanceFilter,
    locationDrilldown,
    advancedFormsOptions,
    drilldownOptions,
    choiceListUtils
) {
    var init = function() {
        // Datespans
        $('.report-filter-datespan').each(function() {
            var $filterRange = $(this);
            if ($filterRange.data("init")) {
                var separator = $filterRange.data('separator');
                var reportLabels = $filterRange.data('reportLabels');
                var standardHQReport = standardHQReportModule.getStandardHQReport();

                $filterRange.createDateRangePicker(
                    reportLabels, separator,
                    $filterRange.data('startDate'),
                    $filterRange.data('endDate')
                );
                $filterRange.on('change apply', function() {
                    var dates = $(this).val().split(separator);
                    $(standardHQReport.filterAccordion).trigger('hqreport.filter.datespan.startdate', dates[0]);
                    $('#report_filter_datespan_startdate').val(dates[0]);
                    $(standardHQReport.filterAccordion).trigger('hqreport.filter.datespan.enddate', dates[1]);
                    $('#report_filter_datespan_enddate').val(dates[1]);
                });
            }
        });

        // other Datespans *groan* TODO unify on this one
        $('.report-filter-datespan-filter').each(function(i, el) {
            var $el = $(el), data = $el.data();
            var $filterStart = $("#" + data.cssId + "-start");
            var $filterEnd = $("#" + data.cssId + "-end");

            $el.createBootstrap3DefaultDateRangePicker();
            $el.on('apply change', function () {
                var separator = $().getDateRangeSeparator();
                var dates = $el.val().split(separator);
                $filterStart.val(dates[0]);
                $filterEnd.val(dates[1]);
            });

            if (!$el.val() && $filterStart.val() && $filterEnd.val()) {
                var text = $filterStart.val() + $().getDateRangeSeparator() + $filterEnd.val();
                $el.val(text);
            } else if (!$el.val()) {
                $el.val(gettext("Show All Dates"));
            }
        });

        // Date selector
        var $dateSelector = $("#filter_date_selector");
        if ($dateSelector.length && $dateSelector.data("init")) {
            $('#filter_date_selector').daterangepicker(
                {
                    locale: {
                        format: 'YYYY-MM-DD',
                    },
                    singleDatePicker: true,
                }
            );
        }

        // Date ranges (used in accounting)
        $('.date-range').each(function() {
            $(this).datepicker({
                changeMonth: true,
                changeYear: true,
                dateFormat: 'yy-mm-dd',
            });
        });

        // Optional date ranges, optional month+year (used in accounting)
        $(".report-filter-optional").each(function() {
            $(this).koApplyBindings({
                showFilterName: ko.observable($(this).data("showFilterName")),
            });
        });

        // Selects
        $('.report-filter-single-option').each(function() {
            select2Filter.initSingle(this);
        });
        $('.report-filter-single-option-paginated').each(function() {
            select2Filter.initSinglePaginated(this);
        });
        $('.report-filter-multi-option').each(function() {
            select2Filter.initMulti(this);
        });

        // Submission type (Raw Forms, Errors, & Duplicates)
        $('.report-filter-button-group').each(function() {
            buttonGroup.link(this);
        });

        // Tags (to filter by CC version in global device logs soft asserts report)
        $('.report-filter-tags').each(function() {
            $(this).select2({tags: $(this).data("tags"), allowClear: true});
        });

        // Initialize any help bubbles
        $('.hq-help-template').each(function () {
            hqMain.transformHelpTemplate($(this), true);
        });

        $(".report-filter-message-type-configuration").each(function (i, el) {
            var $el = $(el),
                data = $el.data();
            var model = scheduleInstanceFilter.model(data.initialValue, data.conditionalAlertChoices);
            $el.koApplyBindings(model);

            $('[name=rule_id]').each(function(i, el) {
                $(el).select2({
                    allowClear: true,
                    placeholder: gettext("All"),
                });
            });
        });
        $(".report-filter-phone-number").each(function (i, el) {
            var $el = $(el),
                data = $el.data();
            var model = phoneNumberFilter.model(data.initialValue, data.groups);
            $el.koApplyBindings(model);
        });
        $('[name=selected_group]').each(function(i, el) {
            $(el).select2({
                allowClear: true,
                placeholder: gettext("Select a group"),
            });
        });
        $('.report-filter-location-async').each(function(i, el) {
            var $el = $(el), data = $el.data();
            var model = locationDrilldown.locationSelectViewModel({
                "hierarchy": data.hierarchy,
                "show_location_filter": data.makeOptional && !data.locId ? "n" : "y",
                "loc_url": data.locationUrl,
                "auto_drill": data.autoDrill,
                "max_drilldown_length": data.maxDrilldownLength,
            });
            $el.koApplyBindings(model);
            model.load(data.locs, data.locId);
        });
        $('.report-filter-logtag').each(function(i, el) {
            var $el = $(el), data = $el.data();
            if (data.defaultOn) {
                $el.attr("name", "");
                $el.change(function () {
                    $el.attr("name", "logtag");
                });
            }
            if (data.errorOnly) {
                $("#device-log-errors-only-checkbox").change(function () {
                    var multiSelect = $el;
                    if ($el.prop('checked')) {
                        $el.attr("name", "errors_only");
                        multiSelect.attr("name", "");
                        multiSelect.addClass("hide");
                    } else {
                        $el.attr("name", "");
                        if (!data.defaultOn) {
                            multiSelect.attr("name", "logtag");
                        }
                        multiSelect.removeClass("hide");
                    }
                });
            }
        });

        $('.report-filter-dynamic-choice-list').each(function (i, el) {
            var $el = $(el), data = $el.data();
            var initialValues = _.map(data.initialValues, function(value) {
                    return choiceListUtils.formatValueForSelect2(value);
                }),
                // TODO: Ideally the separator would be defined in one place. Right now it is
                //       also defined corehq.apps.userreports.reports.filters.CHOICE_DELIMITER
                separator = "\u001F";

            $el.select2({
                minimumInputLength: 0,
                multiple: true,
                separator: separator,
                allowClear: true,
                // allowClear only respected if there is a non empty placeholder
                placeholder: " ",
                ajax: {
                    url: data.ajaxFilterUrl,
                    dataType: 'json',
                    quietMillis: 250,
                    data: choiceListUtils.getApiQueryParams,
                    results: choiceListUtils.formatPageForSelect2,
                    cache: true,
                },
            });
            $el.select2('data', initialValues);
        });
    };

    return {
        init: init,
    };
});
<commit_msg>update dependencies in reports/js/filters/main.js<commit_after>hqDefine("reports/js/filters/main", [
    'jquery',
    'knockout',
    'hqwebapp/js/main',
    'reports/js/standard_hq_report',
    'reports/js/filters/select2s',
    'reports/js/filters/phone_number',
    'reports/js/filters/button_group',
    'reports/js/filters/schedule_instance',
    'locations/js/location_drilldown',
    'reports_core/js/choice_list_utils',
    'select2-3.5.2-legacy/select2',
], function(
    $,
    ko,
    hqMain,
    standardHQReportModule,
    select2Filter,
    phoneNumberFilter,
    buttonGroup,
    scheduleInstanceFilter,
    locationDrilldown,
    choiceListUtils
) {
    var init = function() {
        // Datespans
        $('.report-filter-datespan').each(function() {
            var $filterRange = $(this);
            if ($filterRange.data("init")) {
                var separator = $filterRange.data('separator');
                var reportLabels = $filterRange.data('reportLabels');
                var standardHQReport = standardHQReportModule.getStandardHQReport();

                $filterRange.createDateRangePicker(
                    reportLabels, separator,
                    $filterRange.data('startDate'),
                    $filterRange.data('endDate')
                );
                $filterRange.on('change apply', function() {
                    var dates = $(this).val().split(separator);
                    $(standardHQReport.filterAccordion).trigger('hqreport.filter.datespan.startdate', dates[0]);
                    $('#report_filter_datespan_startdate').val(dates[0]);
                    $(standardHQReport.filterAccordion).trigger('hqreport.filter.datespan.enddate', dates[1]);
                    $('#report_filter_datespan_enddate').val(dates[1]);
                });
            }
        });

        // other Datespans *groan* TODO unify on this one
        $('.report-filter-datespan-filter').each(function(i, el) {
            var $el = $(el), data = $el.data();
            var $filterStart = $("#" + data.cssId + "-start");
            var $filterEnd = $("#" + data.cssId + "-end");

            $el.createBootstrap3DefaultDateRangePicker();
            $el.on('apply change', function () {
                var separator = $().getDateRangeSeparator();
                var dates = $el.val().split(separator);
                $filterStart.val(dates[0]);
                $filterEnd.val(dates[1]);
            });

            if (!$el.val() && $filterStart.val() && $filterEnd.val()) {
                var text = $filterStart.val() + $().getDateRangeSeparator() + $filterEnd.val();
                $el.val(text);
            } else if (!$el.val()) {
                $el.val(gettext("Show All Dates"));
            }
        });

        // Date selector
        var $dateSelector = $("#filter_date_selector");
        if ($dateSelector.length && $dateSelector.data("init")) {
            $('#filter_date_selector').daterangepicker(
                {
                    locale: {
                        format: 'YYYY-MM-DD',
                    },
                    singleDatePicker: true,
                }
            );
        }

        // Date ranges (used in accounting)
        $('.date-range').each(function() {
            $(this).datepicker({
                changeMonth: true,
                changeYear: true,
                dateFormat: 'yy-mm-dd',
            });
        });

        // Optional date ranges, optional month+year (used in accounting)
        $(".report-filter-optional").each(function() {
            $(this).koApplyBindings({
                showFilterName: ko.observable($(this).data("showFilterName")),
            });
        });

        // Selects
        $('.report-filter-single-option').each(function() {
            select2Filter.initSingle(this);
        });
        $('.report-filter-single-option-paginated').each(function() {
            select2Filter.initSinglePaginated(this);
        });
        $('.report-filter-multi-option').each(function() {
            select2Filter.initMulti(this);
        });

        // Submission type (Raw Forms, Errors, & Duplicates)
        $('.report-filter-button-group').each(function() {
            buttonGroup.link(this);
        });

        // Tags (to filter by CC version in global device logs soft asserts report)
        $('.report-filter-tags').each(function() {
            $(this).select2({tags: $(this).data("tags"), allowClear: true});
        });

        // Initialize any help bubbles
        $('.hq-help-template').each(function () {
            hqMain.transformHelpTemplate($(this), true);
        });

        $(".report-filter-message-type-configuration").each(function (i, el) {
            var $el = $(el),
                data = $el.data();
            var model = scheduleInstanceFilter.model(data.initialValue, data.conditionalAlertChoices);
            $el.koApplyBindings(model);

            $('[name=rule_id]').each(function(i, el) {
                $(el).select2({
                    allowClear: true,
                    placeholder: gettext("All"),
                });
            });
        });
        $(".report-filter-phone-number").each(function (i, el) {
            var $el = $(el),
                data = $el.data();
            var model = phoneNumberFilter.model(data.initialValue, data.groups);
            $el.koApplyBindings(model);
        });
        $('[name=selected_group]').each(function(i, el) {
            $(el).select2({
                allowClear: true,
                placeholder: gettext("Select a group"),
            });
        });
        $('.report-filter-location-async').each(function(i, el) {
            var $el = $(el), data = $el.data();
            var model = locationDrilldown.locationSelectViewModel({
                "hierarchy": data.hierarchy,
                "show_location_filter": data.makeOptional && !data.locId ? "n" : "y",
                "loc_url": data.locationUrl,
                "auto_drill": data.autoDrill,
                "max_drilldown_length": data.maxDrilldownLength,
            });
            $el.koApplyBindings(model);
            model.load(data.locs, data.locId);
        });
        $('.report-filter-logtag').each(function(i, el) {
            var $el = $(el), data = $el.data();
            if (data.defaultOn) {
                $el.attr("name", "");
                $el.change(function () {
                    $el.attr("name", "logtag");
                });
            }
            if (data.errorOnly) {
                $("#device-log-errors-only-checkbox").change(function () {
                    var multiSelect = $el;
                    if ($el.prop('checked')) {
                        $el.attr("name", "errors_only");
                        multiSelect.attr("name", "");
                        multiSelect.addClass("hide");
                    } else {
                        $el.attr("name", "");
                        if (!data.defaultOn) {
                            multiSelect.attr("name", "logtag");
                        }
                        multiSelect.removeClass("hide");
                    }
                });
            }
        });

        $('.report-filter-dynamic-choice-list').each(function (i, el) {
            var $el = $(el), data = $el.data();
            var initialValues = _.map(data.initialValues, function(value) {
                    return choiceListUtils.formatValueForSelect2(value);
                }),
                // TODO: Ideally the separator would be defined in one place. Right now it is
                //       also defined corehq.apps.userreports.reports.filters.CHOICE_DELIMITER
                separator = "\u001F";

            $el.select2({
                minimumInputLength: 0,
                multiple: true,
                separator: separator,
                allowClear: true,
                // allowClear only respected if there is a non empty placeholder
                placeholder: " ",
                ajax: {
                    url: data.ajaxFilterUrl,
                    dataType: 'json',
                    quietMillis: 250,
                    data: choiceListUtils.getApiQueryParams,
                    results: choiceListUtils.formatPageForSelect2,
                    cache: true,
                },
            });
            $el.select2('data', initialValues);
        });
    };

    return {
        init: init,
    };
});
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * 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.
 */

var flags = {};

if ( process.argv.length > 2 ) {
  process.argv[2].split(',').forEach(function(f) {
    flags[f] = true;
  });
}

var outfile = __dirname + '/../foam-bin.js';
if ( process.argv.length > 3 ) {
  outfile = process.argv[3];
}

var payload = '';
var env = {
  FOAM_FILES: function(files) {
    files.filter(function(f) {
      return f.flags ? flags[f.flags] : true;
    }).map(function(f) {
      return f.name;
    }).forEach(function(f) {
      var data = require('fs').readFileSync(__dirname + '/../src/' + f + '.js').toString();
      payload += data;
    });
  }
};

var data = [ require('fs').readFileSync(__dirname + '/../src/files.js') ];
if ( flags.nanos ) {
  data.push(
      require('fs').readFileSync(__dirname + '/../src/foam/nanos/nanos.js'));
}

for ( var i = 0; i < data.length; i++ ) {
  with (env) { eval(data[i].toString()); }
}
require('fs').writeFileSync(outfile, payload);
<commit_msg>tools/build.js: Enable js flag when no other language specified<commit_after>/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * 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.
 */

// TODO(markdittmer): Get rid of special-casing of 'js' and 'nanos' flags.

var flags = {};
var otherLanguages = [ 'java', 'swift' ];

if ( process.argv.length > 2 ) {
  process.argv[2].split(',').forEach(function(f) {
    flags[f] = true;
  });

  // Default to language = javascript.
  if ( ! flags.js ) {
    flags.js = ! otherLanguage.some(function(lang) {
      return flags[lang];
    });
  }
}

var outfile = __dirname + '/../foam-bin.js';
if ( process.argv.length > 3 ) {
  outfile = process.argv[3];
}

var payload = '';
var env = {
  FOAM_FILES: function(files) {
    files.filter(function(f) {
      return f.flags ? flags[f.flags] : true;
    }).map(function(f) {
      return f.name;
    }).forEach(function(f) {
      var data = require('fs').readFileSync(__dirname + '/../src/' + f + '.js').toString();
      payload += data;
    });
  }
};

var data = [ require('fs').readFileSync(__dirname + '/../src/files.js') ];
if ( flags.nanos ) {
  data.push(
      require('fs').readFileSync(__dirname + '/../src/foam/nanos/nanos.js'));
}

for ( var i = 0; i < data.length; i++ ) {
  with (env) { eval(data[i].toString()); }
}
require('fs').writeFileSync(outfile, payload);
<|endoftext|>


<commit_before>(function () {
    'use strict';

    angular
        .module('mturk.hit.controllers', [])
        .controller('HITController', HITController);

    HITController.$inject = ['$scope', '$state', '$mdToast', 'HIT', '$filter', '$sce', '$websocket', '$rootScope', '$stateParams', '$location'];

    function HITController($scope, $state, $mdToast, HIT, $filter, $sce, $websocket, $rootScope, $stateParams, $location) {
        var self = this;
        self.isAccepted = false;
        self.submit = submit;
        self.currentStatus = null;
        self.pk = null;
        self.MTURK_HOST = 'https://workersandbox.mturk.com/mturk/externalSubmit';
        self.getHost = getHost;
        self.showSubmit = showSubmit;
        self.showTruth = showTruth;
        self.submitMturk = submitMturk;
        self.showRejectForm = false;
        self.notAllowed = false;
        self.noErrors = false;
        self.rejectionReason = null;
        self.rejectionDetail = null;
        self.rejectHIT = rejectHIT;
        self.HITRejected = false;
        self.hasTruth = false;

        activate();

        self.reject_reason = {
            REASON_LOW_PAY: 1,
            REASON_INAPPROPRIATE: 2,
            OTHER: 3
        };

        function stringify(obj) {
          function flatten(obj) {
            if (_.isObject(obj)) {
              return _.sortBy(_.map(
                  _.pairs(obj),
                  function(p) { return [p[0], flatten(p[1])]; }
                ),
                function(p) { return p[0]; }
              );
            }
            return obj;
          }

          var converted = JSON.parse(angular.toJson(obj));
          return JSON.stringify(flatten(converted));
        }

        function activate() {
            var hitId = $stateParams.hitId;
            var assignmentId = $stateParams.assignmentId;
            self.assignmentId = assignmentId;
            var workerId = $stateParams.workerId;
            var taskId = $stateParams.taskId;

            HIT.get_or_create(taskId, hitId, assignmentId, workerId).then(
                function success(response) {
                    self.taskData = response[0].task;
                    self.is_review = response[0].is_review;
                    self.HITRejected = response[0].is_rejected;
                    self.task_id = self.taskData.id;
                    self.pk = response[0].assignment;
                    self.isAccepted = assignmentId !== 'ASSIGNMENT_ID_NOT_AVAILABLE';
                    if (self.isAccepted) {
                        initializeWebSocket();
                    }
                    self.noErrors = true;
                },
                function error(response) {
                    if (response[1] == 403) {
                        self.notAllowed = true;
                        return;
                    }
                    self.noErrors = false;
                    $mdToast.showSimple('Something went wrong, please try again.');
                }
            ).finally(function () {
            });

            HIT.get_url().then(
                function success(response) {
                    self.MTURK_HOST = response[0].url;
                },
                function error(response) {
                    $mdToast.showSimple('Could not get worker host.');
                }
            ).finally(function () {

            });
        }

        function submit() {
            var itemsToSubmit = $filter('filter')(self.taskData.template.items, {role: 'input'});
            var itemAnswers = [];
            var missing = false;

            self.status = {
                RETURNED: 5,
                REJECTED: 4,
                ACCEPTED: 3,
                SUBMITTED: 2,
                CREATED: 1
            };

            var finalAnswer = {};

            angular.forEach(itemsToSubmit, function (obj) {
                if ((!obj.answer || obj.answer == "") && obj.type != 'checkbox') {
                    missing = true;
                }

                if (obj.type != 'checkbox') {
                    itemAnswers.push(
                        {
                            template_item: obj.id,
                            result: obj.answer || ""
                        }
                    );

                    finalAnswer[obj.name] = obj.answer || "";
                }
                else {
                    itemAnswers.push(
                        {
                            template_item: obj.id,
                            result: obj.aux_attributes.options
                        }
                    );

                    finalAnswer[obj.name] = obj.aux_attributes.options;
                }
            });

            if (missing) {
                $mdToast.showSimple('All fields are required.');
                return;
            }

            var requestData = {
                task: self.taskData.id,
                items: itemAnswers,
                worker_id: $stateParams.workerId,
                assignment_id: $stateParams.assignmentId,
                hit_id: $stateParams.hitId
            };

            HIT.submit_results(self.pk, requestData).then(
                function success(response, status) {
                    self.currentStatus = true;
                    var data = response[0];

                    if (data.hasOwnProperty("message") && data.message=="truth"){
                        self.hasTruth = true;

                        self.truth = {};
                        var truthAnswer = {};
                        var items = angular.copy(self.taskData.template.items);

                        self.truth.items = _.map(items, function (item){
                          if(item.role=='input'){
                              if (data.hasOwnProperty("truth") && data.truth.hasOwnProperty(item.name)){

                                  if(item.type != 'checkbox') {
                                      item.answer = data.truth[item.name];
                                      truthAnswer[item.name] = data.truth[item.name] || "";
                                  }else{
                                      var correctChoices = data.truth[item.name];

                                      item.aux_attributes.options = _.map(item.aux_attributes.options, function(option){
                                          delete option.answer;

                                          if(correctChoices.indexOf(option.value) >= 0){
                                              option.answer=true;
                                          }
                                          return option;
                                      });

                                      truthAnswer[item.name] = item.aux_attributes.options;
                                  }
                              }
                          }

                          return item;
                        });

                        self.truth.match = (stringify(finalAnswer)===stringify(truthAnswer));

                        submitMturk(false);

                    }else {
                       submitMturk(true);
                    }
                },
                function error(data, status) {
                    $mdToast.showSimple('Could not submit task!');

                }).finally(function () {
                }
            );
        }

        function getHost() {
            return $sce.trustAsResourceUrl(self.MTURK_HOST);
        }

        function showSubmit() {
            if (self.isAccepted && !self.currentStatus) {
                return $filter('filter')(self.taskData.template.items, {role: 'input'}).length > 0 && self.noErrors;
            }
            return false;
        }

        function showTruth() {
           return self.isAccepted && self.currentStatus && self.hasTruth;
        }

        function submitMturk(refresh) {
            $('#mturkForm').submit(function (e) {
                if(!refresh){
                    e.preventDefault();
                }
            });
        }

        function initializeWebSocket() {
            self.ws = $websocket.$new({
                url: $rootScope.getWebsocketUrl() + '/ws/external?subscribe-broadcast',
                lazy: true,
                reconnect: true
            });

            self.ws
                .$on('$message', function (data) {
                    receiveMessage(data);
                })
                .$on('$close', function () {

                })
                .$on('$open', function () {
                    console.log('opened');
                })
                .$open();
        }

        function receiveMessage(data) {
            if (!self.taskData) {
                return;
            }
            var message = JSON.parse(data);
            if ($location.search().taskId != message.task_id) return;
            var inputItems = $filter('filter')(self.taskData.template.items, {role: 'input'});
            var remoteContentItems = $filter('filter')(self.taskData.template.items, {type: 'iframe'});
            var item = $filter('filter')(self.taskData.template.items, {id: message.template_item});
            if (inputItems.length == 0 && item.length && item[0].aux_attributes.src.indexOf(message.daemo_id) > 0) {
                item[0].isSubmitted = true;
                var submitted = $filter('filter')(self.taskData.template.items, {
                    isSubmitted: true,
                    type: 'iframe'
                });
                if (remoteContentItems.length == submitted.length) {
                    self.submit();
                }
            }
            $scope.$apply();
        }

        function rejectHIT() {
            if (!self.rejectionReason) {
                $mdToast.showSimple('Please choose a reason');
                return;
            }

            if (self.rejectionReason == self.reject_reason.OTHER && (!self.rejectionDetail || self.rejectionDetail == '')) {
                $mdToast.showSimple('Please provide details for flagging');
                return;
            }

            var request_data = {
                worker_id: $stateParams.workerId,
                assignment_id: $stateParams.assignmentId,
                hit_id: $stateParams.hitId,
                reason: self.rejectionReason,
                detail: self.rejectionDetail
            };

            HIT.reject(self.pk, request_data).then(
                function success(data, status) {
                    self.HITRejected = true;
                },
                function error(data, status) {
                    $mdToast.showSimple("Could not reject HIT!");
                }).finally(function () {
                }
            );
        }
    }
})
();

<commit_msg>submit after timeout<commit_after>(function () {
    'use strict';

    angular
        .module('mturk.hit.controllers', [])
        .controller('HITController', HITController);

    HITController.$inject = ['$scope', '$state', '$mdToast', 'HIT', '$filter', '$sce', '$websocket', '$rootScope', '$stateParams', '$location'];

    function HITController($scope, $state, $mdToast, HIT, $filter, $sce, $websocket, $rootScope, $stateParams, $location) {
        var self = this;
        self.isAccepted = false;
        self.submit = submit;
        self.currentStatus = null;
        self.pk = null;
        self.MTURK_HOST = 'https://workersandbox.mturk.com/mturk/externalSubmit';
        self.getHost = getHost;
        self.showSubmit = showSubmit;
        self.showTruth = showTruth;
        self.submitMturk = submitMturk;
        self.showRejectForm = false;
        self.notAllowed = false;
        self.noErrors = false;
        self.rejectionReason = null;
        self.rejectionDetail = null;
        self.rejectHIT = rejectHIT;
        self.HITRejected = false;
        self.hasTruth = false;

        activate();

        self.reject_reason = {
            REASON_LOW_PAY: 1,
            REASON_INAPPROPRIATE: 2,
            OTHER: 3
        };

        function stringify(obj) {
          function flatten(obj) {
            if (_.isObject(obj)) {
              return _.sortBy(_.map(
                  _.pairs(obj),
                  function(p) { return [p[0], flatten(p[1])]; }
                ),
                function(p) { return p[0]; }
              );
            }
            return obj;
          }

          var converted = JSON.parse(angular.toJson(obj));
          return JSON.stringify(flatten(converted));
        }

        function activate() {
            var hitId = $stateParams.hitId;
            var assignmentId = $stateParams.assignmentId;
            self.assignmentId = assignmentId;
            var workerId = $stateParams.workerId;
            var taskId = $stateParams.taskId;

            HIT.get_or_create(taskId, hitId, assignmentId, workerId).then(
                function success(response) {
                    self.taskData = response[0].task;
                    self.is_review = response[0].is_review;
                    self.HITRejected = response[0].is_rejected;
                    self.task_id = self.taskData.id;
                    self.pk = response[0].assignment;
                    self.isAccepted = assignmentId !== 'ASSIGNMENT_ID_NOT_AVAILABLE';
                    if (self.isAccepted) {
                        initializeWebSocket();
                    }
                    self.noErrors = true;
                },
                function error(response) {
                    if (response[1] == 403) {
                        self.notAllowed = true;
                        return;
                    }
                    self.noErrors = false;
                    $mdToast.showSimple('Something went wrong, please try again.');
                }
            ).finally(function () {
            });

            HIT.get_url().then(
                function success(response) {
                    self.MTURK_HOST = response[0].url;
                },
                function error(response) {
                    $mdToast.showSimple('Could not get worker host.');
                }
            ).finally(function () {

            });
        }

        function submit() {
            var itemsToSubmit = $filter('filter')(self.taskData.template.items, {role: 'input'});
            var itemAnswers = [];
            var missing = false;

            self.status = {
                RETURNED: 5,
                REJECTED: 4,
                ACCEPTED: 3,
                SUBMITTED: 2,
                CREATED: 1
            };

            var finalAnswer = {};

            angular.forEach(itemsToSubmit, function (obj) {
                if ((!obj.answer || obj.answer == "") && obj.type != 'checkbox') {
                    missing = true;
                }

                if (obj.type != 'checkbox') {
                    itemAnswers.push(
                        {
                            template_item: obj.id,
                            result: obj.answer || ""
                        }
                    );

                    finalAnswer[obj.name] = obj.answer || "";
                }
                else {
                    itemAnswers.push(
                        {
                            template_item: obj.id,
                            result: obj.aux_attributes.options
                        }
                    );

                    finalAnswer[obj.name] = obj.aux_attributes.options;
                }
            });

            if (missing) {
                $mdToast.showSimple('All fields are required.');
                return;
            }

            var requestData = {
                task: self.taskData.id,
                items: itemAnswers,
                worker_id: $stateParams.workerId,
                assignment_id: $stateParams.assignmentId,
                hit_id: $stateParams.hitId
            };

            HIT.submit_results(self.pk, requestData).then(
                function success(response, status) {
                    self.currentStatus = true;
                    var data = response[0];

                    if (data.hasOwnProperty("message") && data.message=="truth"){
                        self.hasTruth = true;

                        self.truth = {};
                        var truthAnswer = {};
                        var items = angular.copy(self.taskData.template.items);

                        self.truth.items = _.map(items, function (item){
                          if(item.role=='input'){
                              if (data.hasOwnProperty("truth") && data.truth.hasOwnProperty(item.name)){

                                  if(item.type != 'checkbox') {
                                      item.answer = data.truth[item.name];
                                      truthAnswer[item.name] = data.truth[item.name] || "";
                                  }else{
                                      var correctChoices = data.truth[item.name];

                                      item.aux_attributes.options = _.map(item.aux_attributes.options, function(option){
                                          delete option.answer;

                                          if(correctChoices.indexOf(option.value) >= 0){
                                              option.answer=true;
                                          }
                                          return option;
                                      });

                                      truthAnswer[item.name] = item.aux_attributes.options;
                                  }
                              }
                          }

                          return item;
                        });

                        self.truth.match = (stringify(finalAnswer)===stringify(truthAnswer));

                        $timeout(function(){
                            submitMturk();
                        }, 10000);

                    }else {
                       submitMturk();
                    }
                },
                function error(data, status) {
                    $mdToast.showSimple('Could not submit task!');

                }).finally(function () {
                }
            );
        }

        function getHost() {
            return $sce.trustAsResourceUrl(self.MTURK_HOST);
        }

        function showSubmit() {
            if (self.isAccepted && !self.currentStatus) {
                return $filter('filter')(self.taskData.template.items, {role: 'input'}).length > 0 && self.noErrors;
            }
            return false;
        }

        function showTruth() {
           return self.isAccepted && self.currentStatus && self.hasTruth;
        }

        function submitMturk() {
            $('#mturkForm').submit();
        }

        function initializeWebSocket() {
            self.ws = $websocket.$new({
                url: $rootScope.getWebsocketUrl() + '/ws/external?subscribe-broadcast',
                lazy: true,
                reconnect: true
            });

            self.ws
                .$on('$message', function (data) {
                    receiveMessage(data);
                })
                .$on('$close', function () {

                })
                .$on('$open', function () {
                    console.log('opened');
                })
                .$open();
        }

        function receiveMessage(data) {
            if (!self.taskData) {
                return;
            }
            var message = JSON.parse(data);
            if ($location.search().taskId != message.task_id) return;
            var inputItems = $filter('filter')(self.taskData.template.items, {role: 'input'});
            var remoteContentItems = $filter('filter')(self.taskData.template.items, {type: 'iframe'});
            var item = $filter('filter')(self.taskData.template.items, {id: message.template_item});
            if (inputItems.length == 0 && item.length && item[0].aux_attributes.src.indexOf(message.daemo_id) > 0) {
                item[0].isSubmitted = true;
                var submitted = $filter('filter')(self.taskData.template.items, {
                    isSubmitted: true,
                    type: 'iframe'
                });
                if (remoteContentItems.length == submitted.length) {
                    self.submit();
                }
            }
            $scope.$apply();
        }

        function rejectHIT() {
            if (!self.rejectionReason) {
                $mdToast.showSimple('Please choose a reason');
                return;
            }

            if (self.rejectionReason == self.reject_reason.OTHER && (!self.rejectionDetail || self.rejectionDetail == '')) {
                $mdToast.showSimple('Please provide details for flagging');
                return;
            }

            var request_data = {
                worker_id: $stateParams.workerId,
                assignment_id: $stateParams.assignmentId,
                hit_id: $stateParams.hitId,
                reason: self.rejectionReason,
                detail: self.rejectionDetail
            };

            HIT.reject(self.pk, request_data).then(
                function success(data, status) {
                    self.HITRejected = true;
                },
                function error(data, status) {
                    $mdToast.showSimple("Could not reject HIT!");
                }).finally(function () {
                }
            );
        }
    }
})
();

<|endoftext|>


<commit_before>import React, { useCallback, useState } from "react";
import styled from "styled-components";
import PropTypes from "prop-types";

import Button from "@agir/front/genericComponents/Button";
import AnimatedMoreHorizontal from "@agir/front/genericComponents/AnimatedMoreHorizontal";

import {
  ELU_STATUTS,
  InfosElu,
  ISSUE,
  RequestStatus,
  StatutPill,
} from "../types";
import { creerRechercheParrainage } from "../queries";
import Formulaire from "./Formulaire";
import { MarginBlock, Error } from "../utils";

const HorairesList = styled.ul`
  list-style-type: none;
  margin: 0;
  padding: 0;
`;

const capitalize = (s) => s.charAt(0).toUpperCase() + s.slice(1);

const Horaires = ({ horaires }) => {
  return (
    <HorairesList>
      {horaires.map(([j1, j2, hs]) => {
        const jours = j1 === j2 ? capitalize(j1) : `${capitalize(j1)} au ${j2}`;
        const heures = hs
          .map(([h1, h2]) => `${h1.slice(0, 5)} — ${h2.slice(0, 5)}`)
          .join(" et ");
        return (

            {jours} : {heures}

        );
      })}
    </HorairesList>
  );
};
Horaires.propTypes = {
  horaires: PropTypes.array,
};

const BoutonCreerParrainage = ({ elu, onStatusChange }) => {
  const [state, setState] = useState(RequestStatus.IDLE());
  const callback = useCallback(async () => {
    setState(RequestStatus.LOADING());
    try {
      const res = await creerRechercheParrainage(elu.id);
      setState(RequestStatus.IDLE());
      onStatusChange({
        ...elu,
        statut: ELU_STATUTS.A_CONTACTER,
        idRechercheParrainage: res.id,
      });
    } catch (e) {
      setState(RequestStatus.ERROR(e.message));
    }
  }, [elu, onStatusChange]);

  return (

      <Button color="primary" onClick={callback} disabled={state.loading}>
        Je m'en occupe !
      </Button>
      {state.loading && <AnimatedMoreHorizontal />}
      {state.hasError && <Error>{state.message}</Error>}

  );
};
BoutonCreerParrainage.propTypes = {
  elu: InfosElu,
  onStatusChange: PropTypes.func,
};

const InteractionBoxLayout = styled(MarginBlock)`
  border: 1px solid ${(props) => props.theme.black200};
  padding: 20px;
`;

const InteractionBox = ({ elu, onStatusChange }) => {
  const demonstratif = elu.sexe === "F" ? "cette élue" : "cet élu";

  switch (elu.statut) {
    case "D":
      return (
        <InteractionBoxLayout>

Personne n'a indiqué s'occuper de {demonstratif}.

          <BoutonCreerParrainage elu={elu} onStatusChange={onStatusChange} />
        </InteractionBoxLayout>
      );
    case "E":
      return (
        <InteractionBoxLayout>
          Quelqu'un d'autre a indiqué s'occuper de contacter {demonstratif}
          👍
        </InteractionBoxLayout>
      );
    case "A":
      return (
        <InteractionBoxLayout>
          <Formulaire elu={elu} onStatusChange={onStatusChange} />
        </InteractionBoxLayout>
      );
    case "T":
      return (
        <InteractionBoxLayout>
          Quelqu'un d'autre s'est déjà chargé de contacter {demonstratif}
        </InteractionBoxLayout>
      );
    case "P":
      return (
        <InteractionBoxLayout>

            Merci de vous être occupé⋅e de contacter cette personne 🚀

          {elu.rechercheParrainage?.statut === ISSUE.VALIDE ? (

              Son parrainage a été correctement reçu et confirmé. Bravo
              👏👏👏👏

          ) : (
            <>

                Vous pourrez revenir sur cette page mettre à jour les
                informations en cas de changement de situation.

              <Formulaire elu={elu} onStatusChange={onStatusChange} />
            </>
          )}
        </InteractionBoxLayout>
      );
    case "C":
      return (
        <InteractionBoxLayout>
          Le conseil constitutionnel a déjà reçu et validé le parrainage de{" "}
          {demonstratif} pour {elu.parrainageFinal}.
        </InteractionBoxLayout>
      );
  }
};
InteractionBox.propTypes = {
  elu: InfosElu,
  onStatusChange: PropTypes.func,
};

const Layout = styled.div`
  padding: 60px;

  @media (max-width: ${(props) => props.theme.collapse}px) {
    padding: 0 35px;
  }

  ${MarginBlock} {
    font-size: 16px;
  }

  .entete {
    margin-bottom: 30px;
  }
  h2 {
    margin-bottom: 0.5rem;
  }
  .subtitle {
    font-size: 16px;
  }
  .explication {
    text-decoration: underline dashed;
    cursor: help;
  }

  h3 {
    margin-bottom: 0;
  }

  label {
    display: block;
    margin: 0;
    font-weight: 400;
  }

  label.title,
  h4 {
    font-weight: 700;
    font-size: 14px;
    margin: 20px 0 8px;
  }

  ${Button} {
    margin: 11px 0;
  }
`;

const ColonneCentree = styled.div`
  margin: 0 auto;
  max-width: 600px;
`;

const FicheElu = ({ elu, onStatusChange }) => {
  const mairie = elu.mairie;
  const distance = elu.distance?.toLocaleString?.("fr-FR", {
    maximumFractionDigits: 1,
  });

  return (
    <Layout>
      <ColonneCentree>

{elu.nomComplet}

            {elu.titre} — {elu.commune}
            {distance &&
              (elu.distance > 0.1
                ? ` (à ${distance} km)`
                : " (à moins de 100m)")}

          {elu.pcsLabel && (

              {elu.pcsLabel} (

                cat. {elu.pcs}

              )

          )}

        <MarginBlock>
          <StatutPill statut={elu.statut} />
        </MarginBlock>
        <InteractionBox elu={elu} onStatusChange={onStatusChange} />
        {mairie.adresse && (
          <MarginBlock>

Adresse de la mairie

{mairie.adresse}

          </MarginBlock>
        )}
        {mairie.telephone && (
          <MarginBlock>

Numéro de téléphone de la mairie

{mairie.telephone}

          </MarginBlock>
        )}
        {mairie.email && (
          <MarginBlock>

Adresse email de la mairie

              <a
                href={
                  mairie.email.match(/https?:\/\//)
                    ? mairie.email
                    : `mailto:${mairie.email}`
                }
              >
                {mairie.email}

          </MarginBlock>
        )}
        {mairie.horaires && mairie.horaires.length !== 0 && (
          <MarginBlock>

Horaires d'ouverture de la mairie

            <Horaires horaires={mairie.horaires} />
          </MarginBlock>
        )}
      </ColonneCentree>
    </Layout>
  );
};

FicheElu.propTypes = {
  elu: InfosElu,
  onStatusChange: PropTypes.func,
};
FicheElu.Layout = Layout;

export default FicheElu;
<commit_msg>fix: bug d'affichage des mairies sans horaires<commit_after>*import React, { useCallback, useState } from "react";
import styled from "styled-components";
import PropTypes from "prop-types";

import Button from "@agir/front/genericComponents/Button";
import AnimatedMoreHorizontal from "@agir/front/genericComponents/AnimatedMoreHorizontal";

import {
  ELU_STATUTS,
  InfosElu,
  ISSUE,
  RequestStatus,
  StatutPill,
} from "../types";
import { creerRechercheParrainage } from "../queries";
import Formulaire from "./Formulaire";
import { MarginBlock, Error } from "../utils";

const HorairesList = styled.ul`
  list-style-type: none;
  margin: 0;
  padding: 0;
`;

const capitalize = (s) => s.charAt(0).toUpperCase() + s.slice(1);

const Horaires = ({ horaires }) => {
  return (
    <HorairesList>
      {horaires.map && horaires.map(([j1, j2, hs]) => {
        const jours = j1 === j2 ? capitalize(j1) : `${capitalize(j1)} au ${j2}`;
        const heures = hs
          .map(([h1, h2]) => `${h1.slice(0, 5)} — ${h2.slice(0, 5)}`)
          .join(" et ");
        return (

            {jours} : {heures}

        );
      })}
    </HorairesList>
  );
};
Horaires.propTypes = {
  horaires: PropTypes.array,
};

const BoutonCreerParrainage = ({ elu, onStatusChange }) => {
  const [state, setState] = useState(RequestStatus.IDLE());
  const callback = useCallback(async () => {
    setState(RequestStatus.LOADING());
    try {
      const res = await creerRechercheParrainage(elu.id);
      setState(RequestStatus.IDLE());
      onStatusChange({
        ...elu,
        statut: ELU_STATUTS.A_CONTACTER,
        idRechercheParrainage: res.id,
      });
    } catch (e) {
      setState(RequestStatus.ERROR(e.message));
    }
  }, [elu, onStatusChange]);

  return (

      <Button color="primary" onClick={callback} disabled={state.loading}>
        Je m'en occupe !
      </Button>
      {state.loading && <AnimatedMoreHorizontal />}
      {state.hasError && <Error>{state.message}</Error>}

  );
};
BoutonCreerParrainage.propTypes = {
  elu: InfosElu,
  onStatusChange: PropTypes.func,
};

const InteractionBoxLayout = styled(MarginBlock)`
  border: 1px solid ${(props) => props.theme.black200};
  padding: 20px;
`;

const InteractionBox = ({ elu, onStatusChange }) => {
  const demonstratif = elu.sexe === "F" ? "cette élue" : "cet élu";

  switch (elu.statut) {
    case "D":
      return (
        <InteractionBoxLayout>

Personne n'a indiqué s'occuper de {demonstratif}.

          <BoutonCreerParrainage elu={elu} onStatusChange={onStatusChange} />
        </InteractionBoxLayout>
      );
    case "E":
      return (
        <InteractionBoxLayout>
          Quelqu'un d'autre a indiqué s'occuper de contacter {demonstratif}
          👍
        </InteractionBoxLayout>
      );
    case "A":
      return (
        <InteractionBoxLayout>
          <Formulaire elu={elu} onStatusChange={onStatusChange} />
        </InteractionBoxLayout>
      );
    case "T":
      return (
        <InteractionBoxLayout>
          Quelqu'un d'autre s'est déjà chargé de contacter {demonstratif}
        </InteractionBoxLayout>
      );
    case "P":
      return (
        <InteractionBoxLayout>

            Merci de vous être occupé⋅e de contacter cette personne 🚀

          {elu.rechercheParrainage?.statut === ISSUE.VALIDE ? (

              Son parrainage a été correctement reçu et confirmé. Bravo
              👏👏👏👏

          ) : (
            <>

                Vous pourrez revenir sur cette page mettre à jour les
                informations en cas de changement de situation.

              <Formulaire elu={elu} onStatusChange={onStatusChange} />
            </>
          )}
        </InteractionBoxLayout>
      );
    case "C":
      return (
        <InteractionBoxLayout>
          Le conseil constitutionnel a déjà reçu et validé le parrainage de{" "}
          {demonstratif} pour {elu.parrainageFinal}.
        </InteractionBoxLayout>
      );
  }
};
InteractionBox.propTypes = {
  elu: InfosElu,
  onStatusChange: PropTypes.func,
};

const Layout = styled.div`
  padding: 60px;

  @media (max-width: ${(props) => props.theme.collapse}px) {
    padding: 0 35px;
  }

  ${MarginBlock} {
    font-size: 16px;
  }

  .entete {
    margin-bottom: 30px;
  }
  h2 {
    margin-bottom: 0.5rem;
  }
  .subtitle {
    font-size: 16px;
  }
  .explication {
    text-decoration: underline dashed;
    cursor: help;
  }

  h3 {
    margin-bottom: 0;
  }

  label {
    display: block;
    margin: 0;
    font-weight: 400;
  }

  label.title,
  h4 {
    font-weight: 700;
    font-size: 14px;
    margin: 20px 0 8px;
  }

  ${Button} {
    margin: 11px 0;
  }
`;

const ColonneCentree = styled.div`
  margin: 0 auto;
  max-width: 600px;
`;

const FicheElu = ({ elu, onStatusChange }) => {
  const mairie = elu.mairie;
  const distance = elu.distance?.toLocaleString?.("fr-FR", {
    maximumFractionDigits: 1,
  });

  return (
    <Layout>
      <ColonneCentree>

{elu.nomComplet}

            {elu.titre} — {elu.commune}
            {distance &&
              (elu.distance > 0.1
                ? ` (à ${distance} km)`
                : " (à moins de 100m)")}

          {elu.pcsLabel && (

              {elu.pcsLabel} (

                cat. {elu.pcs}

              )

          )}

        <MarginBlock>
          <StatutPill statut={elu.statut} />
        </MarginBlock>
        <InteractionBox elu={elu} onStatusChange={onStatusChange} />
        {mairie.adresse && (
          <MarginBlock>

Adresse de la mairie

{mairie.adresse}

          </MarginBlock>
        )}
        {mairie.telephone && (
          <MarginBlock>

Numéro de téléphone de la mairie

{mairie.telephone}

          </MarginBlock>
        )}
        {mairie.email && (
          <MarginBlock>

Adresse email de la mairie

              <a
                href={
                  mairie.email.match(/https?:\/\//)
                    ? mairie.email
                    : `mailto:${mairie.email}`
                }
              >
                {mairie.email}

          </MarginBlock>
        )}
        {mairie.horaires && mairie.horaires.length !== 0 && (
          <MarginBlock>

Horaires d'ouverture de la mairie

            <Horaires horaires={mairie.horaires} />
          </MarginBlock>
        )}
      </ColonneCentree>
    </Layout>
  );
};

FicheElu.propTypes = {
  elu: InfosElu,
  onStatusChange: PropTypes.func,
};
FicheElu.Layout = Layout;

export default FicheElu;
<|endoftext|>


<commit_before>/**
 * AMD plugin that loads JSON Schema files (using text plugin).
 * See http://tools.ietf.org/html/draft-zyp-json-schema-03.
 *
 * It also resolves $refs within the schema, executing additional requests until
 * the schema is fully resolved. The additional requests are self-executing using local require,
 * to take advantage of AMD caching of each file.
 *
 * This plugin works like so:
 * 1) Get a schema using ajax, from the configured location (such as a directory service, or file system)
 * 2) Recursively examine that schema for all $ref fields that point to a different schema
 * 3) Construct a list of "dependencies" from the $ref fields, and issue a parentRequire using this very same plugin
 * 4) Replace the $ref values with full objects once they are retrieved from the parentRequire
 *
 * In this manner, it will descend the schema graph until all are retrieved and attached to the original entry point schema.
 * Conveniently, every parentRequire for a child schema results in caching so the next schema will be constructed more quickly.
 *
 * An optional name formatter for the schema IDs (module names) can be supplied, in order to provide a configurable mechanism for
 * preparing IDs for ajax request, such as by prepending with a server name. A default formatter that leaves
 * the ID unmodified is supplied, to account for IDs that resolve properly already, or the use of other aliasing mechanisms.
 *
 * A "sync" config option allows you to force this plugin to use a synchronous XHR instead of the requirejs text plugin.
 * This is useful for projects that have synchronous dependency issues (e.g., those that are transitioning with dojo).
 *
 * LIMITATION: the plugin does not yet attempt any extra id resolution from the jsonschema spec, such as "#".
 *
 */
define([
    "./text",
    "module"
], function (
    text,
    module
) {

    var defaultFormatter = function (name) {
            return name;
        },
        config = module.config(),
        formatter = config ? (config.formatter || defaultFormatter) : defaultFormatter,
        sync = config.sync,
        plugin;

    function getSchema(name, parentRequire, callback) {

        //recursively find all of the $ref items in an object and compile them into a map so there won't be any duplicates
        function findRefs(schema) {

            function walk(obj, refs) {

                Object.keys(obj).forEach(function (key) {

                    var value = obj[key];

                    if (key === "$ref" && !refs[value]) {
                        refs[value] = true; //using an object so we skip dups
                    } else if (typeof value === "object") {
                        walk(value, refs);
                    }

                });

                return refs;

            }

            var starter = {};
            starter[schema.id] = true; //make sure to include the current schema
            return walk(schema, starter);

        }

        //given a list of schema objects, find one with an id that matches the specified id
        function findSchema(id, schemas) {
            var result;
            schemas.some(function (schema) {
                if (schema.id === id) {
                    result = schema;
                    return true;
                }
            });
            return result;
        }

        //resolve an initial schema retrieved via ajax, delegating to this same plugin for child dependencies in a batch
        function resolve(schema, parentRequire, callback) {

            var refs = findRefs(schema, {}),
                refNames = [];

            //make a list of names from the map of ids found in ref search
            Object.keys(refs).forEach(function (ref) {
                if (ref !== name) {
                    refNames.push(module.id + "!" + ref);
                }
            });

            if (refNames.length > 0) {

                parentRequire(refNames, function () {

                    var schemas = Array.prototype.slice.call(arguments);
                    //we've got a set of schema objects, now we need to replace the $ref from the parent with them
                    schema = placeRefs(schema, schemas);

                    callback(schema);
                });

            } else {
                callback(schema);
            }

        }

        //recursively descend an object, replacing all $ref values with the retrieved schemas
        function placeRefs(schema, refObjects) {

            function walk(obj, refObjects) {

                Object.keys(obj).forEach(function (key) {

                    var value = obj[key],
                        subschema;

                    if (key === "$ref") {
                        subschema = findSchema(value, refObjects);
                        obj = subschema;
                        if (!obj.resolved) {
                            obj.resolved = true; //don't do it again
                            obj = walk(obj, refObjects);
                        }
                    } else if (typeof value === "object") {
                        if (!value.resolved) {
                            value.resolved = true; //don't do it again
                            value = walk(value, refObjects);
                        }
                        obj[key] = value;
                    }

                });

                return obj;
            }

            return walk(schema, refObjects);
        }

        var formattedName = formatter(name),
            url = parentRequire.toUrl(formattedName),
            xhr,
            handler = function (schemaText) {
                var json = JSON.parse(schemaText);
                resolve(json, parentRequire, callback);
            };

        //use native XHR if sync is requested, or delegate to text plugin
        if (sync) {
            xhr = new XMLHttpRequest();
            xhr.open("GET", url, false);
            xhr.send();
            handler(xhr.responseText);
        } else {
            text.get(url,
                handler,
                function (err) {
                    throw new Error(err); //text plugin assumes an err callback, we'll just throw so the message can be seen
                });
        }

    }

    plugin = {

        load: function (name, parentRequire, onload, config) {

            getSchema(name, parentRequire, onload);

        }
    };

    return plugin;

});<commit_msg>pushing parent schema into list so it can be found when self-referencing<commit_after>/**
 * AMD plugin that loads JSON Schema files (using text plugin).
 * See http://tools.ietf.org/html/draft-zyp-json-schema-03.
 *
 * It also resolves $refs within the schema, executing additional requests until
 * the schema is fully resolved. The additional requests are self-executing using local require,
 * to take advantage of AMD caching of each file.
 *
 * This plugin works like so:
 * 1) Get a schema using ajax, from the configured location (such as a directory service, or file system)
 * 2) Recursively examine that schema for all $ref fields that point to a different schema
 * 3) Construct a list of "dependencies" from the $ref fields, and issue a parentRequire using this very same plugin
 * 4) Replace the $ref values with full objects once they are retrieved from the parentRequire
 *
 * In this manner, it will descend the schema graph until all are retrieved and attached to the original entry point schema.
 * Conveniently, every parentRequire for a child schema results in caching so the next schema will be constructed more quickly.
 *
 * An optional name formatter for the schema IDs (module names) can be supplied, in order to provide a configurable mechanism for
 * preparing IDs for ajax request, such as by prepending with a server name. A default formatter that leaves
 * the ID unmodified is supplied, to account for IDs that resolve properly already, or the use of other aliasing mechanisms.
 *
 * A "sync" config option allows you to force this plugin to use a synchronous XHR instead of the requirejs text plugin.
 * This is useful for projects that have synchronous dependency issues (e.g., those that are transitioning with dojo).
 *
 * LIMITATION: the plugin does not yet attempt any extra id resolution from the jsonschema spec, such as "#".
 *
 */
define([
    "./text",
    "module"
], function (
    text,
    module
) {

    var defaultFormatter = function (name) {
            return name;
        },
        config = module.config(),
        formatter = config ? (config.formatter || defaultFormatter) : defaultFormatter,
        sync = config.sync,
        plugin;

    function getSchema(name, parentRequire, callback) {

        //recursively find all of the $ref items in an object and compile them into a map so there won't be any duplicates
        function findRefs(schema) {

            function walk(obj, refs) {

                Object.keys(obj).forEach(function (key) {

                    var value = obj[key];

                    if (key === "$ref" && !refs[value]) {
                        refs[value] = true; //using an object so we skip dups
                    } else if (typeof value === "object") {
                        walk(value, refs);
                    }

                });

                return refs;

            }

            return walk(schema, {});

        }

        //given a list of schema objects, find one with an id that matches the specified id
        function findSchema(id, schemas) {
            var result;
            schemas.some(function (schema) {
                if (schema.id === id) {
                    result = schema;
                    return true;
                }
            });
            return result;
        }

        //resolve an initial schema retrieved via ajax, delegating to this same plugin for child dependencies in a batch
        function resolve(schema, parentRequire, callback) {

            var refs = findRefs(schema, {}),
                refNames = [];

            //make a list of names from the map of ids found in ref search
            Object.keys(refs).forEach(function (ref) {
                if (ref !== name) {
                    refNames.push(module.id + "!" + ref);
                }
            });

            if (refNames.length > 0) {

                parentRequire(refNames, function () {

                    var schemas = Array.prototype.slice.call(arguments);
                    //make sure to include the current schema in case of recursion - we didn't want to ajax this again
                    schemas.push(schema);

                    //we've got a set of schema objects, now we need to replace the $ref from the parent with them
                    schema = placeRefs(schema, schemas);

                    callback(schema);
                });

            } else {
                callback(schema);
            }

        }

        //recursively descend an object, replacing all $ref values with the retrieved schemas
        function placeRefs(schema, refObjects) {

            function walk(obj, refObjects) {

                Object.keys(obj).forEach(function (key) {

                    var value = obj[key],
                        subschema;

                    if (key === "$ref") {
                        subschema = findSchema(value, refObjects);
                        obj = subschema;
                        if (!obj.resolved) {
                            obj.resolved = true; //don't do it again
                            obj = walk(obj, refObjects);
                        }
                    } else if (typeof value === "object") {
                        if (!value.resolved) {
                            value.resolved = true; //don't do it again
                            value = walk(value, refObjects);
                        }
                        obj[key] = value;
                    }

                });

                return obj;
            }

            return walk(schema, refObjects);
        }

        var formattedName = formatter(name),
            url = parentRequire.toUrl(formattedName),
            xhr,
            handler = function (schemaText) {
                var json = JSON.parse(schemaText);
                resolve(json, parentRequire, callback);
            };

        //use native XHR if sync is requested, or delegate to text plugin
        if (sync) {
            xhr = new XMLHttpRequest();
            xhr.open("GET", url, false);
            xhr.send();
            handler(xhr.responseText);
        } else {
            text.get(url,
                handler,
                function (err) {
                    throw new Error(err); //text plugin assumes an err callback, we'll just throw so the message can be seen
                });
        }

    }

    plugin = {

        load: function (name, parentRequire, onload, config) {

            getSchema(name, parentRequire, onload);

        }
    };

    return plugin;

});<|endoftext|>


<commit_before>import React, { Component } from "react";

class DogQuestionnaire extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      results = [],
      dogform = {
        age: ''
      },
      catform: {
        age: ''
      }
    }

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange = event => {
    const { name, value } = event.target;
    this.setState({
      [name]: value
    });
  };

  handleSubmit(event) {
    alert('The questionnaire was submitted: ' + this.state.value);
    event.preventDefault();
  }

  render() {
    return (

{props.children}

    );
  }

export default Handler;<commit_msg>saving current state<commit_after>import React, { Component } from "react";

class Handler extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      results = [],
      dogform = {
        age: ''
      },
      catform: {
        age: ''
      }
    }

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange = event => {
    const { name, value } = event.target;
    this.setState({
      [name]: value
    });
  };

  handleSubmit(event) {
    alert('The questionnaire was submitted: ' + this.state.value);
    event.preventDefault();
  }

  render() {
    return (

{props.children}

    );
  }

}

export default Handler;<|endoftext|>