<commit_before>export default {
  lang: 'th',
  label: {
    clear: 'ล้าง',
    ok: 'ตกลง',
    cancel: 'ยกเลิก',
    close: 'ปิด',
    set: 'ตั้งค่า',
    select: 'เลือก',
    reset: 'ตั้งใหม่',
    remove: 'ลบ',
    update: 'ปรับปรุง',
    create: 'สร้าง',
    search: 'ค้นหา',
    filter: 'กรอง',
    refresh: 'รีเฟรช'
  },
  date: {
    days: 'อาทิตย์_จันทร์_อังคาร_พุธ_พฤหัสบดี_ศุกร์_เสาร์'.split('_'),
    daysShort: 'อา._จ._อ._พ._พฤ_.ศ._ส.'.split('_'),
    months: 'มกราคม_กุมภาพันธ์_มีนาคม_เมษายน_พฤษภาคม_มิถุนายน_กรกฎาคม_สิงหาคม_กันยายน_ตุลาคม_พฤศจิกายน_ธันวาคม'.split('_'),
    monthsShort: 'ม.ค._ก.พ._มี.ค._เม.ย._พ.ค._มิ.ย._ก.ค._ส.ค._ก.ย._ต.ค._พ.ย._ธ.ค.'.split('_'),
    firstDayOfWeek: 0, // 0-6, 0 - Sunday, 1 Monday, ...
    format24h: true
  },
  pullToRefresh: {
    pull: 'ดึงลงเพื่อรีเฟรช',
    release: 'ปล่อยเพื่อรีเฟรช',
    refresh: 'กำลังรีเฟรช...'
  },
  table: {
    noData: 'ไม่มีข้อมูล',
    noResults: 'ไม่มีผลลัพธ์',
    loading: 'กำลังโหลด...',
    selectedRecords: function (rows) {
      return rows > 0
        ? 'เลือกทั้งหมด ' + rows + ' แถว'
        : 'ไม่มีแถวที่ถูกเลือก'
    },
    recordsPerPage: 'แถวต่อหน้า:',
    allRows: 'แถวทั้งหมด',
    pagination: function (start, end, total) {
      return start + '-' + end + ' of ' + total
    },
    columns: 'คอลัมน์'
  },
  editor: {
    url: 'URL',
    bold: 'ตัวหนา',
    italic: 'ตัวเอียง',
    strikethrough: 'เส้นคร่อม',
    underline: 'เส้นใต้',
    unorderedList: 'รายการ',
    orderedList: 'ลำดับรายการ',
    subscript: 'ตัวห้อย',
    superscript: 'ตัวยก',
    hyperlink: 'ไฮเปอร์ลิงค์',
    toggleFullscreen: 'สลับเต็มจอ',
    quote: 'อ้างอิง',
    left: 'ชิดซ้าย',
    center: 'แนวกลาง',
    right: 'ชิดขวา',
    justify: 'ชิดขอบ',
    print: 'พิมพ์',
    outdent: 'ลดย่อหน้า',
    indent: 'เพิ่มย่อหน้า',
    removeFormat: 'ล้างรูปแบบ',
    formatting: 'จัดรูปแบบ',
    fontSize: 'ขนาดอักษร',
    align: 'แนว',
    hr: 'เพิ่มเส้นขั้นบรรทัด',
    undo: 'ยกเลิก',
    redo: 'ทำซ้ำ',
    header1: 'หัวข้อ 1',
    header2: 'หัวข้อ 2',
    header3: 'หัวข้อ 3',
    header4: 'หัวข้อ 4',
    header5: 'หัวข้อ 5',
    header6: 'หัวข้อ 6',
    paragraph: 'ย่อหน้า',
    code: 'โค้ด',
    size1: 'เล็กมาก',
    size2: 'เล็ก',
    size3: 'ปกติ',
    size4: 'ใหญ่กว่าปกติ',
    size5: 'ใหญ่',
    size6: 'ใหญ่มาก',
    size7: 'ใหญ่เต็มที่',
    defaultFont: 'ฟอนต์มาตรฐาน'
  },
  tree: {
    noNodes: 'ไม่มีโหนด',
    noResults: 'ไม่พบโหนดตามที่ระบุ'
  }
}
<commit_msg>First day of week for Thailand is Monday<commit_after>export default {
  lang: 'th',
  label: {
    clear: 'ล้าง',
    ok: 'ตกลง',
    cancel: 'ยกเลิก',
    close: 'ปิด',
    set: 'ตั้งค่า',
    select: 'เลือก',
    reset: 'ตั้งใหม่',
    remove: 'ลบ',
    update: 'ปรับปรุง',
    create: 'สร้าง',
    search: 'ค้นหา',
    filter: 'กรอง',
    refresh: 'รีเฟรช'
  },
  date: {
    days: 'อาทิตย์_จันทร์_อังคาร_พุธ_พฤหัสบดี_ศุกร์_เสาร์'.split('_'),
    daysShort: 'อา._จ._อ._พ._พฤ_.ศ._ส.'.split('_'),
    months: 'มกราคม_กุมภาพันธ์_มีนาคม_เมษายน_พฤษภาคม_มิถุนายน_กรกฎาคม_สิงหาคม_กันยายน_ตุลาคม_พฤศจิกายน_ธันวาคม'.split('_'),
    monthsShort: 'ม.ค._ก.พ._มี.ค._เม.ย._พ.ค._มิ.ย._ก.ค._ส.ค._ก.ย._ต.ค._พ.ย._ธ.ค.'.split('_'),
    firstDayOfWeek: 1, // 0-6, 0 - Sunday, 1 Monday, ...
    format24h: true
  },
  pullToRefresh: {
    pull: 'ดึงลงเพื่อรีเฟรช',
    release: 'ปล่อยเพื่อรีเฟรช',
    refresh: 'กำลังรีเฟรช...'
  },
  table: {
    noData: 'ไม่มีข้อมูล',
    noResults: 'ไม่มีผลลัพธ์',
    loading: 'กำลังโหลด...',
    selectedRecords: function (rows) {
      return rows > 0
        ? 'เลือกทั้งหมด ' + rows + ' แถว'
        : 'ไม่มีแถวที่ถูกเลือก'
    },
    recordsPerPage: 'แถวต่อหน้า:',
    allRows: 'แถวทั้งหมด',
    pagination: function (start, end, total) {
      return start + '-' + end + ' of ' + total
    },
    columns: 'คอลัมน์'
  },
  editor: {
    url: 'URL',
    bold: 'ตัวหนา',
    italic: 'ตัวเอียง',
    strikethrough: 'เส้นคร่อม',
    underline: 'เส้นใต้',
    unorderedList: 'รายการ',
    orderedList: 'ลำดับรายการ',
    subscript: 'ตัวห้อย',
    superscript: 'ตัวยก',
    hyperlink: 'ไฮเปอร์ลิงค์',
    toggleFullscreen: 'สลับเต็มจอ',
    quote: 'อ้างอิง',
    left: 'ชิดซ้าย',
    center: 'แนวกลาง',
    right: 'ชิดขวา',
    justify: 'ชิดขอบ',
    print: 'พิมพ์',
    outdent: 'ลดย่อหน้า',
    indent: 'เพิ่มย่อหน้า',
    removeFormat: 'ล้างรูปแบบ',
    formatting: 'จัดรูปแบบ',
    fontSize: 'ขนาดอักษร',
    align: 'แนว',
    hr: 'เพิ่มเส้นขั้นบรรทัด',
    undo: 'ยกเลิก',
    redo: 'ทำซ้ำ',
    header1: 'หัวข้อ 1',
    header2: 'หัวข้อ 2',
    header3: 'หัวข้อ 3',
    header4: 'หัวข้อ 4',
    header5: 'หัวข้อ 5',
    header6: 'หัวข้อ 6',
    paragraph: 'ย่อหน้า',
    code: 'โค้ด',
    size1: 'เล็กมาก',
    size2: 'เล็ก',
    size3: 'ปกติ',
    size4: 'ใหญ่กว่าปกติ',
    size5: 'ใหญ่',
    size6: 'ใหญ่มาก',
    size7: 'ใหญ่เต็มที่',
    defaultFont: 'ฟอนต์มาตรฐาน'
  },
  tree: {
    noNodes: 'ไม่มีโหนด',
    noResults: 'ไม่พบโหนดตามที่ระบุ'
  }
}
<|endoftext|>


<commit_before>$(document).ready(function(){
        // count character on keyup
        function counter(){
            var maxLength     = 140;
            var currentLength = $("#status_textarea").val().length;
            var remaining = 140 - currentLength;
            $("#counter").text(remaining);

            if(remaining <= 0) {
                $("#counter").attr("class", "toomuch");
                } else {
                $("#counter").attr("class", "");
                }
        }

        if ($("#status_textarea").length) {
            $("#status_textarea").bind("keyup", counter);
        }

});

<commit_msg>Removed some DOM lookups in the char counter<commit_after>$(document).ready(function(){
        // count character on keyup
        function counter(){
            var maxLength     = 140;
            var currentLength = $("#status_textarea").val().length;
            var remaining = 140 - currentLength;
            var counter = $("#counter");
            counter.text(remaining);

            if(remaining <= 0) {
                counter.attr("class", "toomuch");
                } else {
                counter.attr("class", "");
                }
        }

        if ($("#status_textarea").length) {
            $("#status_textarea").bind("keyup", counter);
        }

});

<|endoftext|>


<commit_before>#!/usr/bin/env node
/**
 * @fileOverview This sample code illustrates how one can read all collection files within a directory and run them
 * in parallel.
 */
var newman = require('../'), // require('newman')
    fs = require('fs');

fs.readdir('./examples', function (err, files) {
    if (err) { throw err; }

    // we filter all files with JSON file extension
    files = files.filter(function (file) {
    	return /^((?!(package(-lock)?))|.+)\.json/.test(file);
    });

    // now wer iterate on each file name and call newman.run using each file name
    files.forEach(function (file) {
        newman.run({
            // we load collection using require. for better validation and handling
            // JSON.parse could be used
            collection: require(`${__dirname}/${file}`)
        }, function (err) {
            // finally, when the collection executes, print the status
            console.info(`${file}: ${err ? err.name : 'ok'}!`);
        });
    }); // the entire flow can be made more elegant using `async` module
});
<commit_msg>Fix indentation<commit_after>#!/usr/bin/env node
/**
 * @fileOverview This sample code illustrates how one can read all collection files within a directory and run them
 * in parallel.
 */
var newman = require('../'), // require('newman')
    fs = require('fs');

fs.readdir('./examples', function (err, files) {
    if (err) { throw err; }

    // we filter all files with JSON file extension
    files = files.filter(function (file) {
        return /^((?!(package(-lock)?))|.+)\.json/.test(file);
    });

    // now wer iterate on each file name and call newman.run using each file name
    files.forEach(function (file) {
        newman.run({
            // we load collection using require. for better validation and handling
            // JSON.parse could be used
            collection: require(`${__dirname}/${file}`)
        }, function (err) {
            // finally, when the collection executes, print the status
            console.info(`${file}: ${err ? err.name : 'ok'}!`);
        });
    }); // the entire flow can be made more elegant using `async` module
});
<|endoftext|>


<commit_before>db.normalized.aggregate([
  {
    '$match': {
      // 'normalized.ein': '521798711'
      // 'normalized.ein': { $in: ['050509502', '521798711', '131684331'] }
    },
  },
  {
    '$unwind': {
      'path': '$normalized.grants',
      'includeArrayIndex': 'index_for_objectID',
      'preserveNullAndEmptyArrays': false,
    },
  },
  {
    '$project': {
      '_id': 0,
      'ein': '$normalized.ein',
      'organization_name': '$normalized.organization_name',
      'city': '$normalized.city',
      'state': '$normalized.state',
      'tax_year': '$normalized.tax_year',
      'grant_amount': '$normalized.grants.amount',
      'grant_purpose': '$normalized.grants.purpose',
      'grantee_name': '$normalized.grants.name',
      'grantee_city': '$normalized.grants.city',
      'grantee_state': '$normalized.grants.state',
      'grantee_country': '$normalized.grants.country',
      'grantee_is_foreign': '$normalized.grants.is_foreign',
      'index_for_objectID': 1,
    },
  }
]).forEach(function(x) {
  let newID = x.ein + '_' + x.tax_year + '_' + x.index_for_objectID;
  x.objectID = newID;
  x._id = newID;
  x.grant_number = x.index_for_objectID + 1;
  delete x.index_for_objectID;
  if (x.grantee_is_foreign) {
    x.grantee_state_displayed = x.grantee_country + '*';
  } else {
    x.grantee_state_displayed = x.grantee_state;
  }
  db.grants.insert(x);
});

// mongoexport --db irs --collection grants --out grants.json --jsonArray
<commit_msg>Use aggregate instead of forEach loop<commit_after>db.normalized.aggregate(
  [
    {
      '$match': {
        // 'normalized.ein': '521798711'
        // 'normalized.ein': { $in: ['050509502', '521798711', '131684331'] }
      },
    },
    {
      '$unwind': {
        'path': '$normalized.grants',
        'includeArrayIndex': 'index_for_objectID',
        'preserveNullAndEmptyArrays': false,
      },
    },
    {
      '$project': {
        '_id': 0,
        'objectID': {'$concat': [{'$substr': ['$normalized.ein', 0, -1]}, '_', {'$substr': ['$normalized.tax_year', 0, -1]}, '_', {'$substr': ['$index_for_objectID', 0, -1]}] },
        'ein': '$normalized.ein',
        'organization_name': '$normalized.organization_name',
        'city': '$normalized.city',
        'state': '$normalized.state',
        'tax_year': '$normalized.tax_year',
        'last_updated': { '$dateToString': { 'format': '%Y-%m-%dT%H:%M:%S.%L', 'date': '$normalized.last_updated'}},
        'last_updated_irs': { '$dateToString': { 'format': '%Y-%m-%dT%H:%M:%S.%L', 'date': '$normalized.last_updated_irs'}},
        'grant_amount': '$normalized.grants.amount',
        'grant_purpose': '$normalized.grants.purpose',
        'grantee_name': '$normalized.grants.name',
        'grantee_city': '$normalized.grants.city',
        'grantee_state': '$normalized.grants.state',
        'grantee_state_displayed': {
          '$cond': {
            'if': { '$eq': ['$normalized.grants.is_foreign', true]},
            'then': { '$concat': ['$normalized.grants.country', '*']},
            'else': '$normalized.grants.state',
          },
        },
        'grantee_country': '$normalized.grants.country',
        'grantee_is_foreign': '$normalized.grants.is_foreign',
        'grant_number': {'$sum': ['$index_for_objectID', 1]},
      },
    },
    { '$out': 'grants' },
  ],
  { 'allowDiskUse': true}
);

// mongoexport --db irs --collection grants --out grants.json --jsonArray
<|endoftext|>


<commit_before>(function (window, undefined) {
	"use strict";

	var sizes, sheets, matchers, $, F;

	$ = window.jQuery;
	F = window.Foundation;

	// find
	function find(array, callback) {
		var index, max, match;

		index = 0;
		max = array.length;

		if (typeof callback !== "function") {
			match = callback;
			callback = function (item) {
				return item === match;
			};
		}

		while (index < max) {
			if (callback(array[index])) { return array[index]; }
			index += 1;
		}
	}

	// each
	function each(array, callback) {
		var index, max;

		index = 0;
		max = array.length;

		if (!array || !max) { return; }

		while (index < max) {
			if (callback(array[index], index) === false) { return; }
			index += 1;
		}
	}

	// map
	function map(array, callback) {
		var index = 0,
			max = array.length,
			ret = [];

		if (!array || !max) { return ret; }

		while (index < max) {
			ret[index] = callback(array[index], index);
			index += 1;
		}

		return ret;
	}

	// compact
	function compact(array) {
		var ret = [];

		each(array, function (item) {
			if (item) { ret.push(item); }
		});

		return ret;
	}

	// unique
	function unique(array) {
		var ret = [];

		each(array, function (_a) {
			if (!find(ret, _a)) { ret.push(_a); }
		});

		return ret;
	}

	// create matcher
	function createMatcher(size) {
		matchers[size] = new RegExp(" " + size + "\\-height\\-(\\S+)");
	}

	// create sheet
	function createSheet(size) {
		sheets[size] = createStylesheet(F.media_queries[size]);
	}

	// create a style element
	// returns a reference to the created style element's sheet property.
	// accepts a media query applied to the created stylesheet.
	// inspired by http://davidwalsh.name/add-rules-stylesheets
	function createStylesheet(media) {
		var style;

		// create a style element
		style = document.createElement("style");

		// webkit hack
		style.appendChild(document.createTextNode(""));

		if (media) {
			style.setAttribute("media", media);
		}

		// add the style element to the page
		document.head.appendChild(style);

		return style.sheet;
	}

	// delete rules for all responsive-equalized-heights stylesheets
	function deleteRules() {
		each(sizes, function (size) {
			var sheet = sheets[size];

			while (sheet.cssRules.length) {
				sheet.deleteRule(0);
			}
		});
	}

	// insert a rule into a stylesheet
	function insertRule(sheet, rule) {
		sheet.insertRule(rule, sheet.cssRules.length);
	}

	// get array of active screen sizes
	// the current screen size is the last active size in the array
	function getActiveSizes() {
		return compact(map(sizes, function (size) {
			if (matchMedia(F.media_queries[size]).matches) {
				return size;
			}
		}));
	}

	// update stylesheet rules
	function updateRules() {
		deleteRules();
		addRules();
	}

	// create responsive height rules
	function addRules() {
		var cache, activeSizes, $elems, groups;

		// setup groups and element cache
		groups = [];
		cache = {};
		activeSizes = getActiveSizes();

		each(activeSizes, function (size) {
			cache[size] = {};
		});

		// general selector will find all possible matches
		$elems = $('[class*="-height-"]');

		// filter possible matches to find real size groups
		$elems = $elems.filter(function (index, elem) {
			var match;

			each(activeSizes, function (size) {
				var sizeMatch, group;

				sizeMatch = matchers[size].exec(" " + elem.className);

				if (sizeMatch) {
					group = sizeMatch[1];

					if (group !== "auto")
						match = true;

						// save group name
						groups.push(group);

						// cache element under size group
						if (cache[size][group]) {
							cache[size][group] = $(cache[size][group]).add(elem);
						} else {
							cache[size][group] = $(elem);
						}
					}
				}
			});

			return match;
		});

		// create unique list of groups
		groups = unique(groups);

		// process each group
		each(groups, function (group) {
			var $group, groupHeight;

			$group = $();

			// add each cached size group, filtering out those elements that have a size override in any larger active size
			each(activeSizes, function (size, sizeIndex) {
				var largerSizes, $sizeGroup;

				if (cache[size][group]) {
					largerSizes = activeSizes.slice(sizeIndex + 1);
					$sizeGroup = cache[size][group];

					if (largerSizes.length) {
						$sizeGroup = $sizeGroup.filter(function (index, elem) {
							var override;

							each(largerSizes, function (largerSize) {
								override = matchers[largerSize].exec(" " + elem.className);

								if (override) { return false; }
							});

							return !override;
						});
					}

					$group = $group.add($sizeGroup);
				}
			});

			// if there are active elements for this group
			// create rules
			if ($group.length) {
				// find max element height in group
				// use outerHeight to include padding and border because of box-sizing: border-box;
				// add one px to account for zoomed factional pixels
				groupHeight = 1 + Math.max.apply(null, $group.map(function (index, elem) { return $(elem).outerHeight(); }));

				// write CSS rules for active sizes and groups
				each(activeSizes, function (size) {
					insertRule(sheets[size], "." + size + "-height-" + group + " { height: " + groupHeight + "px; }");
				});
			}
		});
	}

	// setup sizes
	sizes = "small medium large xlarge xxlarge".split(" ");

	// setup matcher regexps
	matchers = {};
	each(sizes, createMatcher);

	// setup responsive height stylesheets
	sheets = {};
	each(sizes, createSheet);

	// initialize rules
	addRules();

	// window resize handler
	$(window).on("resize", F.utils.throttle(updateRules, 250));

	// expose to the outside world
	F.responsive_heights = {
		stylesheets: sheets,
		update: updateRules,
		remove: deleteRules
	};
})(this);
<commit_msg>Missing curly brace.<commit_after>(function (window, undefined) {
	"use strict";

	var sizes, sheets, matchers, $, F;

	$ = window.jQuery;
	F = window.Foundation;

	// find
	function find(array, callback) {
		var index, max, match;

		index = 0;
		max = array.length;

		if (typeof callback !== "function") {
			match = callback;
			callback = function (item) {
				return item === match;
			};
		}

		while (index < max) {
			if (callback(array[index])) { return array[index]; }
			index += 1;
		}
	}

	// each
	function each(array, callback) {
		var index, max;

		index = 0;
		max = array.length;

		if (!array || !max) { return; }

		while (index < max) {
			if (callback(array[index], index) === false) { return; }
			index += 1;
		}
	}

	// map
	function map(array, callback) {
		var index = 0,
			max = array.length,
			ret = [];

		if (!array || !max) { return ret; }

		while (index < max) {
			ret[index] = callback(array[index], index);
			index += 1;
		}

		return ret;
	}

	// compact
	function compact(array) {
		var ret = [];

		each(array, function (item) {
			if (item) { ret.push(item); }
		});

		return ret;
	}

	// unique
	function unique(array) {
		var ret = [];

		each(array, function (_a) {
			if (!find(ret, _a)) { ret.push(_a); }
		});

		return ret;
	}

	// create matcher
	function createMatcher(size) {
		matchers[size] = new RegExp(" " + size + "\\-height\\-(\\S+)");
	}

	// create sheet
	function createSheet(size) {
		sheets[size] = createStylesheet(F.media_queries[size]);
	}

	// create a style element
	// returns a reference to the created style element's sheet property.
	// accepts a media query applied to the created stylesheet.
	// inspired by http://davidwalsh.name/add-rules-stylesheets
	function createStylesheet(media) {
		var style;

		// create a style element
		style = document.createElement("style");

		// webkit hack
		style.appendChild(document.createTextNode(""));

		if (media) {
			style.setAttribute("media", media);
		}

		// add the style element to the page
		document.head.appendChild(style);

		return style.sheet;
	}

	// delete rules for all responsive-equalized-heights stylesheets
	function deleteRules() {
		each(sizes, function (size) {
			var sheet = sheets[size];

			while (sheet.cssRules.length) {
				sheet.deleteRule(0);
			}
		});
	}

	// insert a rule into a stylesheet
	function insertRule(sheet, rule) {
		sheet.insertRule(rule, sheet.cssRules.length);
	}

	// get array of active screen sizes
	// the current screen size is the last active size in the array
	function getActiveSizes() {
		return compact(map(sizes, function (size) {
			if (matchMedia(F.media_queries[size]).matches) {
				return size;
			}
		}));
	}

	// update stylesheet rules
	function updateRules() {
		deleteRules();
		addRules();
	}

	// create responsive height rules
	function addRules() {
		var cache, activeSizes, $elems, groups;

		// setup groups and element cache
		groups = [];
		cache = {};
		activeSizes = getActiveSizes();

		each(activeSizes, function (size) {
			cache[size] = {};
		});

		// general selector will find all possible matches
		$elems = $('[class*="-height-"]');

		// filter possible matches to find real size groups
		$elems = $elems.filter(function (index, elem) {
			var match;

			each(activeSizes, function (size) {
				var sizeMatch, group;

				sizeMatch = matchers[size].exec(" " + elem.className);

				if (sizeMatch) {
					group = sizeMatch[1];

					if (group !== "auto") {
						match = true;

						// save group name
						groups.push(group);

						// cache element under size group
						if (cache[size][group]) {
							cache[size][group] = $(cache[size][group]).add(elem);
						} else {
							cache[size][group] = $(elem);
						}
					}
				}
			});

			return match;
		});

		// create unique list of groups
		groups = unique(groups);

		// process each group
		each(groups, function (group) {
			var $group, groupHeight;

			$group = $();

			// add each cached size group, filtering out those elements that have a size override in any larger active size
			each(activeSizes, function (size, sizeIndex) {
				var largerSizes, $sizeGroup;

				if (cache[size][group]) {
					largerSizes = activeSizes.slice(sizeIndex + 1);
					$sizeGroup = cache[size][group];

					if (largerSizes.length) {
						$sizeGroup = $sizeGroup.filter(function (index, elem) {
							var override;

							each(largerSizes, function (largerSize) {
								override = matchers[largerSize].exec(" " + elem.className);

								if (override) { return false; }
							});

							return !override;
						});
					}

					$group = $group.add($sizeGroup);
				}
			});

			// if there are active elements for this group
			// create rules
			if ($group.length) {
				// find max element height in group
				// use outerHeight to include padding and border because of box-sizing: border-box;
				// add one px to account for zoomed factional pixels
				groupHeight = 1 + Math.max.apply(null, $group.map(function (index, elem) { return $(elem).outerHeight(); }));

				// write CSS rules for active sizes and groups
				each(activeSizes, function (size) {
					insertRule(sheets[size], "." + size + "-height-" + group + " { height: " + groupHeight + "px; }");
				});
			}
		});
	}

	// setup sizes
	sizes = "small medium large xlarge xxlarge".split(" ");

	// setup matcher regexps
	matchers = {};
	each(sizes, createMatcher);

	// setup responsive height stylesheets
	sheets = {};
	each(sizes, createSheet);

	// initialize rules
	addRules();

	// window resize handler
	$(window).on("resize", F.utils.throttle(updateRules, 250));

	// expose to the outside world
	F.responsive_heights = {
		stylesheets: sheets,
		update: updateRules,
		remove: deleteRules
	};
})(this);
<|endoftext|>


<commit_before>
var sahne = new THREE.Scene();
var pg = document.getElementById('pg');
var mb = document.getElementById('mb');
var genişlik = window.innerWidth, yükseklik = window.innerHeight;
var en_yakın = 400;
var en_uzak = 1000;
var bakış_açısı = 90;
var aspect_ratio = genişlik / yükseklik;
var hedefx = 0, hedefy = 0;
var teta = 0;
var p1,p2;
var cube;
var txtgroup, letters = [];
var kamera = new THREE.PerspectiveCamera(bakış_açısı, aspect_ratio, en_yakın, en_uzak);
var renderer = new THREE.WebGLRenderer();
var textureLoader = new THREE.TextureLoader();
var fontLoader = new THREE.FontLoader();
var controls ;

onWindowResize();
initRenderer();
initListeners();
initCamera();
initControls();
initLights();
initContainer();
initPlanes();
initFont();
initObj();

function initControls() {
  controls = new THREE.OrbitControls(kamera, pg);
  controls.target.set(0, 5, 0);
  controls.enableDamping = true;
  controls.dampingFactor = 0.25;
  controls.enableZoom = true;
  controls.autoRotate = true;
  controls.update();
}

function initCamera() {
  kamera.position.x = 0;
  kamera.position.y = 0;
  kamera.position.z = 0;
  kamera.zoom = 3.0;
  kamera.updateProjectionMatrix();
}

function initFog() {
  sahne.fog = new THREE.Fog(0xffffff, 20, 100);
  sahne.fog.color.setHSL(0.51, 0.6, 0.6);
}

function initFont(txt="TURNA") {
  txtgroup = new THREE.Object3D();
  fontLoader.load( 'fonts/Titillium_Bold.json', function ( font ) {
    for (var i = 0, len = txt.length; i < len; i++) {
      var m = new THREE.MeshPhongMaterial({color: 0x1000000+(Math.random())*0xffffff,specular: 0xffffff,shininess: 30});
      var textGeom = new THREE.TextGeometry( txt[i], {
        font: font,
        size: 50,
        height: 10,
        curveSegments: 12,
        bevelThickness: 0.5,
        bevelSize: 0.5,
        bevelEnabled: true,
      });
      var letterMesh = new THREE.Mesh( textGeom, m );
      letterMesh.castShadow = true;
      letterMesh.receiveShadow = true;
      letterMesh.position.x = -len * 20 + 50 * i;
      letters.push(letterMesh);
      txtgroup.add(letterMesh);
    }
    txtgroup.position.x = 0;
    txtgroup.position.y = -60;
    txtgroup.position.z = 0;
    sahne.add( txtgroup );
  });
}

function initListeners() {
  window.addEventListener( 'resize', onWindowResize, false );
}

function initRenderer() {
  renderer.setSize(genişlik, yükseklik);
  renderer.setClearColor(0x202025);
  renderer.sortObjects = true;
  renderer.shadowMap.enabled = true;
  renderer.shadowMap.type = THREE.PCFSoftShadowMap;
  pg.appendChild(renderer.domElement);
}

function initLights() {
  var ambientLight = new THREE.AmbientLight(0x404040); // soft white light
  ambientLight.intensity = 3.0;
  sahne.add(ambientLight);

  var spotLight = new THREE.SpotLight(0xffffff);
  spotLight.position.set(0, 250, 250);
  spotLight.castShadow = true;
  spotLight.shadow.mapSize.width = 4096;
  spotLight.shadow.mapSize.height = 4096;
  spotLight.shadow.camera.near = 0.1;
  spotLight.shadow.camera.far = 500;
  spotLight.shadow.camera.fov = 30;
  spotLight.shadow.camera.near = true;
  spotLight.intensity = 0.2;
  sahne.add(spotLight);
}

function initContainer() {
  const box_geometry = new THREE.BoxGeometry(genişlik, yükseklik, 100);
  var geometri = new THREE.EdgesGeometry(box_geometry);
  var materyal = new THREE.LineBasicMaterial({
    color: 0xffffff,
    linewidth: 2,
    linecap: 'round',
    linejoin: 'round'
  });
  var container = new THREE.LineSegments(geometri, materyal);
  sahne.add(container);
}

function initPlanes() {
  var g = new THREE.PlaneGeometry(genişlik, yükseklik);

  textureLoader.load('img/floor_texture02.jpg', function(texture) {
    texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
    texture.offset.set( 0, 0 );
    texture.repeat.set( 8, 4 );
    var m = new THREE.MeshPhongMaterial({map: texture, overdraw: 0.5 });
    //var m = new THREE.MeshPhongMaterial({color: 0xffff00,side: THREE.DoubleSide});
    p2 = new THREE.Mesh(g, m);
    p2.castShadow = false;
    p2.receiveShadow = true;
    p2.position.y = -100;
    p2.rotation.x = -1.48;
    sahne.add(p2);
  });

}

window.requestAnimFrame = (function() {
  return window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    function(callback) {
      window.setTimeout(callback, 1000 / 60);
    };
})();

var render = function() {
  setCamera();
  controls.update();
  renderer.render(sahne, kamera);
};

(function animloop() {
  requestAnimFrame(animloop);
  render();
})();

function zoom(zoomin = true) {
  if (zoomin) {
    kamera.zoom += 0.05;
  } else {
    kamera.zoom -= 0.05;
  }
  kamera.updateProjectionMatrix();
}

function setCamera(x = 0, y = 0, z = 800, lx = 0, ly = 1, lz = 0) {
  kamera.position.set(x,y,z);
  kamera.up = new THREE.Vector3(0, 0, 1);
  kamera.lookAt(new THREE.Vector3(lx, ly, lz));
  kamera.updateProjectionMatrix();
}

function onWindowResize() {
    genişlik = pg.clientWidth; //window.innerWidth;
    yükseklik = pg.clientHeight; //window.innerHeight;
		kamera.aspect = genişlik / yükseklik;
		kamera.updateProjectionMatrix();
		renderer.setSize( window.innerWidth, window.innerHeight );
}

function display(m) {
  mb.style.zIndex = 10;
  mb.innerHTML = m;
}

function initObj(){
  const gltfLoader = new THREE.GLTFLoader();
  gltfLoader.load('models/ring/scene.gltf', (gltf) => {
    gltf.scene.scale.set(60, 60, 60);
    const ring = gltf.scene;
    ring.position.x = 5;
    ring.position.z = 0;
    sahne.add(ring);

    // compute the box that contains all the stuff
    // from root and below
    const box = new THREE.Box3().setFromObject(ring);

    const boxSize = box.getSize(new THREE.Vector3()).length();
    const boxCenter = box.getCenter(new THREE.Vector3());

    kamera.lookAt(boxCenter.x, boxCenter.y, boxCenter.z);

    // update the Trackball controls to handle the new size
    controls.maxDistance = boxSize * 10;
    controls.target.copy(boxCenter);
    controls.update();

  });
}
<commit_msg>geliştirmeler<commit_after>
var sahne = new THREE.Scene();
var pg = document.getElementById('pg');
var mb = document.getElementById('mb');
var genişlik = window.innerWidth, yükseklik = window.innerHeight;
var en_yakın = 400;
var en_uzak = 1000;
var bakış_açısı = 90;
var aspect_ratio = genişlik / yükseklik;
var hedefx = 0, hedefy = 0;
var teta = 0;
var cube;
var txtgroup, letters = [];
var kamera = new THREE.PerspectiveCamera(bakış_açısı, aspect_ratio, en_yakın, en_uzak);
var renderer = new THREE.WebGLRenderer();
var textureLoader = new THREE.TextureLoader();
var fontLoader = new THREE.FontLoader();
var controls ;

onWindowResize();
initRenderer();
initListeners();
initCamera();
initControls();
initLights();
initPlanes();
initFont();
initObj();

function initControls() {
  controls = new THREE.OrbitControls(kamera, pg);
  controls.target.set(0, 5, 0);
  controls.enableDamping = true;
  controls.dampingFactor = 0.25;
  controls.enableZoom = true;
  controls.autoRotate = false;
  controls.update();
}

function initCamera() {
  setCamera();
}

function setCamera(x = 0, y = 200, z = 600, lx = 0, ly = 0, lz = 0) {
  kamera.position.set(x,y,z);
  kamera.lookAt(new THREE.Vector3(lx, ly, lz));
  kamera.updateProjectionMatrix();
}

function initFog() {
  sahne.fog = new THREE.Fog(0xffffff, 20, 100);
  sahne.fog.color.setHSL(0.51, 0.6, 0.6);
}

function initFont(txt="TURNA") {
  txtgroup = new THREE.Object3D();
  fontLoader.load( 'fonts/Titillium_Bold.json', function ( font ) {
    for (var i = 0, len = txt.length; i < len; i++) {
      var m = new THREE.MeshPhongMaterial({color: 0x1000000+(Math.random())*0xffffff,specular: 0xffffff,shininess: 30});
      var textGeom = new THREE.TextGeometry( txt[i], {
        font: font,
        size: 50,
        height: 10,
        curveSegments: 12,
        bevelThickness: 0.5,
        bevelSize: 0.5,
        bevelEnabled: true,
      });
      var letterMesh = new THREE.Mesh( textGeom, m );
      letterMesh.castShadow = true;
      letterMesh.receiveShadow = true;
      letterMesh.position.x = -len * 20 + 50 * i;
      letters.push(letterMesh);
      txtgroup.add(letterMesh);
    }
    txtgroup.position.x = 0;
    txtgroup.position.y = -60;
    txtgroup.position.z = 0;
    sahne.add( txtgroup );
  });
}

function initListeners() {
  window.addEventListener( 'resize', onWindowResize, false );
}

function initRenderer() {
  renderer.setSize(genişlik, yükseklik);
  renderer.setClearColor(0x202025);
  renderer.sortObjects = true;
  renderer.shadowMap.enabled = true;
  renderer.shadowMap.type = THREE.PCFSoftShadowMap;
  pg.appendChild(renderer.domElement);
}

function initLights() {
  var ambientLight = new THREE.AmbientLight(0x404040); // soft white light
  ambientLight.intensity = 3.0;
  sahne.add(ambientLight);

  var spotLight = new THREE.SpotLight(0xffffff);
  spotLight.position.set(0, 250, 250);
  spotLight.castShadow = true;
  spotLight.shadow.mapSize.width = 4096;
  spotLight.shadow.mapSize.height = 4096;
  spotLight.shadow.camera.near = 0.1;
  spotLight.shadow.camera.far = 500;
  spotLight.shadow.camera.fov = 30;
  spotLight.shadow.camera.near = true;
  spotLight.intensity = 0.2;
  sahne.add(spotLight);
}

function initPlanes() {
  var g = new THREE.PlaneGeometry(genişlik, yükseklik);

  textureLoader.load('img/floor_texture02.jpg', function(texture) {
    texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
    texture.offset.set( 0, 0 );
    texture.repeat.set( 8, 4 );
    var m = new THREE.MeshPhongMaterial({map: texture, overdraw: 0.5 });
    //var m = new THREE.MeshPhongMaterial({color: 0xffff00,side: THREE.DoubleSide});
    let zemin = new THREE.Mesh(g, m);
    zemin.castShadow = false;
    zemin.receiveShadow = true;
    zemin.position.y = -100;
    zemin.rotation.x = -1.48;
    sahne.add(zemin);
  });
}

window.requestAnimFrame = (function() {
  return window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    function(callback) {
      window.setTimeout(callback, 1000 / 60);
    };
})();

var render = function() {
  controls.update();
  renderer.render(sahne, kamera);
};

(function animloop() {
  requestAnimFrame(animloop);
  render();
})();

function zoom(zoomin = true) {
  if (zoomin) {
    kamera.zoom += 0.05;
  } else {
    kamera.zoom -= 0.05;
  }
  kamera.updateProjectionMatrix();
}

function onWindowResize() {
    genişlik = pg.clientWidth; //window.innerWidth;
    yükseklik = pg.clientHeight; //window.innerHeight;
		kamera.aspect = genişlik / yükseklik;
		kamera.updateProjectionMatrix();
		renderer.setSize( window.innerWidth, window.innerHeight );
}

function display(m) {
  mb.style.zIndex = 10;
  mb.innerHTML = m;
}

function initObj(){
  const gltfLoader = new THREE.GLTFLoader();
  gltfLoader.load('models/ring/scene.gltf', (gltf) => {
    gltf.scene.scale.set(100, 100, 100);
    const ring = gltf.scene;
    ring.position.x = 0;
    ring.position.y = 10;
    ring.position.z = 0;
    ring.castShadow = true;
    sahne.add(ring);
/*
    const box = new THREE.Box3().setFromObject(ring);

    const boxSize = box.getSize(new THREE.Vector3()).length();
    const boxCenter = box.getCenter(new THREE.Vector3());

    kamera.lookAt(boxCenter.x, boxCenter.y, boxCenter.z);

    // update the Trackball controls to handle the new size
    controls.maxDistance = boxSize * 10;
    controls.target.copy(boxCenter);
    controls.update();
*/
  });
}
<|endoftext|>


<commit_before>/*
 * StatusNet - a distributed open-source microblogging tool
 * Copyright (C) 2008, StatusNet, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @category  UI interaction
 * @package   StatusNet
 * @author    Sarven Capadisli <csarven@status.net>
 * @author    Evan Prodromou <evan@status.net>
 * @copyright 2009 StatusNet, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link      http://status.net/
 */

$(document).ready(function(){
    if ($('body.user_in').length > 0) {
        if ($('#'+SN.C.S.NoticeDataText).length) {
            if (maxLength > 0) {
                $('#'+SN.C.S.NoticeDataText).bind('keyup', function(e) {
                    SN.U.Counter();
                });
                // run once in case there's something in there
                SN.U.Counter();
            }

            $('#'+SN.C.S.NoticeDataText).bind('keydown', function(e) {
                SN.U.SubmitOnReturn(e, $('#'+SN.C.S.FormNotice));
            });

            if($('body')[0].id != 'conversation') {
                $('#'+SN.C.S.NoticeDataText).focus();
            }
        }

        $('.form_user_subscribe').each(function() { SN.U.FormXHR($(this)); });
        $('.form_user_unsubscribe').each(function() { SN.U.FormXHR($(this)); });
        $('.form_favor').each(function() { SN.U.FormXHR($(this)); });
        $('.form_disfavor').each(function() { SN.U.FormXHR($(this)); });
        $('.form_group_join').each(function() { SN.U.FormXHR($(this)); });
        $('.form_group_leave').each(function() { SN.U.FormXHR($(this)); });
        $('.form_user_nudge').each(function() { SN.U.FormXHR($(this)); });

        SN.U.FormNoticeXHR();

        SN.U.NoticeReply();

        SN.U.NoticeDataAttach();
    }

    SN.U.NoticeAttachments();
});

var SN = { // StatusNet
    C: { // Config
        I: { // Init
            CounterBlackout: false,
            MaxLength: 140,
            PatternUsername: /^[0-9a-zA-Z\-_.]*$/,
            HTTP20x30x: [200, 201, 202, 203, 204, 205, 206, 300, 301, 302, 303, 304, 305, 306, 307]
        },
        S: { // Selector
            Disabled: 'disabled',
            Warning: 'warning',
            Error: 'error',
            Success: 'success',
            Processing: 'processing',
            CommendResult: 'command_result',
            FormNotice: 'form_notice',
            NoticeDataText: 'notice_data-text',
            NoticeTextCount: 'notice_text-count',
            NoticeInReplyTo: 'notice_in-reply-to',
            NoticeDataAttach: 'notice_data-attach',
            NoticeDataAttachSelected: 'notice_data-attach_selected',
            NoticeActionSubmit: 'notice_action-submit',
        }
    },

    U: { // Utils
        SubmitOnReturn: function(event, el) {
            if (event.keyCode == 13 || event.keyCode == 10) {
                el.submit();
                event.preventDefault();
                event.stopPropagation();
                $('#'+SN.U.NoticeDataText).blur();
                $('body').focus();
                return false;
            }
            return true;
        },

        Counter: function() {
            if (typeof(maxLength) == "undefined") {
                 maxLength = SN.C.I.MaxLength;
            }

            if (maxLength <= 0) {
                return;
            }

            var remaining = maxLength - $('#'+SN.C.S.NoticeDataText).val().length;
            var counter = $('#'+SN.C.S.NoticeTextCount);

            if (remaining.toString() != counter.text()) {
                if (!SN.C.I.CounterBlackout || remaining == 0) {
                    if (counter.text() != String(remaining)) {
                        counter.text(remaining);
                    }
                    if (remaining < 0) {
                        $('#'+SN.C.S.FormNotice).addClass(SN.C.S.Warning);
                    } else {
                        $('#'+SN.C.S.FormNotice).removeClass(SN.C.S.Warning);
                    }
                    // Skip updates for the next 500ms.
                    // On slower hardware, updating on every keypress is unpleasant.
                    if (!SN.C.I.CounterBlackout) {
                        SN.C.I.CounterBlackout = true;
                        window.setTimeout(SN.U.ClearCounterBlackout, 500);
                    }
                }
            }
        },

        ClearCounterBlackout: function() {
            // Allow keyup events to poke the counter again
            SN.C.I.CounterBlackout = false;
            // Check if the string changed since we last looked
            SN.U.Counter(null);
        },

        FormXHR: function(f) {
            f.bind('submit', function(e) {
                form_id = $(this)[0].id;
                $.ajax({
                    type: 'POST',
                    url: $(this)[0].action,
                    data: $(this).serialize() + '&ajax=1',
                    beforeSend: function(xhr) {
                        $('#'+form_id).addClass(SN.C.S.Processing);
                        $('#'+form_id+' .submit').addClass(SN.C.S.Disabled);
                        $('#'+form_id+' .submit').attr(SN.C.S.Disabled, SN.C.S.Disabled);
                    },
                    error: function (xhr, textStatus, errorThrown) {
                        alert(errorThrown || textStatus);
                    },
                    success: function(data, textStatus) {
                        if ($('form', data)[0].length > 0) {
                            form_new = $('form', data)[0];
                            $('#'+form_id).replaceWith(document._importNode(form_new, true));
                            $('#'+form_new.id).each(function() { SN.U.FormXHR($(this)); });
                        }
                        else {
                            $('#'+form_id).replaceWith(document._importNode($('p', data)[0], true));
                        }
                    }
                });
                return false;
            });
        },

        FormNoticeXHR: function() {
            $('#'+SN.C.S.FormNotice).append('<input type="hidden" name="ajax" value="1"/>');
            $('#'+SN.C.S.FormNotice).ajaxForm({
                timeout: '60000',
                beforeSend: function(xhr) {
                    if ($('#'+SN.C.S.NoticeDataText)[0].value.length === 0) {
                        $('#'+SN.C.S.FormNotice).addClass(SN.C.S.Warning);
                        return false;
                    }
                    $('#'+SN.C.S.FormNotice).addClass(SN.C.S.Processing);
                    $('#'+SN.C.S.NoticeActionSubmit).addClass(SN.C.S.Disabled);
                    $('#'+SN.C.S.NoticeActionSubmit).attr(SN.C.S.Disabled, SN.C.S.Disabled);
                    return true;
                },
                error: function (xhr, textStatus, errorThrown) {
                    $('#'+SN.C.S.FormNotice).removeClass(SN.C.S.Processing);
                    $('#'+SN.C.S.NoticeActionSubmit).removeClass(SN.C.S.Disabled);
                    $('#'+SN.C.S.NoticeActionSubmit).removeAttr(SN.C.S.Disabled, SN.C.S.Disabled);
                    if (textStatus == 'timeout') {
                        alert ('Sorry! We had trouble sending your notice. The servers are overloaded. Please try again, and contact the site administrator if this problem persists');
                    }
                    else {
                        if ($('.'+SN.C.S.Error, xhr.responseXML).length > 0) {
                            $('#'+SN.C.S.FormNotice).append(document._importNode($('.'+SN.C.S.Error, xhr.responseXML)[0], true));
                        }
                        else {
                            if(jQuery.inArray(parseInt(xhr.status), SN.C.I.HTTP20x30x) < 0) {
                                alert('Sorry! We had trouble sending your notice ('+xhr.status+' '+xhr.statusText+'). Please report the problem to the site administrator if this happens again.');
                            }
                            else {
                                SN.C.I.NoticeDataText.val('');
                                SN.U.Counter();
                            }
                        }
                    }
                },
                success: function(data, textStatus) {
                    if ($('#'+SN.C.S.Error, data).length > 0) {
                        var result = document._importNode($('p', data)[0], true);
                        alert(result.textContent || result.innerHTML);
                    }
                    else {
                        if($('body')[0].id == 'bookmarklet') {
                            self.close();
                        }
                        if ($('#'+SN.C.S.CommandResult, data).length > 0) {
                            var result = document._importNode($('p', data)[0], true);
                            alert(result.textContent || result.innerHTML);
                        }
                        else {
                             notice = $('li', data)[0];
                             if ($('#'+notice.id).length === 0) {
                                var notice_irt_value = $('#'+SN.C.S.NoticeInReplyTo).val();
                                var notice_irt = '#notices_primary #notice-'+notice_irt_value;
                                if($('body')[0].id == 'conversation') {
                                    if(notice_irt_value.length > 0 && $(notice_irt+' .notices').length < 1) {
                                        $(notice_irt).append('

');
                                    }
                                    $($(notice_irt+' .notices')[0]).append(document._importNode(notice, true));
                                }
                                else {
                                    $("#notices_primary .notices").prepend(document._importNode(notice, true));
                                }
                                $('#'+notice.id).css({display:'none'});
                                $('#'+notice.id).fadeIn(2500);
                                SN.U.NoticeAttachments();
                                SN.U.NoticeReply();
                             }
                        }
                        $('#'+SN.C.S.NoticeDataText).val('');
                        $('#'+SN.C.S.NoticeDataAttach).val('');
                        $('#'+SN.C.S.NoticeInReplyTo).val('');
                        SN.U.Counter();
                    }
                },
                complete: function(xhr, textStatus) {
                    $('#'+SN.C.S.FormNotice).removeClass(SN.C.S.Processing);
                    $('#'+SN.C.S.NoticeActionSubmit).removeAttr(SN.C.S.Disabled);
                    $('#'+SN.C.S.NoticeActionSubmit).removeClass(SN.C.S.Disabled);
                }
            });
        },

        NoticeReply: function() {
            if ($('#'+SN.C.S.NoticeDataText).length > 0 && $('#content .notice_reply').length > 0) {
                $('#content .notice').each(function() {
                    var notice = $(this)[0];
                    $($('.notice_reply', notice)[0]).click(function() {
                        var nickname = ($('.author .nickname', notice).length > 0) ? $($('.author .nickname', notice)[0]) : $('.author .nickname.uid');
                        SN.U.NoticeReplySet(nickname.text(), $($('.notice_id', notice)[0]).text());
                        return false;
                    });
                });
            }
        },

        NoticeReplySet: function(nick,id) {
            if (nick.match(SN.C.I.PatternUsername)) {
                var text = $('#'+SN.C.S.NoticeDataText);
                if (text.length) {
                    replyto = '@' + nick + ' ';
                    text.val(replyto + text.val().replace(RegExp(replyto, 'i'), ''));
                    $('#'+SN.C.S.FormNotice+' input#'+SN.C.S.NoticeInReplyTo).val(id);
                    if (text.get(0).setSelectionRange) {
                        var len = text.val().length;
                        text.get(0).setSelectionRange(len,len);
                        text.get(0).focus();
                    }
                    return false;
                }
            }
            return true;
        },

        NoticeAttachments: function() {
            $.fn.jOverlay.options = {
                method : 'GET',
                data : '',
                url : '',
                color : '#000',
                opacity : '0.6',
                zIndex : 99,
                center : false,
                imgLoading : $('address .url')[0].href+'theme/base/images/illustrations/illu_progress_loading-01.gif',
                bgClickToClose : true,
                success : function() {
                    $('#jOverlayContent').append('<button>×</button>');
                    $('#jOverlayContent button').click($.closeOverlay);
                },
                timeout : 0,
                autoHide : true,
                css : {'max-width':'542px', 'top':'5%', 'left':'32.5%'}
            };

            $('#content .notice a.attachment').click(function() {
                $().jOverlay({url: $('address .url')[0].href+'attachment/' + ($(this).attr('id').substring('attachment'.length + 1)) + '/ajax'});
                return false;
            });

            var t;
            $("body:not(#shownotice) #content .notice a.thumbnail").hover(
                function() {
                    var anchor = $(this);
                    $("a.thumbnail").children('img').hide();
                    anchor.closest(".entry-title").addClass('ov');

                    if (anchor.children('img').length == 0) {
                        t = setTimeout(function() {
                            $.get($('address .url')[0].href+'attachment/' + (anchor.attr('id').substring('attachment'.length + 1)) + '/thumbnail', null, function(data) {
                                anchor.append(data);
                            });
                        }, 500);
                    }
                    else {
                        anchor.children('img').show();
                    }
                },
                function() {
                    clearTimeout(t);
                    $("a.thumbnail").children('img').hide();
                    $(this).closest(".entry-title").removeClass('ov');
                }
            );
        },

        NoticeDataAttach: function() {
            NDA = $('#'+SN.C.S.NoticeDataAttach);
            NDA.change(function() {
                S = '
'+$(this).val()+' <button>×</button>
';
                NDAS = $('#'+SN.C.S.NoticeDataAttachSelected);
                (NDAS.length > 0) ? NDAS.replaceWith(S) : $('#'+SN.C.S.FormNotice).append(S);
                $('#'+SN.C.S.NoticeDataAttachSelected+' button').click(function(){
                    $('#'+SN.C.S.NoticeDataAttachSelected).remove();
                    NDA.val('');
                });
            });
        }
    }
}
<commit_msg>Added missing dataType line for ajaxForm<commit_after>/*
 * StatusNet - a distributed open-source microblogging tool
 * Copyright (C) 2008, StatusNet, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @category  UI interaction
 * @package   StatusNet
 * @author    Sarven Capadisli <csarven@status.net>
 * @author    Evan Prodromou <evan@status.net>
 * @copyright 2009 StatusNet, Inc.
 * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
 * @link      http://status.net/
 */

$(document).ready(function(){
    if ($('body.user_in').length > 0) {
        if ($('#'+SN.C.S.NoticeDataText).length) {
            if (maxLength > 0) {
                $('#'+SN.C.S.NoticeDataText).bind('keyup', function(e) {
                    SN.U.Counter();
                });
                // run once in case there's something in there
                SN.U.Counter();
            }

            $('#'+SN.C.S.NoticeDataText).bind('keydown', function(e) {
                SN.U.SubmitOnReturn(e, $('#'+SN.C.S.FormNotice));
            });

            if($('body')[0].id != 'conversation') {
                $('#'+SN.C.S.NoticeDataText).focus();
            }
        }

        $('.form_user_subscribe').each(function() { SN.U.FormXHR($(this)); });
        $('.form_user_unsubscribe').each(function() { SN.U.FormXHR($(this)); });
        $('.form_favor').each(function() { SN.U.FormXHR($(this)); });
        $('.form_disfavor').each(function() { SN.U.FormXHR($(this)); });
        $('.form_group_join').each(function() { SN.U.FormXHR($(this)); });
        $('.form_group_leave').each(function() { SN.U.FormXHR($(this)); });
        $('.form_user_nudge').each(function() { SN.U.FormXHR($(this)); });

        SN.U.FormNoticeXHR();

        SN.U.NoticeReply();

        SN.U.NoticeDataAttach();
    }

    SN.U.NoticeAttachments();
});

var SN = { // StatusNet
    C: { // Config
        I: { // Init
            CounterBlackout: false,
            MaxLength: 140,
            PatternUsername: /^[0-9a-zA-Z\-_.]*$/,
            HTTP20x30x: [200, 201, 202, 203, 204, 205, 206, 300, 301, 302, 303, 304, 305, 306, 307]
        },

        S: { // Selector
            Disabled: 'disabled',
            Warning: 'warning',
            Error: 'error',
            Success: 'success',
            Processing: 'processing',
            CommendResult: 'command_result',
            FormNotice: 'form_notice',
            NoticeDataText: 'notice_data-text',
            NoticeTextCount: 'notice_text-count',
            NoticeInReplyTo: 'notice_in-reply-to',
            NoticeDataAttach: 'notice_data-attach',
            NoticeDataAttachSelected: 'notice_data-attach_selected',
            NoticeActionSubmit: 'notice_action-submit',
        }
    },

    U: { // Utils
        SubmitOnReturn: function(event, el) {
            if (event.keyCode == 13 || event.keyCode == 10) {
                el.submit();
                event.preventDefault();
                event.stopPropagation();
                $('#'+SN.U.NoticeDataText).blur();
                $('body').focus();
                return false;
            }
            return true;
        },

        Counter: function() {
            if (typeof(maxLength) == "undefined") {
                 maxLength = SN.C.I.MaxLength;
            }

            if (maxLength <= 0) {
                return;
            }

            var remaining = maxLength - $('#'+SN.C.S.NoticeDataText).val().length;
            var counter = $('#'+SN.C.S.NoticeTextCount);

            if (remaining.toString() != counter.text()) {
                if (!SN.C.I.CounterBlackout || remaining == 0) {
                    if (counter.text() != String(remaining)) {
                        counter.text(remaining);
                    }
                    if (remaining < 0) {
                        $('#'+SN.C.S.FormNotice).addClass(SN.C.S.Warning);
                    } else {
                        $('#'+SN.C.S.FormNotice).removeClass(SN.C.S.Warning);
                    }
                    // Skip updates for the next 500ms.
                    // On slower hardware, updating on every keypress is unpleasant.
                    if (!SN.C.I.CounterBlackout) {
                        SN.C.I.CounterBlackout = true;
                        window.setTimeout(SN.U.ClearCounterBlackout, 500);
                    }
                }
            }
        },

        ClearCounterBlackout: function() {
            // Allow keyup events to poke the counter again
            SN.C.I.CounterBlackout = false;
            // Check if the string changed since we last looked
            SN.U.Counter(null);
        },

        FormXHR: function(f) {
            f.bind('submit', function(e) {
                form_id = $(this)[0].id;
                $.ajax({
                    type: 'POST',
                    url: $(this)[0].action,
                    data: $(this).serialize() + '&ajax=1',
                    beforeSend: function(xhr) {
                        $('#'+form_id).addClass(SN.C.S.Processing);
                        $('#'+form_id+' .submit').addClass(SN.C.S.Disabled);
                        $('#'+form_id+' .submit').attr(SN.C.S.Disabled, SN.C.S.Disabled);
                    },
                    error: function (xhr, textStatus, errorThrown) {
                        alert(errorThrown || textStatus);
                    },
                    success: function(data, textStatus) {
                        if ($('form', data)[0].length > 0) {
                            form_new = $('form', data)[0];
                            $('#'+form_id).replaceWith(document._importNode(form_new, true));
                            $('#'+form_new.id).each(function() { SN.U.FormXHR($(this)); });
                        }
                        else {
                            $('#'+form_id).replaceWith(document._importNode($('p', data)[0], true));
                        }
                    }
                });
                return false;
            });
        },

        FormNoticeXHR: function() {
            $('#'+SN.C.S.FormNotice).append('<input type="hidden" name="ajax" value="1"/>');
            $('#'+SN.C.S.FormNotice).ajaxForm({
                timeout: '60000',
                dataType: 'xml',
                beforeSend: function(xhr) {
                    if ($('#'+SN.C.S.NoticeDataText)[0].value.length === 0) {
                        $('#'+SN.C.S.FormNotice).addClass(SN.C.S.Warning);
                        return false;
                    }
                    $('#'+SN.C.S.FormNotice).addClass(SN.C.S.Processing);
                    $('#'+SN.C.S.NoticeActionSubmit).addClass(SN.C.S.Disabled);
                    $('#'+SN.C.S.NoticeActionSubmit).attr(SN.C.S.Disabled, SN.C.S.Disabled);
                    return true;
                },
                error: function (xhr, textStatus, errorThrown) {
                    $('#'+SN.C.S.FormNotice).removeClass(SN.C.S.Processing);
                    $('#'+SN.C.S.NoticeActionSubmit).removeClass(SN.C.S.Disabled);
                    $('#'+SN.C.S.NoticeActionSubmit).removeAttr(SN.C.S.Disabled, SN.C.S.Disabled);
                    if (textStatus == 'timeout') {
                        alert ('Sorry! We had trouble sending your notice. The servers are overloaded. Please try again, and contact the site administrator if this problem persists');
                    }
                    else {
                        if ($('.'+SN.C.S.Error, xhr.responseXML).length > 0) {
                            $('#'+SN.C.S.FormNotice).append(document._importNode($('.'+SN.C.S.Error, xhr.responseXML)[0], true));
                        }
                        else {
                            if(jQuery.inArray(parseInt(xhr.status), SN.C.I.HTTP20x30x) < 0) {
                                alert('Sorry! We had trouble sending your notice ('+xhr.status+' '+xhr.statusText+'). Please report the problem to the site administrator if this happens again.');
                            }
                            else {
                                SN.C.I.NoticeDataText.val('');
                                SN.U.Counter();
                            }
                        }
                    }
                },
                success: function(data, textStatus) {
                    if ($('#'+SN.C.S.Error, data).length > 0) {
                        var result = document._importNode($('p', data)[0], true);
                        alert(result.textContent || result.innerHTML);
                    }
                    else {
                        if($('body')[0].id == 'bookmarklet') {
                            self.close();
                        }
                        if ($('#'+SN.C.S.CommandResult, data).length > 0) {
                            var result = document._importNode($('p', data)[0], true);
                            alert(result.textContent || result.innerHTML);
                        }
                        else {
                             notice = $('li', data)[0];
                             if ($('#'+notice.id).length === 0) {
                                var notice_irt_value = $('#'+SN.C.S.NoticeInReplyTo).val();
                                var notice_irt = '#notices_primary #notice-'+notice_irt_value;
                                if($('body')[0].id == 'conversation') {
                                    if(notice_irt_value.length > 0 && $(notice_irt+' .notices').length < 1) {
                                        $(notice_irt).append('

');
                                    }
                                    $($(notice_irt+' .notices')[0]).append(document._importNode(notice, true));
                                }
                                else {
                                    $("#notices_primary .notices").prepend(document._importNode(notice, true));
                                }
                                $('#'+notice.id).css({display:'none'});
                                $('#'+notice.id).fadeIn(2500);
                                SN.U.NoticeAttachments();
                                SN.U.NoticeReply();
                             }
                        }
                        $('#'+SN.C.S.NoticeDataText).val('');
                        $('#'+SN.C.S.NoticeDataAttach).val('');
                        $('#'+SN.C.S.NoticeInReplyTo).val('');
                        SN.U.Counter();
                    }
                },
                complete: function(xhr, textStatus) {
                    $('#'+SN.C.S.FormNotice).removeClass(SN.C.S.Processing);
                    $('#'+SN.C.S.NoticeActionSubmit).removeAttr(SN.C.S.Disabled);
                    $('#'+SN.C.S.NoticeActionSubmit).removeClass(SN.C.S.Disabled);
                }
            });
        },

        NoticeReply: function() {
            if ($('#'+SN.C.S.NoticeDataText).length > 0 && $('#content .notice_reply').length > 0) {
                $('#content .notice').each(function() {
                    var notice = $(this)[0];
                    $($('.notice_reply', notice)[0]).click(function() {
                        var nickname = ($('.author .nickname', notice).length > 0) ? $($('.author .nickname', notice)[0]) : $('.author .nickname.uid');
                        SN.U.NoticeReplySet(nickname.text(), $($('.notice_id', notice)[0]).text());
                        return false;
                    });
                });
            }
        },

        NoticeReplySet: function(nick,id) {
            if (nick.match(SN.C.I.PatternUsername)) {
                var text = $('#'+SN.C.S.NoticeDataText);
                if (text.length) {
                    replyto = '@' + nick + ' ';
                    text.val(replyto + text.val().replace(RegExp(replyto, 'i'), ''));
                    $('#'+SN.C.S.FormNotice+' input#'+SN.C.S.NoticeInReplyTo).val(id);
                    if (text.get(0).setSelectionRange) {
                        var len = text.val().length;
                        text.get(0).setSelectionRange(len,len);
                        text.get(0).focus();
                    }
                    return false;
                }
            }
            return true;
        },

        NoticeAttachments: function() {
            $.fn.jOverlay.options = {
                method : 'GET',
                data : '',
                url : '',
                color : '#000',
                opacity : '0.6',
                zIndex : 99,
                center : false,
                imgLoading : $('address .url')[0].href+'theme/base/images/illustrations/illu_progress_loading-01.gif',
                bgClickToClose : true,
                success : function() {
                    $('#jOverlayContent').append('<button>×</button>');
                    $('#jOverlayContent button').click($.closeOverlay);
                },
                timeout : 0,
                autoHide : true,
                css : {'max-width':'542px', 'top':'5%', 'left':'32.5%'}
            };

            $('#content .notice a.attachment').click(function() {
                $().jOverlay({url: $('address .url')[0].href+'attachment/' + ($(this).attr('id').substring('attachment'.length + 1)) + '/ajax'});
                return false;
            });

            var t;
            $("body:not(#shownotice) #content .notice a.thumbnail").hover(
                function() {
                    var anchor = $(this);
                    $("a.thumbnail").children('img').hide();
                    anchor.closest(".entry-title").addClass('ov');

                    if (anchor.children('img').length == 0) {
                        t = setTimeout(function() {
                            $.get($('address .url')[0].href+'attachment/' + (anchor.attr('id').substring('attachment'.length + 1)) + '/thumbnail', null, function(data) {
                                anchor.append(data);
                            });
                        }, 500);
                    }
                    else {
                        anchor.children('img').show();
                    }
                },
                function() {
                    clearTimeout(t);
                    $("a.thumbnail").children('img').hide();
                    $(this).closest(".entry-title").removeClass('ov');
                }
            );
        },

        NoticeDataAttach: function() {
            NDA = $('#'+SN.C.S.NoticeDataAttach);
            NDA.change(function() {
                S = '
'+$(this).val()+' <button>×</button>
';
                NDAS = $('#'+SN.C.S.NoticeDataAttachSelected);
                (NDAS.length > 0) ? NDAS.replaceWith(S) : $('#'+SN.C.S.FormNotice).append(S);
                $('#'+SN.C.S.NoticeDataAttachSelected+' button').click(function(){
                    $('#'+SN.C.S.NoticeDataAttachSelected).remove();
                    NDA.val('');
                });
            });
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Tried fixing infinite loop<commit_after><|endoftext|>


<commit_before>$(document).ready(function(){
        // count character on keyup
        function counter(){
            var maxLength     = 140;
            var currentLength = $("#status_textarea").val().length;
            var remaining = 140 - currentLength;
            var counter = $("#counter");
            counter.text(remaining);

            if(remaining <= 0) {
                counter.attr("class", "toomuch");
                } else {
                counter.attr("class", "");
                }
        }

        if ($("#status_textarea").length) {
            $("#status_textarea").bind("keyup", counter);
            // run once in case there's something in there
			counter();
        }
});

function doreply(nick) {
     rgx_username = /^[0-9a-zA-Z\-_.]*$/;
     if (nick.match(rgx_username)) {
          replyto = "@" + nick + " ";
          if ($("#status_textarea")) {
               $("#status_textarea").value=replyto;
               $("#status_textarea").focus();
          }
     }
     return false;
}

<commit_msg>try another tack<commit_after>$(document).ready(function(){
        // count character on keyup
        function counter(){
            var maxLength     = 140;
            var currentLength = $("#status_textarea").val().length;
            var remaining = 140 - currentLength;
            var counter = $("#counter");
            counter.text(remaining);

            if(remaining <= 0) {
                counter.attr("class", "toomuch");
                } else {
                counter.attr("class", "");
                }
        }

        if ($("#status_textarea").length) {
            $("#status_textarea").bind("keyup", counter);
            // run once in case there's something in there
			counter();
        }
});

function doreply(nick) {
     rgx_username = /^[0-9a-zA-Z\-_.]*$/;
     if (nick.match(rgx_username)) {
          replyto = "@" + nick + " ";
          if ($("#status_textarea")) {
               $("#status_textarea").val(replyto);
               $("#status_textarea").focus();
          }
     }
     return false;
}

<|endoftext|>


<commit_before>var findme_map = L.map('findme-map')
    .setView([41.69, 12.71], 5),
    osmUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
    osmAttrib = 'Dati © OpenStreetMap contributors',
    osm = L.tileLayer(osmUrl, {minZoom: 2, maxZoom: 18, attribution: osmAttrib}).addTo(findme_map),
    category_data = [];
var	payment_data = [];

var findme_marker = L.marker([41.69, 12.71], {draggable:true}).addTo(findme_map);
findme_marker.setOpacity(0);

if (location.hash) location.hash = '';

$.getJSON('./categories.json').success(function(data){
    category_data = data;
});

$.getJSON('./payment.json').success(function(data){
    payment_data = data;
});

$("#category").select2({
    query: function (query) {
        var data = {results: []}, i;
        for (i = 0; i < category_data.length; i++) {
            if (query.term.length === 0 || category_data[i].toLowerCase().indexOf(query.term.toLowerCase()) >= 0) {
                data.results.push({id: category_data[i], text: category_data[i]});
            }
        }
        query.callback(data);
    }
});

$("#payment").select2({
    multiple:true,
    query:function(query) {
        var data={results:[]},
            results=data.results,
            t=query.term;
        if (t!==""&&payment_data.indexOf(t)<0) {
            results.push({id:t, text:t});
        }

        $(payment_data)
         .filter(function() { return t===""||this.indexOf(t)>=0; })
         .each(function() { results.push({id:this, text:this}); });

        query.callback(data);
    }
});
   /*
$("#payment").select2({
    query: function (query) {
        var data = {results: []}, i;
        for (i = 0; i < payment_data.length; i++) {
            if (query.term.length === 0 || payment_data[i].toLowerCase().indexOf(query.term.toLowerCase()) >= 0) {
                data.results.push({id: payment_data[i], text: payment_data[i]});
            }
        }
        query.callback(data);
    }
});*/

/* search action */
$("#find").submit(function(e) {
    e.preventDefault();
    $("#couldnt-find").hide();
    var address_to_find = $("#address").val();
    if (address_to_find.length === 0) return;

    /* NOMINATIM PARAM */
    var qwarg_nominatim = {
        format: 'json',
        q: address_to_find
    };
    var url_nominatim = "http://nominatim.openstreetmap.org/search?" + $.param(qwarg_nominatim);

    /* SOLR TEST SERVER */
    var qwarg_solr = {
        wt: 'json',
        indent: 'true',
        qt: 'italian',
        q: address_to_find
    };
    var url_solr = "http://95.240.35.64:8080/solr-example/collection1/select?" + $.param(qwarg_solr);

    var instance='nominatim';

    $("#findme h4").text("Sto cercando...");
    $("#findme").addClass("loading");

	if (instance=='nominatim')
	{
		$.ajax({
		  'url': url_nominatim,
		  'success': nominatim_callback,
		  'dataType': 'jsonp',
		  'jsonp': 'json_callback'
		});
	}
	else
	{
		$.ajax({
		  'url': url_solr,
		  'success': solr_callback,
		  'dataType': 'jsonp',
		  'jsonp': 'json.wrf'
		});
	}
});

function nominatim_callback(data){
	if (data.length > 0) {
            var chosen_place = data[0];
            console.log(chosen_place);

            var bounds = new L.LatLngBounds(
                [+chosen_place.boundingbox[0], +chosen_place.boundingbox[2]],
                [+chosen_place.boundingbox[1], +chosen_place.boundingbox[3]]);

            findme_map.fitBounds(bounds);
            findme_marker.setOpacity(1);
            findme_marker.setLatLng([chosen_place.lat, chosen_place.lon]);
            $('#instructions').html('Trovato! Clicca e trascina l\'indicatore sulla posizione della tua attività commerciale, così sarai pronto/a a aggiungere dettagli alla tua scheda.');
            $('.step-2 a').attr('href', '#details');
    }	else {
            $('#instructions').html('Non siamo riusciti a trovare il tuo indirizzo. Prova a cercare la tua strada o città con meno dettagli.');
        }
    $("#findme").removeClass("loading");
}

function solr_callback(data){
	if (data.response.docs.length > 0) {
	    var docs=data.response.docs;
		var coords=docs[0].coordinate.split(',');
            findme_marker.setOpacity(1);
            findme_marker.setLatLng([coords[0], coords[1]]);
			findme_map.setView([coords[0], coords[1]],16);
            $('#instructions').html('Trovato! Clicca e trascina l\'indicatore sulla posizione della tua attività commerciale, così sarai pronto/a a aggiungere dettagli alla tua scheda.');
            $('.step-2 a').attr('href', '#details');
    }   else {
            $('#instructions').html('Non siamo riusciti a trovare il tuo indirizzo. Prova a cercare la tua strada o città con meno dettagli.');
        }
	$("#findme").removeClass("loading");
}

/* map action */
findme_map.on('click', function(e){
findme_marker.setOpacity(1);
findme_marker.setLatLng(e.latlng);
$('#instructions').html('Hai attivato l\'indicatore! Cliccalo e trascinalo sulla posizione della tua attività commerciale, così sarai pronto/a a aggiungere dettagli alla tua scheda.');
$('.step-2 a').attr('href', '#details');
});

$(window).on('hashchange', function() {
    if (location.hash == '#details') {
        $('#collect-data-step').removeClass('hide');
        $('#address-step').addClass('hide');
        $('#confirm-step').addClass('hide');
        $('.steps').addClass('on-2');
        $('.steps').removeClass('on-3');
    } else if (location.hash == '#done') {
        $('#confirm-step').removeClass('hide');
        $('#collect-data-step').addClass('hide');
        $('#address-step').addClass('hide');
        $('.steps').addClass('on-3');
    } else {
        $('#address-step').removeClass('hide');
        $('#collect-data-step').addClass('hide');
        $('#confirm-step').addClass('hide');
        $('.steps').removeClass('on-2');
        $('.steps').removeClass('on-3');
    }
    findme_map.invalidateSize();
});

$("#collect-data-done").click(function() {
    location.hash = '#done';

    var note_body = "E' stata inviata una nota tramite su.openstreetmap.it:\n";
	if ($("#name").val()) note_body += "Nome: " + $("#name").val() + "\n";
        if ($("#phone").val()) note_body += "Telefono: " + $("#phone").val() + "\n";
        if ($("#phone").val()) note_body += "Sito web: " + $("#website").val() + "\n";
        if ($("#social").val()) note_body += "Social Network: " + $("#social").val() + "\n";
        if ($("#opening_hours").val()) note_body += "Orario di apertura: " + $("#opening_hours").val() + "\n";
        if ($("#category").val()) note_body += "Categoria: " + $("#category").val() + "\n";
        if ($("#categoryalt").val()) note_body += "Descrizione: " + $("#categoryalt").val() + "\n";
        if ($("#address").val()) note_body += "Indirizzo: " + $("#address").val();
        if ($("#payment").val()) note_body += "Tipologie di pagamento accettate: " + $("#payment").val() + "\n";
    var latlon = findme_marker.getLatLng();
    var qwarg = {
            lat: latlon.lat,
            lon: latlon.lng,
            text: note_body
        };

    $.post('http://api.openstreetmap.org/api/0.6/notes.json', qwarg);
});
<commit_msg>Update site.js<commit_after>var findme_map = L.map('findme-map')
    .setView([41.69, 12.71], 5),
    osmUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
    osmAttrib = 'Dati © OpenStreetMap contributors',
    osm = L.tileLayer(osmUrl, {minZoom: 2, maxZoom: 18, attribution: osmAttrib}).addTo(findme_map),
    category_data = [];
var	payment_data = [];

var findme_marker = L.marker([41.69, 12.71], {draggable:true}).addTo(findme_map);
findme_marker.setOpacity(0);

if (location.hash) location.hash = '';

$.getJSON('./categories.json').success(function(data){
    category_data = data;
});

$.getJSON('./payment.json').success(function(data){
    payment_data = data;
});

$("#category").select2({
    query: function (query) {
        var data = {results: []}, i;
        for (i = 0; i < category_data.length; i++) {
            if (query.term.length === 0 || category_data[i].toLowerCase().indexOf(query.term.toLowerCase()) >= 0) {
                data.results.push({id: category_data[i], text: category_data[i]});
            }
        }
        query.callback(data);
    }
});

$("#payment").select2({
    multiple:true,
    query:function(query) {
        var data={results:[]},
            results=data.results,
            t=query.term;
        if (t!==""&&payment_data.indexOf(t)<0) {
            results.push({id:t, text:t});
        }

        $(payment_data)
         .filter(function() { return t===""||this.indexOf(t)>=0; })
         .each(function() { results.push({id:this, text:this}); });

        query.callback(data);
    }
});

/* search action */
$("#find").submit(function(e) {
    e.preventDefault();
    $("#couldnt-find").hide();
    var address_to_find = $("#address").val();
    if (address_to_find.length === 0) return;

    /* NOMINATIM PARAM */
    var qwarg_nominatim = {
        format: 'json',
        q: address_to_find
    };
    var url_nominatim = "http://nominatim.openstreetmap.org/search?" + $.param(qwarg_nominatim);

    /* SOLR TEST SERVER */
    var qwarg_solr = {
        wt: 'json',
        indent: 'true',
        qt: 'italian',
        q: address_to_find
    };
    var url_solr = "http://95.240.35.64:8080/solr-example/collection1/select?" + $.param(qwarg_solr);

    var instance='nominatim';

    $("#findme h4").text("Sto cercando...");
    $("#findme").addClass("loading");

	if (instance=='nominatim')
	{
		$.ajax({
		  'url': url_nominatim,
		  'success': nominatim_callback,
		  'dataType': 'jsonp',
		  'jsonp': 'json_callback'
		});
	}
	else
	{
		$.ajax({
		  'url': url_solr,
		  'success': solr_callback,
		  'dataType': 'jsonp',
		  'jsonp': 'json.wrf'
		});
	}
});

function nominatim_callback(data){
	if (data.length > 0) {
            var chosen_place = data[0];
            console.log(chosen_place);

            var bounds = new L.LatLngBounds(
                [+chosen_place.boundingbox[0], +chosen_place.boundingbox[2]],
                [+chosen_place.boundingbox[1], +chosen_place.boundingbox[3]]);

            findme_map.fitBounds(bounds);
            findme_marker.setOpacity(1);
            findme_marker.setLatLng([chosen_place.lat, chosen_place.lon]);
            $('#instructions').html('Trovato! Clicca e trascina l\'indicatore sulla posizione della tua attività commerciale, così sarai pronto/a a aggiungere dettagli alla tua scheda.');
            $('.step-2 a').attr('href', '#details');
    }	else {
            $('#instructions').html('Non siamo riusciti a trovare il tuo indirizzo. Prova a cercare la tua strada o città con meno dettagli.');
        }
    $("#findme").removeClass("loading");
}

function solr_callback(data){
	if (data.response.docs.length > 0) {
	    var docs=data.response.docs;
		var coords=docs[0].coordinate.split(',');
            findme_marker.setOpacity(1);
            findme_marker.setLatLng([coords[0], coords[1]]);
			findme_map.setView([coords[0], coords[1]],16);
            $('#instructions').html('Trovato! Clicca e trascina l\'indicatore sulla posizione della tua attività commerciale, così sarai pronto/a a aggiungere dettagli alla tua scheda.');
            $('.step-2 a').attr('href', '#details');
    }   else {
            $('#instructions').html('Non siamo riusciti a trovare il tuo indirizzo. Prova a cercare la tua strada o città con meno dettagli.');
        }
	$("#findme").removeClass("loading");
}

/* map action */
findme_map.on('click', function(e){
findme_marker.setOpacity(1);
findme_marker.setLatLng(e.latlng);
$('#instructions').html('Hai attivato l\'indicatore! Cliccalo e trascinalo sulla posizione della tua attività commerciale, così sarai pronto/a a aggiungere dettagli alla tua scheda.');
$('.step-2 a').attr('href', '#details');
});

$(window).on('hashchange', function() {
    if (location.hash == '#details') {
        $('#collect-data-step').removeClass('hide');
        $('#address-step').addClass('hide');
        $('#confirm-step').addClass('hide');
        $('.steps').addClass('on-2');
        $('.steps').removeClass('on-3');
    } else if (location.hash == '#done') {
        $('#confirm-step').removeClass('hide');
        $('#collect-data-step').addClass('hide');
        $('#address-step').addClass('hide');
        $('.steps').addClass('on-3');
    } else {
        $('#address-step').removeClass('hide');
        $('#collect-data-step').addClass('hide');
        $('#confirm-step').addClass('hide');
        $('.steps').removeClass('on-2');
        $('.steps').removeClass('on-3');
    }
    findme_map.invalidateSize();
});

$("#collect-data-done").click(function() {
    location.hash = '#done';

    var note_body = "E' stata inviata una nota tramite su.openstreetmap.it:\n";
	if ($("#name").val()) note_body += "Nome: " + $("#name").val() + "\n";
        if ($("#phone").val()) note_body += "Telefono: " + $("#phone").val() + "\n";
        if ($("#website").val()) note_body += "Sito web: " + $("#website").val() + "\n";
        if ($("#social").val()) note_body += "Social Network: " + $("#social").val() + "\n";
        if ($("#opening_hours").val()) note_body += "Orario di apertura: " + $("#opening_hours").val() + "\n";
        if ($("#category").val()) note_body += "Categoria: " + $("#category").val() + "\n";
        if ($("#categoryalt").val()) note_body += "Descrizione: " + $("#categoryalt").val() + "\n";
        if ($("#address").val()) note_body += "Indirizzo: " + $("#address").val();
        if ($("#payment").val()) note_body += "Tipologie di pagamento accettate: " + $("#payment").val() + "\n";
    var latlon = findme_marker.getLatLng();
    var qwarg = {
            lat: latlon.lat,
            lon: latlon.lng,
            text: note_body
        };

    $.post('http://api.openstreetmap.org/api/0.6/notes.json', qwarg);
});
<|endoftext|>


<commit_before>import * as path from 'path';
import commonPathPrefix from 'common-path-prefix';
import * as ts from 'typescript';

// returned by CScript sys environment
const UNSUPPORTED_FILE_ENCODING_ERR_CODE = -2147024809;

/* beautify preserve:start */
export const keyByPath = (map, file) => Object.assign(map, { [file.path]: file });
/* beautify preserve:end */

/* eslint-disable class-methods-use-this, immutable/no-mutation */
export default class CompilerHost {

  outFiles = {};

  constructor(input, compilerOpts) {
    this.files = input.reduce(keyByPath, {});
    this.compilerOpts = compilerOpts;
  }

  useCaseSensitiveFileNames() {
    return ts.sys.useCaseSensitiveFileNames;
  }

  getNewLine() {
    return ts.getNewLineCharacter(this.compilerOpts);
  }

  getDefaultLibLocation() {
    return ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath()));
  }

  getDefaultLibFileName(options) {
    return ts.combinePaths(this.getDefaultLibLocation(), ts.getDefaultLibFileName(options));
  }

  getCurrentDirectory() {
    return ts.sys.getCurrentDirectory();
  }

  getCanonicalFileName(fileName) {
    return this.useCaseSensitiveFileNames() ? fileName : fileName.toLowerCase();
  }

  fileExists(fileName) {
    return !!this.files[fileName] || ts.sys.fileExists(fileName);
  }

  readFile(fileName) {
    if (this.files[fileName]) {
      return this.files[fileName].data;
    }

    return ts.sys.readFile(fileName);
  }

  getSourceFile(fileName, languageVersion, onError) {
    let text = null;

    if (this.files[fileName]) {
      text = this.files[fileName].data;
    } else {
      try {
        text = ts.sys.readFile(fileName, this.compilerOpts.charset);
      } catch (e) {
        if (onError) {
          onError(e.number === UNSUPPORTED_FILE_ENCODING_ERR_CODE ?
            ts.createCompilerDiagnostic(ts.Diagnostics.Unsupported_file_encoding).messageText :
            e.message);
        }
        text = '';
      }
    }

    if (text !== null) {
      return ts.createSourceFile(fileName, text, languageVersion, this.setParentNodes);
    }
  }

  writeFile(fileName, data) {
    this.outFiles[fileName] = {
      path: fileName,
      data,
      map: null
    };
  }

  emitFiles() {
    const files = Object.keys(this.outFiles);
    const commonPath = commonPathPrefix(files);
    const currentDir = this.getCurrentDirectory();

    return files.reduce((emitted, file) => {
      const sourceFile = this.outFiles[file];

      if (file.endsWith('.map')) {
        const sourceMap = JSON.parse(sourceFile.data);
        const sourceRoot = path.join(
          path.relative(file, currentDir),
          path.relative(currentDir, commonPath)
        );

        // eslint-disable-next-line no-magic-numbers
        this.outFiles[file.substring(0, file.length - 4)].map = { ...sourceMap, sourceRoot };
      } else {
        // start-write will add these back for us
        const match = sourceFile.data.match(/\/\/# sourceMappingURL=.+$/);

        if (match) {
          // eslint-disable-next-line no-magic-numbers
          sourceFile.data = sourceFile.data.substr(0, match.index).trim();
        }

        emitted.push(sourceFile);
      }

      return emitted;
    }, []);
  }
}
<commit_msg>fix(sourcemap): fix source map path<commit_after>import * as path from 'path';
import commonPathPrefix from 'common-path-prefix';
import * as ts from 'typescript';

// returned by CScript sys environment
const UNSUPPORTED_FILE_ENCODING_ERR_CODE = -2147024809;

/* beautify preserve:start */
export const keyByPath = (map, file) => Object.assign(map, { [file.path]: file });
/* beautify preserve:end */

/* eslint-disable class-methods-use-this, immutable/no-mutation */
export default class CompilerHost {

  outFiles = {};

  constructor(input, compilerOpts) {
    this.files = input.reduce(keyByPath, {});
    this.compilerOpts = compilerOpts;
  }

  useCaseSensitiveFileNames() {
    return ts.sys.useCaseSensitiveFileNames;
  }

  getNewLine() {
    return ts.getNewLineCharacter(this.compilerOpts);
  }

  getDefaultLibLocation() {
    return ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath()));
  }

  getDefaultLibFileName(options) {
    return ts.combinePaths(this.getDefaultLibLocation(), ts.getDefaultLibFileName(options));
  }

  getCurrentDirectory() {
    return ts.sys.getCurrentDirectory();
  }

  getCanonicalFileName(fileName) {
    return this.useCaseSensitiveFileNames() ? fileName : fileName.toLowerCase();
  }

  fileExists(fileName) {
    return !!this.files[fileName] || ts.sys.fileExists(fileName);
  }

  readFile(fileName) {
    if (this.files[fileName]) {
      return this.files[fileName].data;
    }

    return ts.sys.readFile(fileName);
  }

  getSourceFile(fileName, languageVersion, onError) {
    let text = null;

    if (this.files[fileName]) {
      text = this.files[fileName].data;
    } else {
      try {
        text = ts.sys.readFile(fileName, this.compilerOpts.charset);
      } catch (e) {
        if (onError) {
          onError(e.number === UNSUPPORTED_FILE_ENCODING_ERR_CODE ?
            ts.createCompilerDiagnostic(ts.Diagnostics.Unsupported_file_encoding).messageText :
            e.message);
        }
        text = '';
      }
    }

    if (text !== null) {
      return ts.createSourceFile(fileName, text, languageVersion, this.setParentNodes);
    }
  }

  writeFile(fileName, data) {
    this.outFiles[fileName] = {
      path: fileName,
      data,
      map: null
    };
  }

  emitFiles() {
    const files = Object.keys(this.outFiles);
    const commonPath = commonPathPrefix(files);
    const currentDir = this.getCurrentDirectory();

    return files.reduce((emitted, file) => {
      const sourceFile = this.outFiles[file];

      if (file.endsWith('.map')) {
        const sourceMap = JSON.parse(sourceFile.data);
        const sourceRoot = path.join(
          path.relative(file, currentDir),
          path.relative(currentDir, commonPath)
        );
        const sourceRelativePath = path.relative(commonPath, path.dirname(file));

        // eslint-disable-next-line no-magic-numbers
        this.outFiles[file.substring(0, file.length - 4)].map = {
          ...sourceMap,
          sourceRoot,
          sources: sourceMap.sources.map((source) => path.join(sourceRelativePath, source))
        };
      } else {
        // start-write will add these back for us
        const match = sourceFile.data.match(/\/\/# sourceMappingURL=.+$/);

        if (match) {
          // eslint-disable-next-line no-magic-numbers
          sourceFile.data = sourceFile.data.substr(0, match.index).trim();
        }

        emitted.push(sourceFile);
      }

      return emitted;
    }, []);
  }
}
<|endoftext|>