code_text
stringlengths
604
999k
repo_name
stringlengths
4
100
file_path
stringlengths
4
873
language
stringclasses
23 values
license
stringclasses
15 values
size
int32
1.02k
999k
// Copyright 2016 The etcd Authors // // 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. package clientv3 import ( "log" "os" "sync" "google.golang.org/grpc/grpclog" ) type Logger grpclog.Logger var ( logger settableLogger ) type settableLogger struct { l grpclog.Logger mu sync.RWMutex } func init() { // use go's standard logger by default like grpc logger.mu.Lock() logger.l = log.New(os.Stderr, "", log.LstdFlags) grpclog.SetLogger(&logger) logger.mu.Unlock() } func (s *settableLogger) Set(l Logger) { s.mu.Lock() logger.l = l s.mu.Unlock() } func (s *settableLogger) Get() Logger { s.mu.RLock() l := logger.l s.mu.RUnlock() return l } // implement the grpclog.Logger interface func (s *settableLogger) Fatal(args ...interface{}) { s.Get().Fatal(args...) } func (s *settableLogger) Fatalf(format string, args ...interface{}) { s.Get().Fatalf(format, args...) } func (s *settableLogger) Fatalln(args ...interface{}) { s.Get().Fatalln(args...) } func (s *settableLogger) Print(args ...interface{}) { s.Get().Print(args...) } func (s *settableLogger) Printf(format string, args ...interface{}) { s.Get().Printf(format, args...) } func (s *settableLogger) Println(args ...interface{}) { s.Get().Println(args...) }
bryk/kubernetes
vendor/github.com/coreos/etcd/clientv3/logger.go
GO
apache-2.0
1,810
/* * Copyright (C) 2016 The Android Open Source Project * * 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. */ package com.example.android.sunshine.data; import android.net.Uri; import android.provider.BaseColumns; import com.example.android.sunshine.utilities.SunshineDateUtils; /** * Defines table and column names for the weather database. This class is not necessary, but keeps * the code organized. */ public class WeatherContract { /* * The "Content authority" is a name for the entire content provider, similar to the * relationship between a domain name and its website. A convenient string to use for the * content authority is the package name for the app, which is guaranteed to be unique on the * Play Store. */ public static final String CONTENT_AUTHORITY = "com.example.android.sunshine"; /* * Use CONTENT_AUTHORITY to create the base of all URI's which apps will use to contact * the content provider for Sunshine. */ public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY); /* * Possible paths that can be appended to BASE_CONTENT_URI to form valid URI's that Sunshine * can handle. For instance, * * content://com.example.android.sunshine/weather/ * [ BASE_CONTENT_URI ][ PATH_WEATHER ] * * is a valid path for looking at weather data. * * content://com.example.android.sunshine/givemeroot/ * * will fail, as the ContentProvider hasn't been given any information on what to do with * "givemeroot". At least, let's hope not. Don't be that dev, reader. Don't be that dev. */ public static final String PATH_WEATHER = "weather"; /* Inner class that defines the table contents of the weather table */ public static final class WeatherEntry implements BaseColumns { /* The base CONTENT_URI used to query the Weather table from the content provider */ public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon() .appendPath(PATH_WEATHER) .build(); /* Used internally as the name of our weather table. */ public static final String TABLE_NAME = "weather"; /* * The date column will store the UTC date that correlates to the local date for which * each particular weather row represents. For example, if you live in the Eastern * Standard Time (EST) time zone and you load weather data at 9:00 PM on September 23, 2016, * the UTC time stamp for that particular time would be 1474678800000 in milliseconds. * However, due to time zone offsets, it would already be September 24th, 2016 in the GMT * time zone when it is 9:00 PM on the 23rd in the EST time zone. In this example, the date * column would hold the date representing September 23rd at midnight in GMT time. * (1474588800000) * * The reason we store GMT time and not local time is because it is best practice to have a * "normalized", or standard when storing the date and adjust as necessary when * displaying the date. Normalizing the date also allows us an easy way to convert to * local time at midnight, as all we have to do is add a particular time zone's GMT * offset to this date to get local time at midnight on the appropriate date. */ public static final String COLUMN_DATE = "date"; /* Weather ID as returned by API, used to identify the icon to be used */ public static final String COLUMN_WEATHER_ID = "weather_id"; /* Min and max temperatures in °C for the day (stored as floats in the database) */ public static final String COLUMN_MIN_TEMP = "min"; public static final String COLUMN_MAX_TEMP = "max"; /* Humidity is stored as a float representing percentage */ public static final String COLUMN_HUMIDITY = "humidity"; /* Pressure is stored as a float representing percentage */ public static final String COLUMN_PRESSURE = "pressure"; /* Wind speed is stored as a float representing wind speed in mph */ public static final String COLUMN_WIND_SPEED = "wind"; /* * Degrees are meteorological degrees (e.g, 0 is north, 180 is south). * Stored as floats in the database. * * Note: These degrees are not to be confused with temperature degrees of the weather. */ public static final String COLUMN_DEGREES = "degrees"; /** * Builds a URI that adds the weather date to the end of the forecast content URI path. * This is used to query details about a single weather entry by date. This is what we * use for the detail view query. We assume a normalized date is passed to this method. * * @param date Normalized date in milliseconds * @return Uri to query details about a single weather entry */ public static Uri buildWeatherUriWithDate(long date) { return CONTENT_URI.buildUpon() .appendPath(Long.toString(date)) .build(); } /** * Returns just the selection part of the weather query from a normalized today value. * This is used to get a weather forecast from today's date. To make this easy to use * in compound selection, we embed today's date as an argument in the query. * * @return The selection part of the weather query for today onwards */ public static String getSqlSelectForTodayOnwards() { long normalizedUtcNow = SunshineDateUtils.normalizeDate(System.currentTimeMillis()); return WeatherContract.WeatherEntry.COLUMN_DATE + " >= " + normalizedUtcNow; } } }
pearqueros/FastTrackAndroid
S09.05-Exercise-MoreDetails/app/src/main/java/com/example/android/sunshine/data/WeatherContract.java
Java
apache-2.0
6,396
#!/bin/bash set -e # hello-world latest ef872312fe1b 3 months ago 910 B # hello-world latest ef872312fe1bbc5e05aae626791a47ee9b032efa8f3bda39cc0be7b56bfe59b9 3 months ago 910 B # debian latest f6fab3b798be 10 weeks ago 85.1 MB # debian latest f6fab3b798be3174f45aa1eb731f8182705555f89c9026d8c1ef230cbf8301dd 10 weeks ago 85.1 MB if ! command -v curl &> /dev/null; then echo >&2 'error: "curl" not found!' exit 1 fi usage() { echo "usage: $0 dir image[:tag][@image-id] ..." echo " ie: $0 /tmp/hello-world hello-world" echo " $0 /tmp/debian-jessie debian:jessie" echo " $0 /tmp/old-hello-world hello-world@ef872312fe1bbc5e05aae626791a47ee9b032efa8f3bda39cc0be7b56bfe59b9" echo " $0 /tmp/old-debian debian:latest@f6fab3b798be3174f45aa1eb731f8182705555f89c9026d8c1ef230cbf8301dd" [ -z "$1" ] || exit "$1" } dir="$1" # dir for building tar in shift || usage 1 >&2 [ $# -gt 0 -a "$dir" ] || usage 2 >&2 mkdir -p "$dir" # hacky workarounds for Bash 3 support (no associative arrays) images=() rm -f "$dir"/tags-*.tmp # repositories[busybox]='"latest": "...", "ubuntu-14.04": "..."' while [ $# -gt 0 ]; do imageTag="$1" shift image="${imageTag%%[:@]*}" tag="${imageTag#*:}" imageId="${tag##*@}" [ "$imageId" != "$tag" ] || imageId= [ "$tag" != "$imageTag" ] || tag='latest' tag="${tag%@*}" imageFile="${image//\//_}" # "/" can't be in filenames :) token="$(curl -sSL -o /dev/null -D- -H 'X-Docker-Token: true' "https://index.docker.io/v1/repositories/$image/images" | tr -d '\r' | awk -F ': *' '$1 == "X-Docker-Token" { print $2 }')" if [ -z "$imageId" ]; then imageId="$(curl -sSL -H "Authorization: Token $token" "https://registry-1.docker.io/v1/repositories/$image/tags/$tag")" imageId="${imageId//\"/}" fi ancestryJson="$(curl -sSL -H "Authorization: Token $token" "https://registry-1.docker.io/v1/images/$imageId/ancestry")" if [ "${ancestryJson:0:1}" != '[' ]; then echo >&2 "error: /v1/images/$imageId/ancestry returned something unexpected:" echo >&2 " $ancestryJson" exit 1 fi IFS=',' ancestry=( ${ancestryJson//[\[\] \"]/} ) unset IFS if [ -s "$dir/tags-$imageFile.tmp" ]; then echo -n ', ' >> "$dir/tags-$imageFile.tmp" else images=( "${images[@]}" "$image" ) fi echo -n '"'"$tag"'": "'"$imageId"'"' >> "$dir/tags-$imageFile.tmp" echo "Downloading '$imageTag' (${#ancestry[@]} layers)..." for imageId in "${ancestry[@]}"; do mkdir -p "$dir/$imageId" echo '1.0' > "$dir/$imageId/VERSION" curl -sSL -H "Authorization: Token $token" "https://registry-1.docker.io/v1/images/$imageId/json" -o "$dir/$imageId/json" # TODO figure out why "-C -" doesn't work here # "curl: (33) HTTP server doesn't seem to support byte ranges. Cannot resume." # "HTTP/1.1 416 Requested Range Not Satisfiable" if [ -f "$dir/$imageId/layer.tar" ]; then # TODO hackpatch for no -C support :'( echo "skipping existing ${imageId:0:12}" continue fi curl -SL --progress -H "Authorization: Token $token" "https://registry-1.docker.io/v1/images/$imageId/layer" -o "$dir/$imageId/layer.tar" # -C - done echo done echo -n '{' > "$dir/repositories" firstImage=1 for image in "${images[@]}"; do imageFile="${image//\//_}" # "/" can't be in filenames :) [ "$firstImage" ] || echo -n ',' >> "$dir/repositories" firstImage= echo -n $'\n\t' >> "$dir/repositories" echo -n '"'"$image"'": { '"$(cat "$dir/tags-$imageFile.tmp")"' }' >> "$dir/repositories" done echo -n $'\n}\n' >> "$dir/repositories" rm -f "$dir"/tags-*.tmp echo "Download of images into '$dir' complete." echo "Use something like the following to load the result into a Docker daemon:" echo " tar -cC '$dir' . | docker load"
ypid/docker
contrib/download-frozen-image.sh
Shell
apache-2.0
3,866
/*! * Bootstrap v3.2.0 (http://getbootstrap.com) * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) */ if("undefined"==typeof jQuery)throw new Error("Bootstrap's JavaScript requires jQuery");+function(a){"use strict";function b(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var c in b)if(void 0!==a.style[c])return{end:b[c]};return!1}a.fn.emulateTransitionEnd=function(b){var c=!1,d=this;a(this).one("bsTransitionEnd",function(){c=!0});var e=function(){c||a(d).trigger(a.support.transition.end)};return setTimeout(e,b),this},a(function(){a.support.transition=b(),a.support.transition&&(a.event.special.bsTransitionEnd={bindType:a.support.transition.end,delegateType:a.support.transition.end,handle:function(b){return a(b.target).is(this)?b.handleObj.handler.apply(this,arguments):void 0}})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var c=a(this),e=c.data("bs.alert");e||c.data("bs.alert",e=new d(this)),"string"==typeof b&&e[b].call(c)})}var c='[data-dismiss="alert"]',d=function(b){a(b).on("click",c,this.close)};d.VERSION="3.2.0",d.prototype.close=function(b){function c(){f.detach().trigger("closed.bs.alert").remove()}var d=a(this),e=d.attr("data-target");e||(e=d.attr("href"),e=e&&e.replace(/.*(?=#[^\s]*$)/,""));var f=a(e);b&&b.preventDefault(),f.length||(f=d.hasClass("alert")?d:d.parent()),f.trigger(b=a.Event("close.bs.alert")),b.isDefaultPrevented()||(f.removeClass("in"),a.support.transition&&f.hasClass("fade")?f.one("bsTransitionEnd",c).emulateTransitionEnd(150):c())};var e=a.fn.alert;a.fn.alert=b,a.fn.alert.Constructor=d,a.fn.alert.noConflict=function(){return a.fn.alert=e,this},a(document).on("click.bs.alert.data-api",c,d.prototype.close)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.button"),f="object"==typeof b&&b;e||d.data("bs.button",e=new c(this,f)),"toggle"==b?e.toggle():b&&e.setState(b)})}var c=function(b,d){this.$element=a(b),this.options=a.extend({},c.DEFAULTS,d),this.isLoading=!1};c.VERSION="3.2.0",c.DEFAULTS={loadingText:"loading..."},c.prototype.setState=function(b){var c="disabled",d=this.$element,e=d.is("input")?"val":"html",f=d.data();b+="Text",null==f.resetText&&d.data("resetText",d[e]()),d[e](null==f[b]?this.options[b]:f[b]),setTimeout(a.proxy(function(){"loadingText"==b?(this.isLoading=!0,d.addClass(c).attr(c,c)):this.isLoading&&(this.isLoading=!1,d.removeClass(c).removeAttr(c))},this),0)},c.prototype.toggle=function(){var a=!0,b=this.$element.closest('[data-toggle="buttons"]');if(b.length){var c=this.$element.find("input");"radio"==c.prop("type")&&(c.prop("checked")&&this.$element.hasClass("active")?a=!1:b.find(".active").removeClass("active")),a&&c.prop("checked",!this.$element.hasClass("active")).trigger("change")}a&&this.$element.toggleClass("active")};var d=a.fn.button;a.fn.button=b,a.fn.button.Constructor=c,a.fn.button.noConflict=function(){return a.fn.button=d,this},a(document).on("click.bs.button.data-api",'[data-toggle^="button"]',function(c){var d=a(c.target);d.hasClass("btn")||(d=d.closest(".btn")),b.call(d,"toggle"),c.preventDefault()})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.carousel"),f=a.extend({},c.DEFAULTS,d.data(),"object"==typeof b&&b),g="string"==typeof b?b:f.slide;e||d.data("bs.carousel",e=new c(this,f)),"number"==typeof b?e.to(b):g?e[g]():f.interval&&e.pause().cycle()})}var c=function(b,c){this.$element=a(b).on("keydown.bs.carousel",a.proxy(this.keydown,this)),this.$indicators=this.$element.find(".carousel-indicators"),this.options=c,this.paused=this.sliding=this.interval=this.$active=this.$items=null,"hover"==this.options.pause&&this.$element.on("mouseenter.bs.carousel",a.proxy(this.pause,this)).on("mouseleave.bs.carousel",a.proxy(this.cycle,this))};c.VERSION="3.2.0",c.DEFAULTS={interval:5e3,pause:"hover",wrap:!0},c.prototype.keydown=function(a){switch(a.which){case 37:this.prev();break;case 39:this.next();break;default:return}a.preventDefault()},c.prototype.cycle=function(b){return b||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(a.proxy(this.next,this),this.options.interval)),this},c.prototype.getItemIndex=function(a){return this.$items=a.parent().children(".item"),this.$items.index(a||this.$active)},c.prototype.to=function(b){var c=this,d=this.getItemIndex(this.$active=this.$element.find(".item.active"));return b>this.$items.length-1||0>b?void 0:this.sliding?this.$element.one("slid.bs.carousel",function(){c.to(b)}):d==b?this.pause().cycle():this.slide(b>d?"next":"prev",a(this.$items[b]))},c.prototype.pause=function(b){return b||(this.paused=!0),this.$element.find(".next, .prev").length&&a.support.transition&&(this.$element.trigger(a.support.transition.end),this.cycle(!0)),this.interval=clearInterval(this.interval),this},c.prototype.next=function(){return this.sliding?void 0:this.slide("next")},c.prototype.prev=function(){return this.sliding?void 0:this.slide("prev")},c.prototype.slide=function(b,c){var d=this.$element.find(".item.active"),e=c||d[b](),f=this.interval,g="next"==b?"left":"right",h="next"==b?"first":"last",i=this;if(!e.length){if(!this.options.wrap)return;e=this.$element.find(".item")[h]()}if(e.hasClass("active"))return this.sliding=!1;var j=e[0],k=a.Event("slide.bs.carousel",{relatedTarget:j,direction:g});if(this.$element.trigger(k),!k.isDefaultPrevented()){if(this.sliding=!0,f&&this.pause(),this.$indicators.length){this.$indicators.find(".active").removeClass("active");var l=a(this.$indicators.children()[this.getItemIndex(e)]);l&&l.addClass("active")}var m=a.Event("slid.bs.carousel",{relatedTarget:j,direction:g});return a.support.transition&&this.$element.hasClass("slide")?(e.addClass(b),e[0].offsetWidth,d.addClass(g),e.addClass(g),d.one("bsTransitionEnd",function(){e.removeClass([b,g].join(" ")).addClass("active"),d.removeClass(["active",g].join(" ")),i.sliding=!1,setTimeout(function(){i.$element.trigger(m)},0)}).emulateTransitionEnd(1e3*d.css("transition-duration").slice(0,-1))):(d.removeClass("active"),e.addClass("active"),this.sliding=!1,this.$element.trigger(m)),f&&this.cycle(),this}};var d=a.fn.carousel;a.fn.carousel=b,a.fn.carousel.Constructor=c,a.fn.carousel.noConflict=function(){return a.fn.carousel=d,this},a(document).on("click.bs.carousel.data-api","[data-slide], [data-slide-to]",function(c){var d,e=a(this),f=a(e.attr("data-target")||(d=e.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,""));if(f.hasClass("carousel")){var g=a.extend({},f.data(),e.data()),h=e.attr("data-slide-to");h&&(g.interval=!1),b.call(f,g),h&&f.data("bs.carousel").to(h),c.preventDefault()}}),a(window).on("load",function(){a('[data-ride="carousel"]').each(function(){var c=a(this);b.call(c,c.data())})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.collapse"),f=a.extend({},c.DEFAULTS,d.data(),"object"==typeof b&&b);!e&&f.toggle&&"show"==b&&(b=!b),e||d.data("bs.collapse",e=new c(this,f)),"string"==typeof b&&e[b]()})}var c=function(b,d){this.$element=a(b),this.options=a.extend({},c.DEFAULTS,d),this.transitioning=null,this.options.parent&&(this.$parent=a(this.options.parent)),this.options.toggle&&this.toggle()};c.VERSION="3.2.0",c.DEFAULTS={toggle:!0},c.prototype.dimension=function(){var a=this.$element.hasClass("width");return a?"width":"height"},c.prototype.show=function(){if(!this.transitioning&&!this.$element.hasClass("in")){var c=a.Event("show.bs.collapse");if(this.$element.trigger(c),!c.isDefaultPrevented()){var d=this.$parent&&this.$parent.find("> .panel > .in");if(d&&d.length){var e=d.data("bs.collapse");if(e&&e.transitioning)return;b.call(d,"hide"),e||d.data("bs.collapse",null)}var f=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[f](0),this.transitioning=1;var g=function(){this.$element.removeClass("collapsing").addClass("collapse in")[f](""),this.transitioning=0,this.$element.trigger("shown.bs.collapse")};if(!a.support.transition)return g.call(this);var h=a.camelCase(["scroll",f].join("-"));this.$element.one("bsTransitionEnd",a.proxy(g,this)).emulateTransitionEnd(350)[f](this.$element[0][h])}}},c.prototype.hide=function(){if(!this.transitioning&&this.$element.hasClass("in")){var b=a.Event("hide.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.dimension();this.$element[c](this.$element[c]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse").removeClass("in"),this.transitioning=1;var d=function(){this.transitioning=0,this.$element.trigger("hidden.bs.collapse").removeClass("collapsing").addClass("collapse")};return a.support.transition?void this.$element[c](0).one("bsTransitionEnd",a.proxy(d,this)).emulateTransitionEnd(350):d.call(this)}}},c.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()};var d=a.fn.collapse;a.fn.collapse=b,a.fn.collapse.Constructor=c,a.fn.collapse.noConflict=function(){return a.fn.collapse=d,this},a(document).on("click.bs.collapse.data-api",'[data-toggle="collapse"]',function(c){var d,e=a(this),f=e.attr("data-target")||c.preventDefault()||(d=e.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,""),g=a(f),h=g.data("bs.collapse"),i=h?"toggle":e.data(),j=e.attr("data-parent"),k=j&&a(j);h&&h.transitioning||(k&&k.find('[data-toggle="collapse"][data-parent="'+j+'"]').not(e).addClass("collapsed"),e[g.hasClass("in")?"addClass":"removeClass"]("collapsed")),b.call(g,i)})}(jQuery),+function(a){"use strict";function b(b){b&&3===b.which||(a(e).remove(),a(f).each(function(){var d=c(a(this)),e={relatedTarget:this};d.hasClass("open")&&(d.trigger(b=a.Event("hide.bs.dropdown",e)),b.isDefaultPrevented()||d.removeClass("open").trigger("hidden.bs.dropdown",e))}))}function c(b){var c=b.attr("data-target");c||(c=b.attr("href"),c=c&&/#[A-Za-z]/.test(c)&&c.replace(/.*(?=#[^\s]*$)/,""));var d=c&&a(c);return d&&d.length?d:b.parent()}function d(b){return this.each(function(){var c=a(this),d=c.data("bs.dropdown");d||c.data("bs.dropdown",d=new g(this)),"string"==typeof b&&d[b].call(c)})}var e=".dropdown-backdrop",f='[data-toggle="dropdown"]',g=function(b){a(b).on("click.bs.dropdown",this.toggle)};g.VERSION="3.2.0",g.prototype.toggle=function(d){var e=a(this);if(!e.is(".disabled, :disabled")){var f=c(e),g=f.hasClass("open");if(b(),!g){"ontouchstart"in document.documentElement&&!f.closest(".navbar-nav").length&&a('<div class="dropdown-backdrop"/>').insertAfter(a(this)).on("click",b);var h={relatedTarget:this};if(f.trigger(d=a.Event("show.bs.dropdown",h)),d.isDefaultPrevented())return;e.trigger("focus"),f.toggleClass("open").trigger("shown.bs.dropdown",h)}return!1}},g.prototype.keydown=function(b){if(/(38|40|27)/.test(b.keyCode)){var d=a(this);if(b.preventDefault(),b.stopPropagation(),!d.is(".disabled, :disabled")){var e=c(d),g=e.hasClass("open");if(!g||g&&27==b.keyCode)return 27==b.which&&e.find(f).trigger("focus"),d.trigger("click");var h=" li:not(.divider):visible a",i=e.find('[role="menu"]'+h+', [role="listbox"]'+h);if(i.length){var j=i.index(i.filter(":focus"));38==b.keyCode&&j>0&&j--,40==b.keyCode&&j<i.length-1&&j++,~j||(j=0),i.eq(j).trigger("focus")}}}};var h=a.fn.dropdown;a.fn.dropdown=d,a.fn.dropdown.Constructor=g,a.fn.dropdown.noConflict=function(){return a.fn.dropdown=h,this},a(document).on("click.bs.dropdown.data-api",b).on("click.bs.dropdown.data-api",".dropdown form",function(a){a.stopPropagation()}).on("click.bs.dropdown.data-api",f,g.prototype.toggle).on("keydown.bs.dropdown.data-api",f+', [role="menu"], [role="listbox"]',g.prototype.keydown)}(jQuery),+function(a){"use strict";function b(b,d){return this.each(function(){var e=a(this),f=e.data("bs.modal"),g=a.extend({},c.DEFAULTS,e.data(),"object"==typeof b&&b);f||e.data("bs.modal",f=new c(this,g)),"string"==typeof b?f[b](d):g.show&&f.show(d)})}var c=function(b,c){this.options=c,this.$body=a(document.body),this.$element=a(b),this.$backdrop=this.isShown=null,this.scrollbarWidth=0,this.options.remote&&this.$element.find(".modal-content").load(this.options.remote,a.proxy(function(){this.$element.trigger("loaded.bs.modal")},this))};c.VERSION="3.2.0",c.DEFAULTS={backdrop:!0,keyboard:!0,show:!0},c.prototype.toggle=function(a){return this.isShown?this.hide():this.show(a)},c.prototype.show=function(b){var c=this,d=a.Event("show.bs.modal",{relatedTarget:b});this.$element.trigger(d),this.isShown||d.isDefaultPrevented()||(this.isShown=!0,this.checkScrollbar(),this.$body.addClass("modal-open"),this.setScrollbar(),this.escape(),this.$element.on("click.dismiss.bs.modal",'[data-dismiss="modal"]',a.proxy(this.hide,this)),this.backdrop(function(){var d=a.support.transition&&c.$element.hasClass("fade");c.$element.parent().length||c.$element.appendTo(c.$body),c.$element.show().scrollTop(0),d&&c.$element[0].offsetWidth,c.$element.addClass("in").attr("aria-hidden",!1),c.enforceFocus();var e=a.Event("shown.bs.modal",{relatedTarget:b});d?c.$element.find(".modal-dialog").one("bsTransitionEnd",function(){c.$element.trigger("focus").trigger(e)}).emulateTransitionEnd(300):c.$element.trigger("focus").trigger(e)}))},c.prototype.hide=function(b){b&&b.preventDefault(),b=a.Event("hide.bs.modal"),this.$element.trigger(b),this.isShown&&!b.isDefaultPrevented()&&(this.isShown=!1,this.$body.removeClass("modal-open"),this.resetScrollbar(),this.escape(),a(document).off("focusin.bs.modal"),this.$element.removeClass("in").attr("aria-hidden",!0).off("click.dismiss.bs.modal"),a.support.transition&&this.$element.hasClass("fade")?this.$element.one("bsTransitionEnd",a.proxy(this.hideModal,this)).emulateTransitionEnd(300):this.hideModal())},c.prototype.enforceFocus=function(){a(document).off("focusin.bs.modal").on("focusin.bs.modal",a.proxy(function(a){this.$element[0]===a.target||this.$element.has(a.target).length||this.$element.trigger("focus")},this))},c.prototype.escape=function(){this.isShown&&this.options.keyboard?this.$element.on("keyup.dismiss.bs.modal",a.proxy(function(a){27==a.which&&this.hide()},this)):this.isShown||this.$element.off("keyup.dismiss.bs.modal")},c.prototype.hideModal=function(){var a=this;this.$element.hide(),this.backdrop(function(){a.$element.trigger("hidden.bs.modal")})},c.prototype.removeBackdrop=function(){this.$backdrop&&this.$backdrop.remove(),this.$backdrop=null},c.prototype.backdrop=function(b){var c=this,d=this.$element.hasClass("fade")?"fade":"";if(this.isShown&&this.options.backdrop){var e=a.support.transition&&d;if(this.$backdrop=a('<div class="modal-backdrop '+d+'" />').appendTo(this.$body),this.$element.on("click.dismiss.bs.modal",a.proxy(function(a){a.target===a.currentTarget&&("static"==this.options.backdrop?this.$element[0].focus.call(this.$element[0]):this.hide.call(this))},this)),e&&this.$backdrop[0].offsetWidth,this.$backdrop.addClass("in"),!b)return;e?this.$backdrop.one("bsTransitionEnd",b).emulateTransitionEnd(150):b()}else if(!this.isShown&&this.$backdrop){this.$backdrop.removeClass("in");var f=function(){c.removeBackdrop(),b&&b()};a.support.transition&&this.$element.hasClass("fade")?this.$backdrop.one("bsTransitionEnd",f).emulateTransitionEnd(150):f()}else b&&b()},c.prototype.checkScrollbar=function(){document.body.clientWidth>=window.innerWidth||(this.scrollbarWidth=this.scrollbarWidth||this.measureScrollbar())},c.prototype.setScrollbar=function(){var a=parseInt(this.$body.css("padding-right")||0,10);this.scrollbarWidth&&this.$body.css("padding-right",a+this.scrollbarWidth)},c.prototype.resetScrollbar=function(){this.$body.css("padding-right","")},c.prototype.measureScrollbar=function(){var a=document.createElement("div");a.className="modal-scrollbar-measure",this.$body.append(a);var b=a.offsetWidth-a.clientWidth;return this.$body[0].removeChild(a),b};var d=a.fn.modal;a.fn.modal=b,a.fn.modal.Constructor=c,a.fn.modal.noConflict=function(){return a.fn.modal=d,this},a(document).on("click.bs.modal.data-api",'[data-toggle="modal"]',function(c){var d=a(this),e=d.attr("href"),f=a(d.attr("data-target")||e&&e.replace(/.*(?=#[^\s]+$)/,"")),g=f.data("bs.modal")?"toggle":a.extend({remote:!/#/.test(e)&&e},f.data(),d.data());d.is("a")&&c.preventDefault(),f.one("show.bs.modal",function(a){a.isDefaultPrevented()||f.one("hidden.bs.modal",function(){d.is(":visible")&&d.trigger("focus")})}),b.call(f,g,this)})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.tooltip"),f="object"==typeof b&&b;(e||"destroy"!=b)&&(e||d.data("bs.tooltip",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.type=this.options=this.enabled=this.timeout=this.hoverState=this.$element=null,this.init("tooltip",a,b)};c.VERSION="3.2.0",c.DEFAULTS={animation:!0,placement:"top",selector:!1,template:'<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',trigger:"hover focus",title:"",delay:0,html:!1,container:!1,viewport:{selector:"body",padding:0}},c.prototype.init=function(b,c,d){this.enabled=!0,this.type=b,this.$element=a(c),this.options=this.getOptions(d),this.$viewport=this.options.viewport&&a(this.options.viewport.selector||this.options.viewport);for(var e=this.options.trigger.split(" "),f=e.length;f--;){var g=e[f];if("click"==g)this.$element.on("click."+this.type,this.options.selector,a.proxy(this.toggle,this));else if("manual"!=g){var h="hover"==g?"mouseenter":"focusin",i="hover"==g?"mouseleave":"focusout";this.$element.on(h+"."+this.type,this.options.selector,a.proxy(this.enter,this)),this.$element.on(i+"."+this.type,this.options.selector,a.proxy(this.leave,this))}}this.options.selector?this._options=a.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.getOptions=function(b){return b=a.extend({},this.getDefaults(),this.$element.data(),b),b.delay&&"number"==typeof b.delay&&(b.delay={show:b.delay,hide:b.delay}),b},c.prototype.getDelegateOptions=function(){var b={},c=this.getDefaults();return this._options&&a.each(this._options,function(a,d){c[a]!=d&&(b[a]=d)}),b},c.prototype.enter=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),clearTimeout(c.timeout),c.hoverState="in",c.options.delay&&c.options.delay.show?void(c.timeout=setTimeout(function(){"in"==c.hoverState&&c.show()},c.options.delay.show)):c.show()},c.prototype.leave=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),clearTimeout(c.timeout),c.hoverState="out",c.options.delay&&c.options.delay.hide?void(c.timeout=setTimeout(function(){"out"==c.hoverState&&c.hide()},c.options.delay.hide)):c.hide()},c.prototype.show=function(){var b=a.Event("show.bs."+this.type);if(this.hasContent()&&this.enabled){this.$element.trigger(b);var c=a.contains(document.documentElement,this.$element[0]);if(b.isDefaultPrevented()||!c)return;var d=this,e=this.tip(),f=this.getUID(this.type);this.setContent(),e.attr("id",f),this.$element.attr("aria-describedby",f),this.options.animation&&e.addClass("fade");var g="function"==typeof this.options.placement?this.options.placement.call(this,e[0],this.$element[0]):this.options.placement,h=/\s?auto?\s?/i,i=h.test(g);i&&(g=g.replace(h,"")||"top"),e.detach().css({top:0,left:0,display:"block"}).addClass(g).data("bs."+this.type,this),this.options.container?e.appendTo(this.options.container):e.insertAfter(this.$element);var j=this.getPosition(),k=e[0].offsetWidth,l=e[0].offsetHeight;if(i){var m=g,n=this.$element.parent(),o=this.getPosition(n);g="bottom"==g&&j.top+j.height+l-o.scroll>o.height?"top":"top"==g&&j.top-o.scroll-l<0?"bottom":"right"==g&&j.right+k>o.width?"left":"left"==g&&j.left-k<o.left?"right":g,e.removeClass(m).addClass(g)}var p=this.getCalculatedOffset(g,j,k,l);this.applyPlacement(p,g);var q=function(){d.$element.trigger("shown.bs."+d.type),d.hoverState=null};a.support.transition&&this.$tip.hasClass("fade")?e.one("bsTransitionEnd",q).emulateTransitionEnd(150):q()}},c.prototype.applyPlacement=function(b,c){var d=this.tip(),e=d[0].offsetWidth,f=d[0].offsetHeight,g=parseInt(d.css("margin-top"),10),h=parseInt(d.css("margin-left"),10);isNaN(g)&&(g=0),isNaN(h)&&(h=0),b.top=b.top+g,b.left=b.left+h,a.offset.setOffset(d[0],a.extend({using:function(a){d.css({top:Math.round(a.top),left:Math.round(a.left)})}},b),0),d.addClass("in");var i=d[0].offsetWidth,j=d[0].offsetHeight;"top"==c&&j!=f&&(b.top=b.top+f-j);var k=this.getViewportAdjustedDelta(c,b,i,j);k.left?b.left+=k.left:b.top+=k.top;var l=k.left?2*k.left-e+i:2*k.top-f+j,m=k.left?"left":"top",n=k.left?"offsetWidth":"offsetHeight";d.offset(b),this.replaceArrow(l,d[0][n],m)},c.prototype.replaceArrow=function(a,b,c){this.arrow().css(c,a?50*(1-a/b)+"%":"")},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle();a.find(".tooltip-inner")[this.options.html?"html":"text"](b),a.removeClass("fade in top bottom left right")},c.prototype.hide=function(){function b(){"in"!=c.hoverState&&d.detach(),c.$element.trigger("hidden.bs."+c.type)}var c=this,d=this.tip(),e=a.Event("hide.bs."+this.type);return this.$element.removeAttr("aria-describedby"),this.$element.trigger(e),e.isDefaultPrevented()?void 0:(d.removeClass("in"),a.support.transition&&this.$tip.hasClass("fade")?d.one("bsTransitionEnd",b).emulateTransitionEnd(150):b(),this.hoverState=null,this)},c.prototype.fixTitle=function(){var a=this.$element;(a.attr("title")||"string"!=typeof a.attr("data-original-title"))&&a.attr("data-original-title",a.attr("title")||"").attr("title","")},c.prototype.hasContent=function(){return this.getTitle()},c.prototype.getPosition=function(b){b=b||this.$element;var c=b[0],d="BODY"==c.tagName;return a.extend({},"function"==typeof c.getBoundingClientRect?c.getBoundingClientRect():null,{scroll:d?document.documentElement.scrollTop||document.body.scrollTop:b.scrollTop(),width:d?a(window).width():b.outerWidth(),height:d?a(window).height():b.outerHeight()},d?{top:0,left:0}:b.offset())},c.prototype.getCalculatedOffset=function(a,b,c,d){return"bottom"==a?{top:b.top+b.height,left:b.left+b.width/2-c/2}:"top"==a?{top:b.top-d,left:b.left+b.width/2-c/2}:"left"==a?{top:b.top+b.height/2-d/2,left:b.left-c}:{top:b.top+b.height/2-d/2,left:b.left+b.width}},c.prototype.getViewportAdjustedDelta=function(a,b,c,d){var e={top:0,left:0};if(!this.$viewport)return e;var f=this.options.viewport&&this.options.viewport.padding||0,g=this.getPosition(this.$viewport);if(/right|left/.test(a)){var h=b.top-f-g.scroll,i=b.top+f-g.scroll+d;h<g.top?e.top=g.top-h:i>g.top+g.height&&(e.top=g.top+g.height-i)}else{var j=b.left-f,k=b.left+f+c;j<g.left?e.left=g.left-j:k>g.width&&(e.left=g.left+g.width-k)}return e},c.prototype.getTitle=function(){var a,b=this.$element,c=this.options;return a=b.attr("data-original-title")||("function"==typeof c.title?c.title.call(b[0]):c.title)},c.prototype.getUID=function(a){do a+=~~(1e6*Math.random());while(document.getElementById(a));return a},c.prototype.tip=function(){return this.$tip=this.$tip||a(this.options.template)},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},c.prototype.validate=function(){this.$element[0].parentNode||(this.hide(),this.$element=null,this.options=null)},c.prototype.enable=function(){this.enabled=!0},c.prototype.disable=function(){this.enabled=!1},c.prototype.toggleEnabled=function(){this.enabled=!this.enabled},c.prototype.toggle=function(b){var c=this;b&&(c=a(b.currentTarget).data("bs."+this.type),c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c))),c.tip().hasClass("in")?c.leave(c):c.enter(c)},c.prototype.destroy=function(){clearTimeout(this.timeout),this.hide().$element.off("."+this.type).removeData("bs."+this.type)};var d=a.fn.tooltip;a.fn.tooltip=b,a.fn.tooltip.Constructor=c,a.fn.tooltip.noConflict=function(){return a.fn.tooltip=d,this}}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.popover"),f="object"==typeof b&&b;(e||"destroy"!=b)&&(e||d.data("bs.popover",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.init("popover",a,b)};if(!a.fn.tooltip)throw new Error("Popover requires tooltip.js");c.VERSION="3.2.0",c.DEFAULTS=a.extend({},a.fn.tooltip.Constructor.DEFAULTS,{placement:"right",trigger:"click",content:"",template:'<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'}),c.prototype=a.extend({},a.fn.tooltip.Constructor.prototype),c.prototype.constructor=c,c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle(),c=this.getContent();a.find(".popover-title")[this.options.html?"html":"text"](b),a.find(".popover-content").empty()[this.options.html?"string"==typeof c?"html":"append":"text"](c),a.removeClass("fade top bottom left right in"),a.find(".popover-title").html()||a.find(".popover-title").hide()},c.prototype.hasContent=function(){return this.getTitle()||this.getContent()},c.prototype.getContent=function(){var a=this.$element,b=this.options;return a.attr("data-content")||("function"==typeof b.content?b.content.call(a[0]):b.content)},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")},c.prototype.tip=function(){return this.$tip||(this.$tip=a(this.options.template)),this.$tip};var d=a.fn.popover;a.fn.popover=b,a.fn.popover.Constructor=c,a.fn.popover.noConflict=function(){return a.fn.popover=d,this}}(jQuery),+function(a){"use strict";function b(c,d){var e=a.proxy(this.process,this);this.$body=a("body"),this.$scrollElement=a(a(c).is("body")?window:c),this.options=a.extend({},b.DEFAULTS,d),this.selector=(this.options.target||"")+" .nav li > a",this.offsets=[],this.targets=[],this.activeTarget=null,this.scrollHeight=0,this.$scrollElement.on("scroll.bs.scrollspy",e),this.refresh(),this.process()}function c(c){return this.each(function(){var d=a(this),e=d.data("bs.scrollspy"),f="object"==typeof c&&c;e||d.data("bs.scrollspy",e=new b(this,f)),"string"==typeof c&&e[c]()})}b.VERSION="3.2.0",b.DEFAULTS={offset:10},b.prototype.getScrollHeight=function(){return this.$scrollElement[0].scrollHeight||Math.max(this.$body[0].scrollHeight,document.documentElement.scrollHeight)},b.prototype.refresh=function(){var b="offset",c=0;a.isWindow(this.$scrollElement[0])||(b="position",c=this.$scrollElement.scrollTop()),this.offsets=[],this.targets=[],this.scrollHeight=this.getScrollHeight();var d=this;this.$body.find(this.selector).map(function(){var d=a(this),e=d.data("target")||d.attr("href"),f=/^#./.test(e)&&a(e);return f&&f.length&&f.is(":visible")&&[[f[b]().top+c,e]]||null}).sort(function(a,b){return a[0]-b[0]}).each(function(){d.offsets.push(this[0]),d.targets.push(this[1])})},b.prototype.process=function(){var a,b=this.$scrollElement.scrollTop()+this.options.offset,c=this.getScrollHeight(),d=this.options.offset+c-this.$scrollElement.height(),e=this.offsets,f=this.targets,g=this.activeTarget;if(this.scrollHeight!=c&&this.refresh(),b>=d)return g!=(a=f[f.length-1])&&this.activate(a);if(g&&b<=e[0])return g!=(a=f[0])&&this.activate(a);for(a=e.length;a--;)g!=f[a]&&b>=e[a]&&(!e[a+1]||b<=e[a+1])&&this.activate(f[a])},b.prototype.activate=function(b){this.activeTarget=b,a(this.selector).parentsUntil(this.options.target,".active").removeClass("active");var c=this.selector+'[data-target="'+b+'"],'+this.selector+'[href="'+b+'"]',d=a(c).parents("li").addClass("active");d.parent(".dropdown-menu").length&&(d=d.closest("li.dropdown").addClass("active")),d.trigger("activate.bs.scrollspy")};var d=a.fn.scrollspy;a.fn.scrollspy=c,a.fn.scrollspy.Constructor=b,a.fn.scrollspy.noConflict=function(){return a.fn.scrollspy=d,this},a(window).on("load.bs.scrollspy.data-api",function(){a('[data-spy="scroll"]').each(function(){var b=a(this);c.call(b,b.data())})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.tab");e||d.data("bs.tab",e=new c(this)),"string"==typeof b&&e[b]()})}var c=function(b){this.element=a(b)};c.VERSION="3.2.0",c.prototype.show=function(){var b=this.element,c=b.closest("ul:not(.dropdown-menu)"),d=b.data("target");if(d||(d=b.attr("href"),d=d&&d.replace(/.*(?=#[^\s]*$)/,"")),!b.parent("li").hasClass("active")){var e=c.find(".active:last a")[0],f=a.Event("show.bs.tab",{relatedTarget:e});if(b.trigger(f),!f.isDefaultPrevented()){var g=a(d);this.activate(b.closest("li"),c),this.activate(g,g.parent(),function(){b.trigger({type:"shown.bs.tab",relatedTarget:e})})}}},c.prototype.activate=function(b,c,d){function e(){f.removeClass("active").find("> .dropdown-menu > .active").removeClass("active"),b.addClass("active"),g?(b[0].offsetWidth,b.addClass("in")):b.removeClass("fade"),b.parent(".dropdown-menu")&&b.closest("li.dropdown").addClass("active"),d&&d()}var f=c.find("> .active"),g=d&&a.support.transition&&f.hasClass("fade");g?f.one("bsTransitionEnd",e).emulateTransitionEnd(150):e(),f.removeClass("in")};var d=a.fn.tab;a.fn.tab=b,a.fn.tab.Constructor=c,a.fn.tab.noConflict=function(){return a.fn.tab=d,this},a(document).on("click.bs.tab.data-api",'[data-toggle="tab"], [data-toggle="pill"]',function(c){c.preventDefault(),b.call(a(this),"show")})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.affix"),f="object"==typeof b&&b;e||d.data("bs.affix",e=new c(this,f)),"string"==typeof b&&e[b]()})}var c=function(b,d){this.options=a.extend({},c.DEFAULTS,d),this.$target=a(this.options.target).on("scroll.bs.affix.data-api",a.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",a.proxy(this.checkPositionWithEventLoop,this)),this.$element=a(b),this.affixed=this.unpin=this.pinnedOffset=null,this.checkPosition()};c.VERSION="3.2.0",c.RESET="affix affix-top affix-bottom",c.DEFAULTS={offset:0,target:window},c.prototype.getPinnedOffset=function(){if(this.pinnedOffset)return this.pinnedOffset;this.$element.removeClass(c.RESET).addClass("affix");var a=this.$target.scrollTop(),b=this.$element.offset();return this.pinnedOffset=b.top-a},c.prototype.checkPositionWithEventLoop=function(){setTimeout(a.proxy(this.checkPosition,this),1)},c.prototype.checkPosition=function(){if(this.$element.is(":visible")){var b=a(document).height(),d=this.$target.scrollTop(),e=this.$element.offset(),f=this.options.offset,g=f.top,h=f.bottom;"object"!=typeof f&&(h=g=f),"function"==typeof g&&(g=f.top(this.$element)),"function"==typeof h&&(h=f.bottom(this.$element));var i=null!=this.unpin&&d+this.unpin<=e.top?!1:null!=h&&e.top+this.$element.height()>=b-h?"bottom":null!=g&&g>=d?"top":!1;if(this.affixed!==i){null!=this.unpin&&this.$element.css("top","");var j="affix"+(i?"-"+i:""),k=a.Event(j+".bs.affix");this.$element.trigger(k),k.isDefaultPrevented()||(this.affixed=i,this.unpin="bottom"==i?this.getPinnedOffset():null,this.$element.removeClass(c.RESET).addClass(j).trigger(a.Event(j.replace("affix","affixed"))),"bottom"==i&&this.$element.offset({top:b-this.$element.height()-h}))}}};var d=a.fn.affix;a.fn.affix=b,a.fn.affix.Constructor=c,a.fn.affix.noConflict=function(){return a.fn.affix=d,this},a(window).on("load",function(){a('[data-spy="affix"]').each(function(){var c=a(this),d=c.data();d.offset=d.offset||{},d.offsetBottom&&(d.offset.bottom=d.offsetBottom),d.offsetTop&&(d.offset.top=d.offsetTop),b.call(c,d)})})}(jQuery);
StepUpSoftware/StepUpSoftware.github.io
js/bootstrap.min.js
JavaScript
apache-2.0
31,819
/** * Module dependencies. */ var Transport = require('../transport') , parser = require('engine.io-parser') , debug = require('debug')('engine:ws') /** * Export the constructor. */ module.exports = WebSocket; /** * WebSocket transport * * @param {http.ServerRequest} * @api public */ function WebSocket (req) { Transport.call(this, req); var self = this; this.socket = req.websocket; this.socket.on('message', this.onData.bind(this)); this.socket.once('close', this.onClose.bind(this)); this.socket.on('error', this.onError.bind(this)); this.socket.on('headers', function (headers) { self.emit('headers', headers); }); this.writable = true; }; /** * Inherits from Transport. */ WebSocket.prototype.__proto__ = Transport.prototype; /** * Transport name * * @api public */ WebSocket.prototype.name = 'websocket'; /** * Advertise upgrade support. * * @api public */ WebSocket.prototype.handlesUpgrades = true; /** * Advertise framing support. * * @api public */ WebSocket.prototype.supportsFraming = true; /** * Processes the incoming data. * * @param {String} encoded packet * @api private */ WebSocket.prototype.onData = function (data) { debug('received "%s"', data); Transport.prototype.onData.call(this, data); }; /** * Writes a packet payload. * * @param {Array} packets * @api private */ WebSocket.prototype.send = function (packets) { var self = this; for (var i = 0, l = packets.length; i < l; i++) { parser.encodePacket(packets[i], this.supportsBinary, function(data) { debug('writing "%s"', data); self.writable = false; self.socket.send(data, function (err){ if (err) return self.onError('write error', err.stack); self.writable = true; self.emit('drain'); }); }); } }; /** * Closes the transport. * * @api private */ WebSocket.prototype.doClose = function (fn) { debug('closing'); this.socket.close(); fn && fn(); };
plantvsbirds/picknot-web
node_modules/socket.io/node_modules/engine.io/lib/transports/websocket.js
JavaScript
apache-2.0
1,984
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\HttpFoundation; /** * Request stack that controls the lifecycle of requests. * * @author Benjamin Eberlei <kontakt@beberlei.de> */ class RequestStack { /** * @var Request[] */ private $requests = array(); /** * Pushes a Request on the stack. * * This method should generally not be called directly as the stack * management should be taken care of by the application itself. */ public function push(Request $request) { $this->requests[] = $request; } /** * Pops the current request from the stack. * * This operation lets the current request go out of scope. * * This method should generally not be called directly as the stack * management should be taken care of by the application itself. * * @return Request|null */ public function pop() { if (!$this->requests) { return; } return array_pop($this->requests); } /** * @return Request|null */ public function getCurrentRequest() { return end($this->requests) ?: null; } /** * Gets the master Request. * * Be warned that making your code aware of the master request * might make it un-compatible with other features of your framework * like ESI support. * * @return Request|null */ public function getMasterRequest() { if (!$this->requests) { return; } return $this->requests[0]; } /** * Returns the parent request of the current. * * Be warned that making your code aware of the parent request * might make it un-compatible with other features of your framework * like ESI support. * * If current Request is the master request, it returns null. * * @return Request|null */ public function getParentRequest() { $pos = count($this->requests) - 2; if (!isset($this->requests[$pos])) { return; } return $this->requests[$pos]; } }
sml2h3/goldedu
vendor/symfony/http-foundation/RequestStack.php
PHP
apache-2.0
2,358
// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package proto /* * Routines for encoding data into the wire format for protocol buffers. */ import ( "errors" "fmt" "reflect" "sort" ) // RequiredNotSetError is the error returned if Marshal is called with // a protocol buffer struct whose required fields have not // all been initialized. It is also the error returned if Unmarshal is // called with an encoded protocol buffer that does not include all the // required fields. // // When printed, RequiredNotSetError reports the first unset required field in a // message. If the field cannot be precisely determined, it is reported as // "{Unknown}". type RequiredNotSetError struct { field string } func (e *RequiredNotSetError) Error() string { return fmt.Sprintf("proto: required field %q not set", e.field) } var ( // errRepeatedHasNil is the error returned if Marshal is called with // a struct with a repeated field containing a nil element. errRepeatedHasNil = errors.New("proto: repeated field has nil element") // ErrNil is the error returned if Marshal is called with nil. ErrNil = errors.New("proto: Marshal called with nil") ) // The fundamental encoders that put bytes on the wire. // Those that take integer types all accept uint64 and are // therefore of type valueEncoder. const maxVarintBytes = 10 // maximum length of a varint // EncodeVarint returns the varint encoding of x. // This is the format for the // int32, int64, uint32, uint64, bool, and enum // protocol buffer types. // Not used by the package itself, but helpful to clients // wishing to use the same encoding. func EncodeVarint(x uint64) []byte { var buf [maxVarintBytes]byte var n int for n = 0; x > 127; n++ { buf[n] = 0x80 | uint8(x&0x7F) x >>= 7 } buf[n] = uint8(x) n++ return buf[0:n] } // EncodeVarint writes a varint-encoded integer to the Buffer. // This is the format for the // int32, int64, uint32, uint64, bool, and enum // protocol buffer types. func (p *Buffer) EncodeVarint(x uint64) error { for x >= 1<<7 { p.buf = append(p.buf, uint8(x&0x7f|0x80)) x >>= 7 } p.buf = append(p.buf, uint8(x)) return nil } func sizeVarint(x uint64) (n int) { for { n++ x >>= 7 if x == 0 { break } } return n } // EncodeFixed64 writes a 64-bit integer to the Buffer. // This is the format for the // fixed64, sfixed64, and double protocol buffer types. func (p *Buffer) EncodeFixed64(x uint64) error { p.buf = append(p.buf, uint8(x), uint8(x>>8), uint8(x>>16), uint8(x>>24), uint8(x>>32), uint8(x>>40), uint8(x>>48), uint8(x>>56)) return nil } func sizeFixed64(x uint64) int { return 8 } // EncodeFixed32 writes a 32-bit integer to the Buffer. // This is the format for the // fixed32, sfixed32, and float protocol buffer types. func (p *Buffer) EncodeFixed32(x uint64) error { p.buf = append(p.buf, uint8(x), uint8(x>>8), uint8(x>>16), uint8(x>>24)) return nil } func sizeFixed32(x uint64) int { return 4 } // EncodeZigzag64 writes a zigzag-encoded 64-bit integer // to the Buffer. // This is the format used for the sint64 protocol buffer type. func (p *Buffer) EncodeZigzag64(x uint64) error { // use signed number to get arithmetic right shift. return p.EncodeVarint(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } func sizeZigzag64(x uint64) int { return sizeVarint(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } // EncodeZigzag32 writes a zigzag-encoded 32-bit integer // to the Buffer. // This is the format used for the sint32 protocol buffer type. func (p *Buffer) EncodeZigzag32(x uint64) error { // use signed number to get arithmetic right shift. return p.EncodeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31)))) } func sizeZigzag32(x uint64) int { return sizeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31)))) } // EncodeRawBytes writes a count-delimited byte buffer to the Buffer. // This is the format used for the bytes protocol buffer // type and for embedded messages. func (p *Buffer) EncodeRawBytes(b []byte) error { p.EncodeVarint(uint64(len(b))) p.buf = append(p.buf, b...) return nil } func sizeRawBytes(b []byte) int { return sizeVarint(uint64(len(b))) + len(b) } // EncodeStringBytes writes an encoded string to the Buffer. // This is the format used for the proto2 string type. func (p *Buffer) EncodeStringBytes(s string) error { p.EncodeVarint(uint64(len(s))) p.buf = append(p.buf, s...) return nil } func sizeStringBytes(s string) int { return sizeVarint(uint64(len(s))) + len(s) } // Marshaler is the interface representing objects that can marshal themselves. type Marshaler interface { Marshal() ([]byte, error) } // Marshal takes the protocol buffer // and encodes it into the wire format, returning the data. func Marshal(pb Message) ([]byte, error) { // Can the object marshal itself? if m, ok := pb.(Marshaler); ok { return m.Marshal() } p := NewBuffer(nil) err := p.Marshal(pb) var state errorState if err != nil && !state.shouldContinue(err, nil) { return nil, err } if p.buf == nil && err == nil { // Return a non-nil slice on success. return []byte{}, nil } return p.buf, err } // EncodeMessage writes the protocol buffer to the Buffer, // prefixed by a varint-encoded length. func (p *Buffer) EncodeMessage(pb Message) error { t, base, err := getbase(pb) if structPointer_IsNil(base) { return ErrNil } if err == nil { var state errorState err = p.enc_len_struct(GetProperties(t.Elem()), base, &state) } return err } // Marshal takes the protocol buffer // and encodes it into the wire format, writing the result to the // Buffer. func (p *Buffer) Marshal(pb Message) error { // Can the object marshal itself? if m, ok := pb.(Marshaler); ok { data, err := m.Marshal() if err != nil { return err } p.buf = append(p.buf, data...) return nil } t, base, err := getbase(pb) if structPointer_IsNil(base) { return ErrNil } if err == nil { err = p.enc_struct(GetProperties(t.Elem()), base) } if collectStats { stats.Encode++ } return err } // Size returns the encoded size of a protocol buffer. func Size(pb Message) (n int) { // Can the object marshal itself? If so, Size is slow. // TODO: add Size to Marshaler, or add a Sizer interface. if m, ok := pb.(Marshaler); ok { b, _ := m.Marshal() return len(b) } t, base, err := getbase(pb) if structPointer_IsNil(base) { return 0 } if err == nil { n = size_struct(GetProperties(t.Elem()), base) } if collectStats { stats.Size++ } return } // Individual type encoders. // Encode a bool. func (o *Buffer) enc_bool(p *Properties, base structPointer) error { v := *structPointer_Bool(base, p.field) if v == nil { return ErrNil } x := 0 if *v { x = 1 } o.buf = append(o.buf, p.tagcode...) p.valEnc(o, uint64(x)) return nil } func (o *Buffer) enc_proto3_bool(p *Properties, base structPointer) error { v := *structPointer_BoolVal(base, p.field) if !v { return ErrNil } o.buf = append(o.buf, p.tagcode...) p.valEnc(o, 1) return nil } func size_bool(p *Properties, base structPointer) int { v := *structPointer_Bool(base, p.field) if v == nil { return 0 } return len(p.tagcode) + 1 // each bool takes exactly one byte } func size_proto3_bool(p *Properties, base structPointer) int { v := *structPointer_BoolVal(base, p.field) if !v && !p.oneof { return 0 } return len(p.tagcode) + 1 // each bool takes exactly one byte } // Encode an int32. func (o *Buffer) enc_int32(p *Properties, base structPointer) error { v := structPointer_Word32(base, p.field) if word32_IsNil(v) { return ErrNil } x := int32(word32_Get(v)) // permit sign extension to use full 64-bit range o.buf = append(o.buf, p.tagcode...) p.valEnc(o, uint64(x)) return nil } func (o *Buffer) enc_proto3_int32(p *Properties, base structPointer) error { v := structPointer_Word32Val(base, p.field) x := int32(word32Val_Get(v)) // permit sign extension to use full 64-bit range if x == 0 { return ErrNil } o.buf = append(o.buf, p.tagcode...) p.valEnc(o, uint64(x)) return nil } func size_int32(p *Properties, base structPointer) (n int) { v := structPointer_Word32(base, p.field) if word32_IsNil(v) { return 0 } x := int32(word32_Get(v)) // permit sign extension to use full 64-bit range n += len(p.tagcode) n += p.valSize(uint64(x)) return } func size_proto3_int32(p *Properties, base structPointer) (n int) { v := structPointer_Word32Val(base, p.field) x := int32(word32Val_Get(v)) // permit sign extension to use full 64-bit range if x == 0 && !p.oneof { return 0 } n += len(p.tagcode) n += p.valSize(uint64(x)) return } // Encode a uint32. // Exactly the same as int32, except for no sign extension. func (o *Buffer) enc_uint32(p *Properties, base structPointer) error { v := structPointer_Word32(base, p.field) if word32_IsNil(v) { return ErrNil } x := word32_Get(v) o.buf = append(o.buf, p.tagcode...) p.valEnc(o, uint64(x)) return nil } func (o *Buffer) enc_proto3_uint32(p *Properties, base structPointer) error { v := structPointer_Word32Val(base, p.field) x := word32Val_Get(v) if x == 0 { return ErrNil } o.buf = append(o.buf, p.tagcode...) p.valEnc(o, uint64(x)) return nil } func size_uint32(p *Properties, base structPointer) (n int) { v := structPointer_Word32(base, p.field) if word32_IsNil(v) { return 0 } x := word32_Get(v) n += len(p.tagcode) n += p.valSize(uint64(x)) return } func size_proto3_uint32(p *Properties, base structPointer) (n int) { v := structPointer_Word32Val(base, p.field) x := word32Val_Get(v) if x == 0 && !p.oneof { return 0 } n += len(p.tagcode) n += p.valSize(uint64(x)) return } // Encode an int64. func (o *Buffer) enc_int64(p *Properties, base structPointer) error { v := structPointer_Word64(base, p.field) if word64_IsNil(v) { return ErrNil } x := word64_Get(v) o.buf = append(o.buf, p.tagcode...) p.valEnc(o, x) return nil } func (o *Buffer) enc_proto3_int64(p *Properties, base structPointer) error { v := structPointer_Word64Val(base, p.field) x := word64Val_Get(v) if x == 0 { return ErrNil } o.buf = append(o.buf, p.tagcode...) p.valEnc(o, x) return nil } func size_int64(p *Properties, base structPointer) (n int) { v := structPointer_Word64(base, p.field) if word64_IsNil(v) { return 0 } x := word64_Get(v) n += len(p.tagcode) n += p.valSize(x) return } func size_proto3_int64(p *Properties, base structPointer) (n int) { v := structPointer_Word64Val(base, p.field) x := word64Val_Get(v) if x == 0 && !p.oneof { return 0 } n += len(p.tagcode) n += p.valSize(x) return } // Encode a string. func (o *Buffer) enc_string(p *Properties, base structPointer) error { v := *structPointer_String(base, p.field) if v == nil { return ErrNil } x := *v o.buf = append(o.buf, p.tagcode...) o.EncodeStringBytes(x) return nil } func (o *Buffer) enc_proto3_string(p *Properties, base structPointer) error { v := *structPointer_StringVal(base, p.field) if v == "" { return ErrNil } o.buf = append(o.buf, p.tagcode...) o.EncodeStringBytes(v) return nil } func size_string(p *Properties, base structPointer) (n int) { v := *structPointer_String(base, p.field) if v == nil { return 0 } x := *v n += len(p.tagcode) n += sizeStringBytes(x) return } func size_proto3_string(p *Properties, base structPointer) (n int) { v := *structPointer_StringVal(base, p.field) if v == "" && !p.oneof { return 0 } n += len(p.tagcode) n += sizeStringBytes(v) return } // All protocol buffer fields are nillable, but be careful. func isNil(v reflect.Value) bool { switch v.Kind() { case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: return v.IsNil() } return false } // Encode a message struct. func (o *Buffer) enc_struct_message(p *Properties, base structPointer) error { var state errorState structp := structPointer_GetStructPointer(base, p.field) if structPointer_IsNil(structp) { return ErrNil } // Can the object marshal itself? if p.isMarshaler { m := structPointer_Interface(structp, p.stype).(Marshaler) data, err := m.Marshal() if err != nil && !state.shouldContinue(err, nil) { return err } o.buf = append(o.buf, p.tagcode...) o.EncodeRawBytes(data) return state.err } o.buf = append(o.buf, p.tagcode...) return o.enc_len_struct(p.sprop, structp, &state) } func size_struct_message(p *Properties, base structPointer) int { structp := structPointer_GetStructPointer(base, p.field) if structPointer_IsNil(structp) { return 0 } // Can the object marshal itself? if p.isMarshaler { m := structPointer_Interface(structp, p.stype).(Marshaler) data, _ := m.Marshal() n0 := len(p.tagcode) n1 := sizeRawBytes(data) return n0 + n1 } n0 := len(p.tagcode) n1 := size_struct(p.sprop, structp) n2 := sizeVarint(uint64(n1)) // size of encoded length return n0 + n1 + n2 } // Encode a group struct. func (o *Buffer) enc_struct_group(p *Properties, base structPointer) error { var state errorState b := structPointer_GetStructPointer(base, p.field) if structPointer_IsNil(b) { return ErrNil } o.EncodeVarint(uint64((p.Tag << 3) | WireStartGroup)) err := o.enc_struct(p.sprop, b) if err != nil && !state.shouldContinue(err, nil) { return err } o.EncodeVarint(uint64((p.Tag << 3) | WireEndGroup)) return state.err } func size_struct_group(p *Properties, base structPointer) (n int) { b := structPointer_GetStructPointer(base, p.field) if structPointer_IsNil(b) { return 0 } n += sizeVarint(uint64((p.Tag << 3) | WireStartGroup)) n += size_struct(p.sprop, b) n += sizeVarint(uint64((p.Tag << 3) | WireEndGroup)) return } // Encode a slice of bools ([]bool). func (o *Buffer) enc_slice_bool(p *Properties, base structPointer) error { s := *structPointer_BoolSlice(base, p.field) l := len(s) if l == 0 { return ErrNil } for _, x := range s { o.buf = append(o.buf, p.tagcode...) v := uint64(0) if x { v = 1 } p.valEnc(o, v) } return nil } func size_slice_bool(p *Properties, base structPointer) int { s := *structPointer_BoolSlice(base, p.field) l := len(s) if l == 0 { return 0 } return l * (len(p.tagcode) + 1) // each bool takes exactly one byte } // Encode a slice of bools ([]bool) in packed format. func (o *Buffer) enc_slice_packed_bool(p *Properties, base structPointer) error { s := *structPointer_BoolSlice(base, p.field) l := len(s) if l == 0 { return ErrNil } o.buf = append(o.buf, p.tagcode...) o.EncodeVarint(uint64(l)) // each bool takes exactly one byte for _, x := range s { v := uint64(0) if x { v = 1 } p.valEnc(o, v) } return nil } func size_slice_packed_bool(p *Properties, base structPointer) (n int) { s := *structPointer_BoolSlice(base, p.field) l := len(s) if l == 0 { return 0 } n += len(p.tagcode) n += sizeVarint(uint64(l)) n += l // each bool takes exactly one byte return } // Encode a slice of bytes ([]byte). func (o *Buffer) enc_slice_byte(p *Properties, base structPointer) error { s := *structPointer_Bytes(base, p.field) if s == nil { return ErrNil } o.buf = append(o.buf, p.tagcode...) o.EncodeRawBytes(s) return nil } func (o *Buffer) enc_proto3_slice_byte(p *Properties, base structPointer) error { s := *structPointer_Bytes(base, p.field) if len(s) == 0 { return ErrNil } o.buf = append(o.buf, p.tagcode...) o.EncodeRawBytes(s) return nil } func size_slice_byte(p *Properties, base structPointer) (n int) { s := *structPointer_Bytes(base, p.field) if s == nil && !p.oneof { return 0 } n += len(p.tagcode) n += sizeRawBytes(s) return } func size_proto3_slice_byte(p *Properties, base structPointer) (n int) { s := *structPointer_Bytes(base, p.field) if len(s) == 0 && !p.oneof { return 0 } n += len(p.tagcode) n += sizeRawBytes(s) return } // Encode a slice of int32s ([]int32). func (o *Buffer) enc_slice_int32(p *Properties, base structPointer) error { s := structPointer_Word32Slice(base, p.field) l := s.Len() if l == 0 { return ErrNil } for i := 0; i < l; i++ { o.buf = append(o.buf, p.tagcode...) x := int32(s.Index(i)) // permit sign extension to use full 64-bit range p.valEnc(o, uint64(x)) } return nil } func size_slice_int32(p *Properties, base structPointer) (n int) { s := structPointer_Word32Slice(base, p.field) l := s.Len() if l == 0 { return 0 } for i := 0; i < l; i++ { n += len(p.tagcode) x := int32(s.Index(i)) // permit sign extension to use full 64-bit range n += p.valSize(uint64(x)) } return } // Encode a slice of int32s ([]int32) in packed format. func (o *Buffer) enc_slice_packed_int32(p *Properties, base structPointer) error { s := structPointer_Word32Slice(base, p.field) l := s.Len() if l == 0 { return ErrNil } // TODO: Reuse a Buffer. buf := NewBuffer(nil) for i := 0; i < l; i++ { x := int32(s.Index(i)) // permit sign extension to use full 64-bit range p.valEnc(buf, uint64(x)) } o.buf = append(o.buf, p.tagcode...) o.EncodeVarint(uint64(len(buf.buf))) o.buf = append(o.buf, buf.buf...) return nil } func size_slice_packed_int32(p *Properties, base structPointer) (n int) { s := structPointer_Word32Slice(base, p.field) l := s.Len() if l == 0 { return 0 } var bufSize int for i := 0; i < l; i++ { x := int32(s.Index(i)) // permit sign extension to use full 64-bit range bufSize += p.valSize(uint64(x)) } n += len(p.tagcode) n += sizeVarint(uint64(bufSize)) n += bufSize return } // Encode a slice of uint32s ([]uint32). // Exactly the same as int32, except for no sign extension. func (o *Buffer) enc_slice_uint32(p *Properties, base structPointer) error { s := structPointer_Word32Slice(base, p.field) l := s.Len() if l == 0 { return ErrNil } for i := 0; i < l; i++ { o.buf = append(o.buf, p.tagcode...) x := s.Index(i) p.valEnc(o, uint64(x)) } return nil } func size_slice_uint32(p *Properties, base structPointer) (n int) { s := structPointer_Word32Slice(base, p.field) l := s.Len() if l == 0 { return 0 } for i := 0; i < l; i++ { n += len(p.tagcode) x := s.Index(i) n += p.valSize(uint64(x)) } return } // Encode a slice of uint32s ([]uint32) in packed format. // Exactly the same as int32, except for no sign extension. func (o *Buffer) enc_slice_packed_uint32(p *Properties, base structPointer) error { s := structPointer_Word32Slice(base, p.field) l := s.Len() if l == 0 { return ErrNil } // TODO: Reuse a Buffer. buf := NewBuffer(nil) for i := 0; i < l; i++ { p.valEnc(buf, uint64(s.Index(i))) } o.buf = append(o.buf, p.tagcode...) o.EncodeVarint(uint64(len(buf.buf))) o.buf = append(o.buf, buf.buf...) return nil } func size_slice_packed_uint32(p *Properties, base structPointer) (n int) { s := structPointer_Word32Slice(base, p.field) l := s.Len() if l == 0 { return 0 } var bufSize int for i := 0; i < l; i++ { bufSize += p.valSize(uint64(s.Index(i))) } n += len(p.tagcode) n += sizeVarint(uint64(bufSize)) n += bufSize return } // Encode a slice of int64s ([]int64). func (o *Buffer) enc_slice_int64(p *Properties, base structPointer) error { s := structPointer_Word64Slice(base, p.field) l := s.Len() if l == 0 { return ErrNil } for i := 0; i < l; i++ { o.buf = append(o.buf, p.tagcode...) p.valEnc(o, s.Index(i)) } return nil } func size_slice_int64(p *Properties, base structPointer) (n int) { s := structPointer_Word64Slice(base, p.field) l := s.Len() if l == 0 { return 0 } for i := 0; i < l; i++ { n += len(p.tagcode) n += p.valSize(s.Index(i)) } return } // Encode a slice of int64s ([]int64) in packed format. func (o *Buffer) enc_slice_packed_int64(p *Properties, base structPointer) error { s := structPointer_Word64Slice(base, p.field) l := s.Len() if l == 0 { return ErrNil } // TODO: Reuse a Buffer. buf := NewBuffer(nil) for i := 0; i < l; i++ { p.valEnc(buf, s.Index(i)) } o.buf = append(o.buf, p.tagcode...) o.EncodeVarint(uint64(len(buf.buf))) o.buf = append(o.buf, buf.buf...) return nil } func size_slice_packed_int64(p *Properties, base structPointer) (n int) { s := structPointer_Word64Slice(base, p.field) l := s.Len() if l == 0 { return 0 } var bufSize int for i := 0; i < l; i++ { bufSize += p.valSize(s.Index(i)) } n += len(p.tagcode) n += sizeVarint(uint64(bufSize)) n += bufSize return } // Encode a slice of slice of bytes ([][]byte). func (o *Buffer) enc_slice_slice_byte(p *Properties, base structPointer) error { ss := *structPointer_BytesSlice(base, p.field) l := len(ss) if l == 0 { return ErrNil } for i := 0; i < l; i++ { o.buf = append(o.buf, p.tagcode...) o.EncodeRawBytes(ss[i]) } return nil } func size_slice_slice_byte(p *Properties, base structPointer) (n int) { ss := *structPointer_BytesSlice(base, p.field) l := len(ss) if l == 0 { return 0 } n += l * len(p.tagcode) for i := 0; i < l; i++ { n += sizeRawBytes(ss[i]) } return } // Encode a slice of strings ([]string). func (o *Buffer) enc_slice_string(p *Properties, base structPointer) error { ss := *structPointer_StringSlice(base, p.field) l := len(ss) for i := 0; i < l; i++ { o.buf = append(o.buf, p.tagcode...) o.EncodeStringBytes(ss[i]) } return nil } func size_slice_string(p *Properties, base structPointer) (n int) { ss := *structPointer_StringSlice(base, p.field) l := len(ss) n += l * len(p.tagcode) for i := 0; i < l; i++ { n += sizeStringBytes(ss[i]) } return } // Encode a slice of message structs ([]*struct). func (o *Buffer) enc_slice_struct_message(p *Properties, base structPointer) error { var state errorState s := structPointer_StructPointerSlice(base, p.field) l := s.Len() for i := 0; i < l; i++ { structp := s.Index(i) if structPointer_IsNil(structp) { return errRepeatedHasNil } // Can the object marshal itself? if p.isMarshaler { m := structPointer_Interface(structp, p.stype).(Marshaler) data, err := m.Marshal() if err != nil && !state.shouldContinue(err, nil) { return err } o.buf = append(o.buf, p.tagcode...) o.EncodeRawBytes(data) continue } o.buf = append(o.buf, p.tagcode...) err := o.enc_len_struct(p.sprop, structp, &state) if err != nil && !state.shouldContinue(err, nil) { if err == ErrNil { return errRepeatedHasNil } return err } } return state.err } func size_slice_struct_message(p *Properties, base structPointer) (n int) { s := structPointer_StructPointerSlice(base, p.field) l := s.Len() n += l * len(p.tagcode) for i := 0; i < l; i++ { structp := s.Index(i) if structPointer_IsNil(structp) { return // return the size up to this point } // Can the object marshal itself? if p.isMarshaler { m := structPointer_Interface(structp, p.stype).(Marshaler) data, _ := m.Marshal() n += len(p.tagcode) n += sizeRawBytes(data) continue } n0 := size_struct(p.sprop, structp) n1 := sizeVarint(uint64(n0)) // size of encoded length n += n0 + n1 } return } // Encode a slice of group structs ([]*struct). func (o *Buffer) enc_slice_struct_group(p *Properties, base structPointer) error { var state errorState s := structPointer_StructPointerSlice(base, p.field) l := s.Len() for i := 0; i < l; i++ { b := s.Index(i) if structPointer_IsNil(b) { return errRepeatedHasNil } o.EncodeVarint(uint64((p.Tag << 3) | WireStartGroup)) err := o.enc_struct(p.sprop, b) if err != nil && !state.shouldContinue(err, nil) { if err == ErrNil { return errRepeatedHasNil } return err } o.EncodeVarint(uint64((p.Tag << 3) | WireEndGroup)) } return state.err } func size_slice_struct_group(p *Properties, base structPointer) (n int) { s := structPointer_StructPointerSlice(base, p.field) l := s.Len() n += l * sizeVarint(uint64((p.Tag<<3)|WireStartGroup)) n += l * sizeVarint(uint64((p.Tag<<3)|WireEndGroup)) for i := 0; i < l; i++ { b := s.Index(i) if structPointer_IsNil(b) { return // return size up to this point } n += size_struct(p.sprop, b) } return } // Encode an extension map. func (o *Buffer) enc_map(p *Properties, base structPointer) error { v := *structPointer_ExtMap(base, p.field) if err := encodeExtensionMap(v); err != nil { return err } // Fast-path for common cases: zero or one extensions. if len(v) <= 1 { for _, e := range v { o.buf = append(o.buf, e.enc...) } return nil } // Sort keys to provide a deterministic encoding. keys := make([]int, 0, len(v)) for k := range v { keys = append(keys, int(k)) } sort.Ints(keys) for _, k := range keys { o.buf = append(o.buf, v[int32(k)].enc...) } return nil } func size_map(p *Properties, base structPointer) int { v := *structPointer_ExtMap(base, p.field) return sizeExtensionMap(v) } // Encode a map field. func (o *Buffer) enc_new_map(p *Properties, base structPointer) error { var state errorState // XXX: or do we need to plumb this through? /* A map defined as map<key_type, value_type> map_field = N; is encoded in the same way as message MapFieldEntry { key_type key = 1; value_type value = 2; } repeated MapFieldEntry map_field = N; */ v := structPointer_NewAt(base, p.field, p.mtype).Elem() // map[K]V if v.Len() == 0 { return nil } keycopy, valcopy, keybase, valbase := mapEncodeScratch(p.mtype) enc := func() error { if err := p.mkeyprop.enc(o, p.mkeyprop, keybase); err != nil { return err } if err := p.mvalprop.enc(o, p.mvalprop, valbase); err != nil { return err } return nil } // Don't sort map keys. It is not required by the spec, and C++ doesn't do it. for _, key := range v.MapKeys() { val := v.MapIndex(key) // The only illegal map entry values are nil message pointers. if val.Kind() == reflect.Ptr && val.IsNil() { return errors.New("proto: map has nil element") } keycopy.Set(key) valcopy.Set(val) o.buf = append(o.buf, p.tagcode...) if err := o.enc_len_thing(enc, &state); err != nil { return err } } return nil } func size_new_map(p *Properties, base structPointer) int { v := structPointer_NewAt(base, p.field, p.mtype).Elem() // map[K]V keycopy, valcopy, keybase, valbase := mapEncodeScratch(p.mtype) n := 0 for _, key := range v.MapKeys() { val := v.MapIndex(key) keycopy.Set(key) valcopy.Set(val) // Tag codes for key and val are the responsibility of the sub-sizer. keysize := p.mkeyprop.size(p.mkeyprop, keybase) valsize := p.mvalprop.size(p.mvalprop, valbase) entry := keysize + valsize // Add on tag code and length of map entry itself. n += len(p.tagcode) + sizeVarint(uint64(entry)) + entry } return n } // mapEncodeScratch returns a new reflect.Value matching the map's value type, // and a structPointer suitable for passing to an encoder or sizer. func mapEncodeScratch(mapType reflect.Type) (keycopy, valcopy reflect.Value, keybase, valbase structPointer) { // Prepare addressable doubly-indirect placeholders for the key and value types. // This is needed because the element-type encoders expect **T, but the map iteration produces T. keycopy = reflect.New(mapType.Key()).Elem() // addressable K keyptr := reflect.New(reflect.PtrTo(keycopy.Type())).Elem() // addressable *K keyptr.Set(keycopy.Addr()) // keybase = toStructPointer(keyptr.Addr()) // **K // Value types are more varied and require special handling. switch mapType.Elem().Kind() { case reflect.Slice: // []byte var dummy []byte valcopy = reflect.ValueOf(&dummy).Elem() // addressable []byte valbase = toStructPointer(valcopy.Addr()) case reflect.Ptr: // message; the generated field type is map[K]*Msg (so V is *Msg), // so we only need one level of indirection. valcopy = reflect.New(mapType.Elem()).Elem() // addressable V valbase = toStructPointer(valcopy.Addr()) default: // everything else valcopy = reflect.New(mapType.Elem()).Elem() // addressable V valptr := reflect.New(reflect.PtrTo(valcopy.Type())).Elem() // addressable *V valptr.Set(valcopy.Addr()) // valbase = toStructPointer(valptr.Addr()) // **V } return } // Encode a struct. func (o *Buffer) enc_struct(prop *StructProperties, base structPointer) error { var state errorState // Encode fields in tag order so that decoders may use optimizations // that depend on the ordering. // https://developers.google.com/protocol-buffers/docs/encoding#order for _, i := range prop.order { p := prop.Prop[i] if p.enc != nil { err := p.enc(o, p, base) if err != nil { if err == ErrNil { if p.Required && state.err == nil { state.err = &RequiredNotSetError{p.Name} } } else if err == errRepeatedHasNil { // Give more context to nil values in repeated fields. return errors.New("repeated field " + p.OrigName + " has nil element") } else if !state.shouldContinue(err, p) { return err } } } } // Do oneof fields. if prop.oneofMarshaler != nil { m := structPointer_Interface(base, prop.stype).(Message) if err := prop.oneofMarshaler(m, o); err != nil { return err } } // Add unrecognized fields at the end. if prop.unrecField.IsValid() { v := *structPointer_Bytes(base, prop.unrecField) if len(v) > 0 { o.buf = append(o.buf, v...) } } return state.err } func size_struct(prop *StructProperties, base structPointer) (n int) { for _, i := range prop.order { p := prop.Prop[i] if p.size != nil { n += p.size(p, base) } } // Add unrecognized fields at the end. if prop.unrecField.IsValid() { v := *structPointer_Bytes(base, prop.unrecField) n += len(v) } // Factor in any oneof fields. // TODO: This could be faster and use less reflection. if prop.oneofMarshaler != nil { sv := reflect.ValueOf(structPointer_Interface(base, prop.stype)).Elem() for i := 0; i < prop.stype.NumField(); i++ { fv := sv.Field(i) if fv.Kind() != reflect.Interface || fv.IsNil() { continue } if prop.stype.Field(i).Tag.Get("protobuf_oneof") == "" { continue } spv := fv.Elem() // interface -> *T sv := spv.Elem() // *T -> T sf := sv.Type().Field(0) // StructField inside T var prop Properties prop.Init(sf.Type, "whatever", sf.Tag.Get("protobuf"), &sf) n += prop.size(&prop, toStructPointer(spv)) } } return } var zeroes [20]byte // longer than any conceivable sizeVarint // Encode a struct, preceded by its encoded length (as a varint). func (o *Buffer) enc_len_struct(prop *StructProperties, base structPointer, state *errorState) error { return o.enc_len_thing(func() error { return o.enc_struct(prop, base) }, state) } // Encode something, preceded by its encoded length (as a varint). func (o *Buffer) enc_len_thing(enc func() error, state *errorState) error { iLen := len(o.buf) o.buf = append(o.buf, 0, 0, 0, 0) // reserve four bytes for length iMsg := len(o.buf) err := enc() if err != nil && !state.shouldContinue(err, nil) { return err } lMsg := len(o.buf) - iMsg lLen := sizeVarint(uint64(lMsg)) switch x := lLen - (iMsg - iLen); { case x > 0: // actual length is x bytes larger than the space we reserved // Move msg x bytes right. o.buf = append(o.buf, zeroes[:x]...) copy(o.buf[iMsg+x:], o.buf[iMsg:iMsg+lMsg]) case x < 0: // actual length is x bytes smaller than the space we reserved // Move msg x bytes left. copy(o.buf[iMsg+x:], o.buf[iMsg:iMsg+lMsg]) o.buf = o.buf[:len(o.buf)+x] // x is negative } // Encode the length in the reserved space. o.buf = o.buf[:iLen] o.EncodeVarint(uint64(lMsg)) o.buf = o.buf[:len(o.buf)+lMsg] return state.err } // errorState maintains the first error that occurs and updates that error // with additional context. type errorState struct { err error } // shouldContinue reports whether encoding should continue upon encountering the // given error. If the error is RequiredNotSetError, shouldContinue returns true // and, if this is the first appearance of that error, remembers it for future // reporting. // // If prop is not nil, it may update any error with additional context about the // field with the error. func (s *errorState) shouldContinue(err error, prop *Properties) bool { // Ignore unset required fields. reqNotSet, ok := err.(*RequiredNotSetError) if !ok { return false } if s.err == nil { if prop != nil { err = &RequiredNotSetError{prop.Name + "." + reqNotSet.field} } s.err = err } return true }
luxas/contrib
cluster-autoscaler/vendor/github.com/gogo/protobuf/proto/encode.go
GO
apache-2.0
34,123
// Copyright ©2014 The gonum Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package simple import ( "math" "testing" "k8s.io/kubernetes/third_party/forked/gonum/graph" ) var _ graph.Graph = (*UndirectedGraph)(nil) func TestAssertMutableNotDirected(t *testing.T) { var g graph.UndirectedBuilder = NewUndirectedGraph(0, math.Inf(1)) if _, ok := g.(graph.Directed); ok { t.Fatal("Graph is directed, but a MutableGraph cannot safely be directed!") } } func TestMaxID(t *testing.T) { g := NewUndirectedGraph(0, math.Inf(1)) nodes := make(map[graph.Node]struct{}) for i := Node(0); i < 3; i++ { g.AddNode(i) nodes[i] = struct{}{} } g.RemoveNode(Node(0)) delete(nodes, Node(0)) g.RemoveNode(Node(2)) delete(nodes, Node(2)) n := Node(g.NewNodeID()) g.AddNode(n) if !g.Has(n) { t.Error("added node does not exist in graph") } if _, exists := nodes[n]; exists { t.Errorf("Created already existing node id: %v", n.ID()) } } // Test for issue #123 https://github.com/gonum/graph/issues/123 func TestIssue123UndirectedGraph(t *testing.T) { defer func() { if r := recover(); r != nil { t.Errorf("unexpected panic: %v", r) } }() g := NewUndirectedGraph(0, math.Inf(1)) n0 := Node(g.NewNodeID()) g.AddNode(n0) n1 := Node(g.NewNodeID()) g.AddNode(n1) g.RemoveNode(n0) n2 := Node(g.NewNodeID()) g.AddNode(n2) }
errordeveloper/kubernetes
third_party/forked/gonum/graph/simple/undirected_test.go
GO
apache-2.0
1,439
package netlink import ( "syscall" "github.com/vishvananda/netlink/nl" ) func selFromPolicy(sel *nl.XfrmSelector, policy *XfrmPolicy) { sel.Family = uint16(nl.GetIPFamily(policy.Dst.IP)) sel.Daddr.FromIP(policy.Dst.IP) sel.Saddr.FromIP(policy.Src.IP) prefixlenD, _ := policy.Dst.Mask.Size() sel.PrefixlenD = uint8(prefixlenD) prefixlenS, _ := policy.Src.Mask.Size() sel.PrefixlenS = uint8(prefixlenS) } // XfrmPolicyAdd will add an xfrm policy to the system. // Equivalent to: `ip xfrm policy add $policy` func XfrmPolicyAdd(policy *XfrmPolicy) error { req := nl.NewNetlinkRequest(nl.XFRM_MSG_NEWPOLICY, syscall.NLM_F_CREATE|syscall.NLM_F_EXCL|syscall.NLM_F_ACK) msg := &nl.XfrmUserpolicyInfo{} selFromPolicy(&msg.Sel, policy) msg.Priority = uint32(policy.Priority) msg.Index = uint32(policy.Index) msg.Dir = uint8(policy.Dir) msg.Lft.SoftByteLimit = nl.XFRM_INF msg.Lft.HardByteLimit = nl.XFRM_INF msg.Lft.SoftPacketLimit = nl.XFRM_INF msg.Lft.HardPacketLimit = nl.XFRM_INF req.AddData(msg) tmplData := make([]byte, nl.SizeofXfrmUserTmpl*len(policy.Tmpls)) for i, tmpl := range policy.Tmpls { start := i * nl.SizeofXfrmUserTmpl userTmpl := nl.DeserializeXfrmUserTmpl(tmplData[start : start+nl.SizeofXfrmUserTmpl]) userTmpl.XfrmId.Daddr.FromIP(tmpl.Dst) userTmpl.Saddr.FromIP(tmpl.Src) userTmpl.XfrmId.Proto = uint8(tmpl.Proto) userTmpl.Mode = uint8(tmpl.Mode) userTmpl.Reqid = uint32(tmpl.Reqid) userTmpl.Aalgos = ^uint32(0) userTmpl.Ealgos = ^uint32(0) userTmpl.Calgos = ^uint32(0) } if len(tmplData) > 0 { tmpls := nl.NewRtAttr(nl.XFRMA_TMPL, tmplData) req.AddData(tmpls) } _, err := req.Execute(syscall.NETLINK_XFRM, 0) return err } // XfrmPolicyDel will delete an xfrm policy from the system. Note that // the Tmpls are ignored when matching the policy to delete. // Equivalent to: `ip xfrm policy del $policy` func XfrmPolicyDel(policy *XfrmPolicy) error { req := nl.NewNetlinkRequest(nl.XFRM_MSG_DELPOLICY, syscall.NLM_F_ACK) msg := &nl.XfrmUserpolicyId{} selFromPolicy(&msg.Sel, policy) msg.Index = uint32(policy.Index) msg.Dir = uint8(policy.Dir) req.AddData(msg) _, err := req.Execute(syscall.NETLINK_XFRM, 0) return err } // XfrmPolicyList gets a list of xfrm policies in the system. // Equivalent to: `ip xfrm policy show`. // The list can be filtered by ip family. func XfrmPolicyList(family int) ([]XfrmPolicy, error) { req := nl.NewNetlinkRequest(nl.XFRM_MSG_GETPOLICY, syscall.NLM_F_DUMP) msg := nl.NewIfInfomsg(family) req.AddData(msg) msgs, err := req.Execute(syscall.NETLINK_XFRM, nl.XFRM_MSG_NEWPOLICY) if err != nil { return nil, err } var res []XfrmPolicy for _, m := range msgs { msg := nl.DeserializeXfrmUserpolicyInfo(m) if family != FAMILY_ALL && family != int(msg.Sel.Family) { continue } var policy XfrmPolicy policy.Dst = msg.Sel.Daddr.ToIPNet(msg.Sel.PrefixlenD) policy.Src = msg.Sel.Saddr.ToIPNet(msg.Sel.PrefixlenS) policy.Priority = int(msg.Priority) policy.Index = int(msg.Index) policy.Dir = Dir(msg.Dir) attrs, err := nl.ParseRouteAttr(m[msg.Len():]) if err != nil { return nil, err } for _, attr := range attrs { switch attr.Attr.Type { case nl.XFRMA_TMPL: max := len(attr.Value) for i := 0; i < max; i += nl.SizeofXfrmUserTmpl { var resTmpl XfrmPolicyTmpl tmpl := nl.DeserializeXfrmUserTmpl(attr.Value[i : i+nl.SizeofXfrmUserTmpl]) resTmpl.Dst = tmpl.XfrmId.Daddr.ToIP() resTmpl.Src = tmpl.Saddr.ToIP() resTmpl.Proto = Proto(tmpl.XfrmId.Proto) resTmpl.Mode = Mode(tmpl.Mode) resTmpl.Reqid = int(tmpl.Reqid) policy.Tmpls = append(policy.Tmpls, resTmpl) } } } res = append(res, policy) } return res, nil }
ABaldwinHunter/docker
vendor/src/github.com/vishvananda/netlink/xfrm_policy_linux.go
GO
apache-2.0
3,729
package matchers_test import ( "errors" "fmt" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" . "github.com/onsi/gomega/matchers" ) type CustomError struct { } func (c CustomError) Error() string { return "an error" } var _ = Describe("MatchErrorMatcher", func() { Context("When asserting against an error", func() { It("should succeed when matching with an error", func() { err := errors.New("an error") fmtErr := fmt.Errorf("an error") customErr := CustomError{} Ω(err).Should(MatchError(errors.New("an error"))) Ω(err).ShouldNot(MatchError(errors.New("another error"))) Ω(fmtErr).Should(MatchError(errors.New("an error"))) Ω(customErr).Should(MatchError(CustomError{})) }) It("should succeed when matching with a string", func() { err := errors.New("an error") fmtErr := fmt.Errorf("an error") customErr := CustomError{} Ω(err).Should(MatchError("an error")) Ω(err).ShouldNot(MatchError("another error")) Ω(fmtErr).Should(MatchError("an error")) Ω(customErr).Should(MatchError("an error")) }) Context("when passed a matcher", func() { It("should pass if the matcher passes against the error string", func() { err := errors.New("error 123 abc") Ω(err).Should(MatchError(MatchRegexp(`\d{3}`))) }) It("should fail if the matcher fails against the error string", func() { err := errors.New("no digits") Ω(err).ShouldNot(MatchError(MatchRegexp(`\d`))) }) }) It("should fail when passed anything else", func() { actualErr := errors.New("an error") _, err := (&MatchErrorMatcher{ Expected: []byte("an error"), }).Match(actualErr) Ω(err).Should(HaveOccurred()) _, err = (&MatchErrorMatcher{ Expected: 3, }).Match(actualErr) Ω(err).Should(HaveOccurred()) }) }) Context("when passed nil", func() { It("should fail", func() { _, err := (&MatchErrorMatcher{ Expected: "an error", }).Match(nil) Ω(err).Should(HaveOccurred()) }) }) Context("when passed a non-error", func() { It("should fail", func() { _, err := (&MatchErrorMatcher{ Expected: "an error", }).Match("an error") Ω(err).Should(HaveOccurred()) _, err = (&MatchErrorMatcher{ Expected: "an error", }).Match(3) Ω(err).Should(HaveOccurred()) }) }) })
wyue-redhat/origin
Godeps/_workspace/src/github.com/onsi/gomega/matchers/match_error_matcher_test.go
GO
apache-2.0
2,311
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE // LUA mode. Ported to CodeMirror 2 from Franciszek Wawrzak's // CodeMirror 1 mode. // highlights keywords, strings, comments (no leveling supported! ("[==[")), tokens, basic indenting (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("lua", function(config, parserConfig) { var indentUnit = config.indentUnit; function prefixRE(words) { return new RegExp("^(?:" + words.join("|") + ")", "i"); } function wordRE(words) { return new RegExp("^(?:" + words.join("|") + ")$", "i"); } var specials = wordRE(parserConfig.specials || []); // long list of standard functions from lua manual var builtins = wordRE([ "_G","_VERSION","assert","collectgarbage","dofile","error","getfenv","getmetatable","ipairs","load", "loadfile","loadstring","module","next","pairs","pcall","print","rawequal","rawget","rawset","require", "select","setfenv","setmetatable","tonumber","tostring","type","unpack","xpcall", "coroutine.create","coroutine.resume","coroutine.running","coroutine.status","coroutine.wrap","coroutine.yield", "debug.debug","debug.getfenv","debug.gethook","debug.getinfo","debug.getlocal","debug.getmetatable", "debug.getregistry","debug.getupvalue","debug.setfenv","debug.sethook","debug.setlocal","debug.setmetatable", "debug.setupvalue","debug.traceback", "close","flush","lines","read","seek","setvbuf","write", "io.close","io.flush","io.input","io.lines","io.open","io.output","io.popen","io.read","io.stderr","io.stdin", "io.stdout","io.tmpfile","io.type","io.write", "math.abs","math.acos","math.asin","math.atan","math.atan2","math.ceil","math.cos","math.cosh","math.deg", "math.exp","math.floor","math.fmod","math.frexp","math.huge","math.ldexp","math.log","math.log10","math.max", "math.min","math.modf","math.pi","math.pow","math.rad","math.random","math.randomseed","math.sin","math.sinh", "math.sqrt","math.tan","math.tanh", "os.clock","os.date","os.difftime","os.execute","os.exit","os.getenv","os.remove","os.rename","os.setlocale", "os.time","os.tmpname", "package.cpath","package.loaded","package.loaders","package.loadlib","package.path","package.preload", "package.seeall", "string.byte","string.char","string.dump","string.find","string.format","string.gmatch","string.gsub", "string.len","string.lower","string.match","string.rep","string.reverse","string.sub","string.upper", "table.concat","table.insert","table.maxn","table.remove","table.sort" ]); var keywords = wordRE(["and","break","elseif","false","nil","not","or","return", "true","function", "end", "if", "then", "else", "do", "while", "repeat", "until", "for", "in", "local" ]); var indentTokens = wordRE(["function", "if","repeat","do", "\\(", "{"]); var dedentTokens = wordRE(["end", "until", "\\)", "}"]); var dedentPartial = prefixRE(["end", "until", "\\)", "}", "else", "elseif"]); function readBracket(stream) { var level = 0; while (stream.eat("=")) ++level; stream.eat("["); return level; } function normal(stream, state) { var ch = stream.next(); if (ch == "-" && stream.eat("-")) { if (stream.eat("[") && stream.eat("[")) return (state.cur = bracketed(readBracket(stream), "comment"))(stream, state); stream.skipToEnd(); return "comment"; } if (ch == "\"" || ch == "'") return (state.cur = string(ch))(stream, state); if (ch == "[" && /[\[=]/.test(stream.peek())) return (state.cur = bracketed(readBracket(stream), "string"))(stream, state); if (/\d/.test(ch)) { stream.eatWhile(/[\w.%]/); return "number"; } if (/[\w_]/.test(ch)) { stream.eatWhile(/[\w\\\-_.]/); return "variable"; } return null; } function bracketed(level, style) { return function(stream, state) { var curlev = null, ch; while ((ch = stream.next()) != null) { if (curlev == null) {if (ch == "]") curlev = 0;} else if (ch == "=") ++curlev; else if (ch == "]" && curlev == level) { state.cur = normal; break; } else curlev = null; } return style; }; } function string(quote) { return function(stream, state) { var escaped = false, ch; while ((ch = stream.next()) != null) { if (ch == quote && !escaped) break; escaped = !escaped && ch == "\\"; } if (!escaped) state.cur = normal; return "string"; }; } return { startState: function(basecol) { return {basecol: basecol || 0, indentDepth: 0, cur: normal}; }, token: function(stream, state) { if (stream.eatSpace()) return null; var style = state.cur(stream, state); var word = stream.current(); if (style == "variable") { if (keywords.test(word)) style = "keyword"; else if (builtins.test(word)) style = "builtin"; else if (specials.test(word)) style = "variable-2"; } if ((style != "comment") && (style != "string")){ if (indentTokens.test(word)) ++state.indentDepth; else if (dedentTokens.test(word)) --state.indentDepth; } return style; }, indent: function(state, textAfter) { var closing = dedentPartial.test(textAfter); return state.basecol + indentUnit * (state.indentDepth - (closing ? 1 : 0)); }, lineComment: "--", blockCommentStart: "--[[", blockCommentEnd: "]]" }; }); CodeMirror.defineMIME("text/x-lua", "lua"); });
nkhuyu/spark-notebook
public/ipython/components/codemirror/mode/lua/lua.js
JavaScript
apache-2.0
5,950
package storage import ( "bytes" "crypto/rand" "io" mrand "math/rand" "os" "testing" "github.com/docker/distribution/context" "github.com/docker/distribution/digest" "github.com/docker/distribution/registry/storage/driver/inmemory" ) func TestSimpleRead(t *testing.T) { ctx := context.Background() content := make([]byte, 1<<20) n, err := rand.Read(content) if err != nil { t.Fatalf("unexpected error building random data: %v", err) } if n != len(content) { t.Fatalf("random read didn't fill buffer") } dgst, err := digest.FromReader(bytes.NewReader(content)) if err != nil { t.Fatalf("unexpected error digesting random content: %v", err) } driver := inmemory.New() path := "/random" if err := driver.PutContent(ctx, path, content); err != nil { t.Fatalf("error putting patterned content: %v", err) } fr, err := newFileReader(ctx, driver, path, int64(len(content))) if err != nil { t.Fatalf("error allocating file reader: %v", err) } verifier, err := digest.NewDigestVerifier(dgst) if err != nil { t.Fatalf("error getting digest verifier: %s", err) } io.Copy(verifier, fr) if !verifier.Verified() { t.Fatalf("unable to verify read data") } } func TestFileReaderSeek(t *testing.T) { driver := inmemory.New() pattern := "01234567890ab" // prime length block repititions := 1024 path := "/patterned" content := bytes.Repeat([]byte(pattern), repititions) ctx := context.Background() if err := driver.PutContent(ctx, path, content); err != nil { t.Fatalf("error putting patterned content: %v", err) } fr, err := newFileReader(ctx, driver, path, int64(len(content))) if err != nil { t.Fatalf("unexpected error creating file reader: %v", err) } // Seek all over the place, in blocks of pattern size and make sure we get // the right data. for _, repitition := range mrand.Perm(repititions - 1) { targetOffset := int64(len(pattern) * repitition) // Seek to a multiple of pattern size and read pattern size bytes offset, err := fr.Seek(targetOffset, os.SEEK_SET) if err != nil { t.Fatalf("unexpected error seeking: %v", err) } if offset != targetOffset { t.Fatalf("did not seek to correct offset: %d != %d", offset, targetOffset) } p := make([]byte, len(pattern)) n, err := fr.Read(p) if err != nil { t.Fatalf("error reading pattern: %v", err) } if n != len(pattern) { t.Fatalf("incorrect read length: %d != %d", n, len(pattern)) } if string(p) != pattern { t.Fatalf("incorrect read content: %q != %q", p, pattern) } // Check offset current, err := fr.Seek(0, os.SEEK_CUR) if err != nil { t.Fatalf("error checking current offset: %v", err) } if current != targetOffset+int64(len(pattern)) { t.Fatalf("unexpected offset after read: %v", err) } } start, err := fr.Seek(0, os.SEEK_SET) if err != nil { t.Fatalf("error seeking to start: %v", err) } if start != 0 { t.Fatalf("expected to seek to start: %v != 0", start) } end, err := fr.Seek(0, os.SEEK_END) if err != nil { t.Fatalf("error checking current offset: %v", err) } if end != int64(len(content)) { t.Fatalf("expected to seek to end: %v != %v", end, len(content)) } // 4. Seek before start, ensure error. // seek before start before, err := fr.Seek(-1, os.SEEK_SET) if err == nil { t.Fatalf("error expected, returned offset=%v", before) } // 5. Seek after end, after, err := fr.Seek(1, os.SEEK_END) if err != nil { t.Fatalf("unexpected error expected, returned offset=%v", after) } p := make([]byte, 16) n, err := fr.Read(p) if n != 0 { t.Fatalf("bytes reads %d != %d", n, 0) } if err != io.EOF { t.Fatalf("expected io.EOF, got %v", err) } } // TestFileReaderNonExistentFile ensures the reader behaves as expected with a // missing or zero-length remote file. While the file may not exist, the // reader should not error out on creation and should return 0-bytes from the // read method, with an io.EOF error. func TestFileReaderNonExistentFile(t *testing.T) { driver := inmemory.New() fr, err := newFileReader(context.Background(), driver, "/doesnotexist", 10) if err != nil { t.Fatalf("unexpected error initializing reader: %v", err) } var buf [1024]byte n, err := fr.Read(buf[:]) if n != 0 { t.Fatalf("non-zero byte read reported: %d != 0", n) } if err != io.EOF { t.Fatalf("read on missing file should return io.EOF, got %v", err) } } // TestLayerReadErrors covers the various error return type for different // conditions that can arise when reading a layer. func TestFileReaderErrors(t *testing.T) { // TODO(stevvooe): We need to cover error return types, driven by the // errors returned via the HTTP API. For now, here is a incomplete list: // // 1. Layer Not Found: returned when layer is not found or access is // denied. // 2. Layer Unavailable: returned when link references are unresolved, // but layer is known to the registry. // 3. Layer Invalid: This may more split into more errors, but should be // returned when name or tarsum does not reference a valid error. We // may also need something to communication layer verification errors // for the inline tarsum check. // 4. Timeout: timeouts to backend. Need to better understand these // failure cases and how the storage driver propagates these errors // up the stack. }
raffaelespazzoli/origin
cmd/cluster-capacity/go/src/github.com/kubernetes-incubator/cluster-capacity/vendor/github.com/docker/distribution/registry/storage/filereader_test.go
GO
apache-2.0
5,357
plupload.addI18n({"Stop Upload":"Stop Upload","Upload URL might be wrong or doesn't exist.":"Upload URL might be wrong or doesn't exist.","tb":"","Size":"Veličina","Close":"Close","Init error.":"Init error.","Add files to the upload queue and click the start button.":"Dodajte fajlove u listu i kliknite na dugme Start.","Filename":"Naziv fajla","Image format either wrong or not supported.":"Image format either wrong or not supported.","Status":"Status","HTTP Error.":"HTTP Error.","Start Upload":"Počni upload","mb":"","kb":"","Duplicate file error.":"","File size error.":"File size error.","N/A":"N/A","gb":"","Error: Invalid file extension:":"Error: Invalid file extension:","Select files":"Izaberite fajlove","%s already present in the queue.":"","File: %s":"File: %s","b":"","Uploaded %d/%d files":"Snimljeno %d/%d fajlova","Upload element accepts only %d file(s) at a time. Extra files were stripped.":"Upload element accepts only %d file(s) at a time. Extra files were stripped.","%d files queued":"%d files queued","File: %s, size: %d, max file size: %d":"","Drag files here.":"Prevucite fajlove ovde.","Runtime ran out of available memory.":"Runtime ran out of available memory.","File count error.":"File count error.","File extension error.":"File extension error.","Error: File too large:":"Error: File too large:","Add Files":"Dodaj fajlove"});
huanxu20011572/evm
evm/src/main/webapp/js/plupload-2.0.0/js/i18n/sr.js
JavaScript
apache-2.0
1,362
/* * /MathJax/jax/output/SVG/fonts/STIX-Web/Monospace/Regular/Main.js * * Copyright (c) 2009-2015 The MathJax Consortium * * 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. */ MathJax.OutputJax.SVG.FONTDATA.FONTS.STIXMathJax_Monospace={directory:"Monospace/Regular",family:"STIXMathJax_Monospace",id:"STIXWEBMONOSPACE",32:[0,0,525,0,0,""],160:[0,0,525,0,0,""],120432:[673,0,525,26,496,"496 40v-16c0 -13 -11 -24 -24 -24h-127c-14 0 -24 11 -24 24v16c0 13 10 24 24 24h31l-26 117h-178l-26 -117h32c13 0 24 -11 24 -24v-16c0 -13 -11 -24 -24 -24h-128c-13 0 -24 11 -24 24v16c0 13 11 24 24 24h36l130 585c3 14 16 24 30 24h30c14 0 27 -10 30 -24 l130 -585h36c13 0 24 -11 24 -24zM186 245h150c-37 168 -74 338 -74 344h-1c0 -6 -38 -176 -75 -344"],120433:[662,0,525,29,480,"53 662h240c92 0 167 -75 167 -168c0 -68 -45 -126 -109 -148c74 -17 129 -84 129 -164c0 -101 -74 -182 -166 -182h-261c-13 0 -24 11 -24 24v16c0 13 11 24 24 24h43v534h-43c-13 0 -24 10 -24 24v16c0 13 11 24 24 24zM155 376h117c72 0 130 52 130 118 c0 57 -49 104 -109 104h-138v-222zM155 64h138c71 0 129 53 129 118c0 71 -53 130 -119 130h-148v-248"],120434:[672,11,525,40,482,"448 232h10c13 0 24 -11 24 -24c0 -115 -84 -219 -202 -219c-140 0 -240 162 -240 341c0 180 100 342 240 342c57 0 103 -26 137 -65l15 48c3 10 12 17 23 17h3c13 0 24 -11 24 -24v-206c0 -13 -11 -24 -24 -24h-10c-13 0 -23 10 -24 22c-8 94 -60 168 -131 168 c-101 0 -195 -117 -195 -278c0 -160 95 -277 196 -277c73 0 130 69 130 155c0 13 11 24 24 24"],120435:[662,0,525,25,483,"49 662h222c117 0 212 -151 212 -337c0 -180 -95 -325 -212 -325h-222c-13 0 -24 11 -24 24v16c0 13 11 24 24 24h38v534h-38c-13 0 -24 10 -24 24v16c0 13 11 24 24 24zM146 64h110c93 0 169 117 169 261c0 151 -76 273 -169 273h-110v-534"],120436:[662,0,525,31,500,"500 150v-126c0 -13 -11 -24 -24 -24h-421c-13 0 -24 11 -24 24v16c0 13 11 24 24 24h46v534h-46c-13 0 -24 10 -24 24v16c0 13 11 24 24 24h400c13 0 24 -11 24 -24v-111c0 -13 -11 -24 -24 -24h-10c-13 0 -24 11 -24 24v71h-261v-223h141v32c0 13 11 24 24 24h10 c14 0 25 -11 25 -24v-129c0 -13 -11 -24 -25 -24h-10c-13 0 -24 11 -24 24v32h-141v-246h282v86c0 13 11 24 24 24h10c13 0 24 -11 24 -24"],120437:[662,0,525,34,488,"488 638v-111c0 -13 -11 -24 -24 -24h-10c-13 0 -24 11 -24 24v71h-264v-235h145v32c0 13 11 24 24 24h11c13 0 24 -11 24 -24v-129c0 -13 -11 -24 -24 -24h-11c-13 0 -24 11 -24 24v32h-145v-234h68c13 0 24 -11 24 -24v-16c0 -13 -11 -24 -24 -24h-176 c-13 0 -24 11 -24 24v16c0 13 11 24 24 24h49v534h-49c-13 0 -24 10 -24 24v16c0 13 11 24 24 24h406c13 0 24 -11 24 -24"],120438:[672,11,525,37,495,"495 282v-16c0 -13 -11 -24 -24 -24h-23v-218c0 -13 -11 -24 -24 -24h-10c-13 0 -24 11 -24 24v34c-30 -41 -72 -69 -130 -69c-132 0 -223 164 -223 341c0 178 91 342 223 342c53 0 94 -24 124 -60l14 43c3 10 12 17 23 17h3c13 0 24 -11 24 -24v-206 c0 -13 -11 -24 -24 -24h-10c-13 0 -23 10 -24 22c-8 95 -52 168 -118 168c-89 0 -177 -115 -177 -278s87 -277 174 -277c73 0 112 81 119 189h-58c-13 0 -24 11 -24 24v16c0 14 11 24 24 24h141c13 0 24 -10 24 -24"],120439:[662,0,525,26,496,"496 40v-16c0 -13 -11 -24 -24 -24h-140c-14 0 -24 11 -24 24v16c0 13 10 24 24 24h41v248h-223v-248h41c13 0 24 -11 24 -24v-16c0 -13 -11 -24 -24 -24h-141c-13 0 -24 11 -24 24v16c0 13 11 24 24 24h41v534h-41c-13 0 -24 10 -24 24v16c0 13 11 24 24 24h141 c13 0 24 -11 24 -24v-16c0 -14 -11 -24 -24 -24h-41v-222h223v222h-41c-14 0 -24 10 -24 24v16c0 13 10 24 24 24h140c13 0 24 -11 24 -24v-16c0 -14 -11 -24 -24 -24h-41v-534h41c13 0 24 -11 24 -24"],120440:[662,0,525,84,438,"438 40v-16c0 -13 -11 -24 -24 -24h-306c-13 0 -24 11 -24 24v16c0 13 11 24 24 24h123l1 534h-124c-13 0 -24 10 -24 24v16c0 13 11 24 24 24h306c13 0 24 -11 24 -24v-16c0 -14 -11 -24 -24 -24h-123l-1 -534h124c13 0 24 -11 24 -24"],120441:[662,11,525,85,476,"476 638v-16c0 -14 -10 -24 -24 -24h-46v-459c0 -85 -74 -150 -160 -150c-72 0 -161 37 -161 121c0 25 20 37 38 37c17 0 37 -12 37 -37c0 -10 -3 -17 -8 -23c14 -20 47 -34 94 -34c59 0 102 42 102 86v459h-99c-13 0 -24 10 -24 24v16c0 13 11 24 24 24h203 c14 0 24 -11 24 -24"],120442:[662,0,525,30,494,"494 40v-16c0 -13 -11 -24 -24 -24h-101c-13 0 -24 11 -24 24v16c0 13 11 24 24 24h15l-145 283l-98 -135v-148h38c13 0 24 -11 24 -24v-16c0 -13 -11 -24 -24 -24h-125c-13 0 -24 11 -24 24v16c0 13 11 24 24 24h38v534h-38c-13 0 -24 10 -24 24v16c0 13 11 24 24 24 h125c13 0 24 -11 24 -24v-16c0 -14 -11 -24 -24 -24h-38v-304l222 304h-16c-14 0 -24 10 -24 24v16c0 13 10 24 24 24h112c14 0 25 -11 25 -24v-16c0 -14 -11 -24 -25 -24h-37l-151 -207l167 -327h32c13 0 24 -11 24 -24"],120443:[662,0,525,37,487,"487 150v-126c0 -13 -11 -24 -24 -24h-402c-14 0 -24 11 -24 24v16c0 13 10 24 24 24h53v534h-53c-14 0 -24 10 -24 24v16c0 13 10 24 24 24h183c13 0 24 -11 24 -24v-16c0 -14 -11 -24 -24 -24h-72v-534h257v86c0 13 11 24 24 24h10c13 0 24 -11 24 -24"],120444:[662,0,525,21,501,"501 40v-16c0 -13 -11 -24 -24 -24h-106c-13 0 -24 11 -24 24v16c0 13 11 24 24 24h29v526h-1c0 -8 -69 -230 -106 -346c-4 -14 -17 -24 -32 -24c-14 0 -28 10 -32 24c-37 116 -105 338 -105 346h-1v-526h28c14 0 24 -11 24 -24v-16c0 -13 -10 -24 -24 -24h-105 c-14 0 -25 11 -25 24v16c0 13 11 24 25 24h28v534h-28c-14 0 -25 10 -25 24v16c0 13 11 24 25 24h75c15 0 29 -10 33 -24c37 -116 107 -340 107 -346h1c0 6 69 230 106 346c4 14 18 24 33 24h76c13 0 24 -11 24 -24v-16c0 -14 -11 -24 -24 -24h-29v-534h29 c13 0 24 -11 24 -24"],120445:[662,0,525,31,491,"491 638v-16c0 -14 -11 -24 -24 -24h-41v-574c0 -13 -11 -24 -24 -24h-23c-15 0 -29 10 -34 24l-200 570v-530h41c13 0 24 -11 24 -24v-16c0 -13 -11 -24 -24 -24h-131c-13 0 -24 11 -24 24v16c0 13 11 24 24 24h41v534h-41c-13 0 -24 10 -24 24v16c0 13 11 24 24 24h88 c16 0 29 -10 34 -24l201 -570v530h-41c-14 0 -24 10 -24 24v16c0 13 10 24 24 24h130c13 0 24 -11 24 -24"],120446:[672,11,525,56,466,"466 330c0 -310 -19 -341 -205 -341s-205 31 -205 341c0 311 19 342 205 342s205 -31 205 -342zM408 344c0 240 -13 264 -147 264c-133 0 -146 -24 -146 -264c0 -264 13 -291 146 -291c134 0 147 27 147 291"],120447:[662,0,525,31,479,"55 662h239c102 0 185 -88 185 -197c0 -110 -83 -199 -185 -199h-134v-202h46c13 0 24 -11 24 -24v-16c0 -13 -11 -24 -24 -24h-151c-13 0 -24 11 -24 24v16c0 13 11 24 24 24h46v534h-46c-13 0 -24 10 -24 24v16c0 13 11 24 24 24zM160 330h119c78 0 142 60 142 135 c0 73 -64 133 -142 133h-119v-268"],120448:[672,139,525,56,466,"390 -127l-63 118c-19 -1 -41 -2 -66 -2c-186 0 -205 31 -205 341c0 311 19 342 205 342s205 -31 205 -342c0 -213 -9 -294 -75 -324l63 -121l1 -7c0 -9 -7 -17 -16 -17h-29c-9 0 -16 5 -20 12zM301 179l57 -110c44 26 50 93 50 261c0 252 -13 278 -147 278 c-133 0 -146 -26 -146 -278s13 -277 146 -277l33 1l-57 107l-2 7c0 9 7 17 17 17h39c4 0 8 -3 10 -6"],120449:[662,11,525,26,520,"486 125h10c14 0 24 -11 24 -24c0 -55 -16 -112 -82 -112c-84 0 -91 69 -91 137v82c0 49 -47 90 -106 90h-91v-234h41c13 0 24 -11 24 -24v-16c0 -13 -11 -24 -24 -24h-141c-13 0 -24 11 -24 24v16c0 13 11 24 24 24h41v534h-41c-13 0 -24 10 -24 24v16c0 13 11 24 24 24 h191c105 0 191 -81 191 -181c0 -65 -35 -121 -87 -153c36 -28 60 -71 60 -120v-82c0 -71 12 -73 33 -73c10 0 24 2 24 48c0 13 11 24 24 24zM150 363h84c77 0 140 52 140 118c0 64 -63 117 -140 117h-84v-235"],120450:[672,11,525,52,470,"203 389l128 -33c83 -21 139 -96 139 -181c0 -102 -81 -186 -183 -186c-70 0 -132 20 -175 59l-9 -40c-3 -11 -12 -19 -24 -19h-3c-13 0 -24 11 -24 24v182c0 13 11 24 24 24h10c14 0 24 -11 24 -24c0 -91 68 -142 177 -142c67 0 122 56 122 125c0 58 -38 108 -93 122 l-128 32c-77 19 -136 86 -136 167c0 97 84 173 183 173c64 0 114 -22 149 -59l9 40c3 11 12 19 24 19h3c13 0 24 -11 24 -24v-182c0 -13 -11 -24 -24 -24h-10c-13 0 -23 9 -24 22c-10 91 -63 144 -151 144c-69 0 -121 -52 -121 -112c0 -50 37 -94 89 -107"],120451:[662,0,525,26,496,"496 638v-111c0 -13 -11 -24 -24 -24h-10c-13 0 -24 11 -24 24v71h-148v-534h68c13 0 24 -11 24 -24v-16c0 -13 -11 -24 -24 -24h-194c-13 0 -24 11 -24 24v16c0 13 11 24 24 24h68v534h-148v-71c0 -13 -10 -24 -24 -24h-10c-13 0 -24 11 -24 24v111c0 13 11 24 24 24 h422c13 0 24 -11 24 -24"],120452:[662,11,525,9,514,"514 638v-16c0 -14 -11 -24 -24 -24h-47v-378c0 -121 -76 -231 -182 -231s-182 110 -182 231v378h-46c-13 0 -24 10 -24 24v16c0 13 11 24 24 24h151c13 0 24 -11 24 -24v-16c0 -14 -11 -24 -24 -24h-46v-378c0 -98 60 -167 123 -167s124 69 124 167v378h-47 c-13 0 -24 10 -24 24v16c0 13 11 24 24 24h152c13 0 24 -11 24 -24"],120453:[662,8,525,17,506,"506 638v-16c0 -14 -11 -24 -24 -24h-34l-141 -582c-3 -14 -17 -24 -31 -24h-30c-14 0 -27 10 -30 24l-141 582h-34c-14 0 -24 10 -24 24v16c0 13 10 24 24 24h124c13 0 24 -11 24 -24v-16c0 -14 -11 -24 -24 -24h-31c48 -197 127 -520 127 -526h1c0 6 78 329 126 526 h-31c-13 0 -24 10 -24 24v16c0 13 11 24 24 24h125c13 0 24 -11 24 -24"],120454:[662,8,525,11,512,"512 638v-16c0 -14 -11 -24 -24 -24h-14l-76 -582c-2 -14 -14 -24 -28 -24h-13c-14 0 -27 10 -30 24c-22 103 -65 303 -65 310h-1c0 -7 -43 -207 -66 -310c-3 -14 -15 -24 -30 -24h-13c-14 0 -26 10 -28 24l-75 582h-14c-14 0 -24 10 -24 24v16c0 13 10 24 24 24h103 c13 0 24 -11 24 -24v-16c0 -14 -11 -24 -24 -24h-41c26 -195 66 -504 66 -526h1c0 23 38 200 60 302c3 14 15 24 30 24h15c14 0 27 -10 30 -24c21 -102 60 -279 60 -302h1c0 22 40 331 65 526h-41c-13 0 -24 10 -24 24v16c0 13 11 24 24 24h104c13 0 24 -11 24 -24"],120455:[662,0,525,24,497,"497 40v-16c0 -13 -10 -24 -24 -24h-125c-13 0 -24 11 -24 24v16c0 13 11 24 24 24h19l-111 226l-103 -226h20c13 0 24 -11 24 -24v-16c0 -13 -11 -24 -24 -24h-125c-13 0 -24 11 -24 24v16c0 13 11 24 24 24h42l137 288l-125 246h-43c-13 0 -24 10 -24 24v16 c0 13 11 24 24 24h125c13 0 24 -11 24 -24v-16c0 -14 -11 -24 -24 -24h-18l90 -177l83 177h-20c-13 0 -24 10 -24 24v16c0 13 11 24 24 24h125c14 0 24 -11 24 -24v-16c0 -14 -10 -24 -24 -24h-41l-118 -246l146 -288h42c14 0 24 -11 24 -24"],120456:[662,0,525,15,507,"507 638v-16c0 -14 -11 -24 -24 -24h-41l-152 -334v-200h41c14 0 24 -11 24 -24v-16c0 -13 -10 -24 -24 -24h-140c-13 0 -24 11 -24 24v16c0 13 11 24 24 24h41v200l-152 334h-40c-14 0 -25 10 -25 24v16c0 13 11 24 25 24h124c14 0 25 -11 25 -24v-16 c0 -14 -11 -24 -25 -24h-20c48 -106 117 -256 117 -260h1c0 4 68 154 116 260h-20c-13 0 -24 10 -24 24v16c0 13 11 24 24 24h125c13 0 24 -11 24 -24"],120457:[662,0,525,47,479,"479 153v-129c0 -13 -11 -24 -24 -24h-384c-13 0 -24 11 -24 24v19c0 4 1 9 4 12l345 543h-278v-71c0 -13 -11 -24 -25 -24h-10c-13 0 -24 11 -24 24v111c0 13 11 24 24 24h368c13 0 24 -11 24 -24v-19c0 -4 -1 -9 -3 -12l-345 -543h294v89c0 13 11 24 24 24h10 c13 0 24 -11 24 -24"],120458:[459,6,525,58,516,"516 127v-34c0 -54 -44 -96 -97 -96c-33 0 -54 23 -63 49c-42 -36 -106 -52 -162 -52c-79 0 -136 69 -136 146c0 107 123 157 291 162v15c0 36 -45 78 -117 78c-25 0 -52 0 -72 -3h-1c-1 -24 -21 -36 -37 -36c-18 0 -38 12 -38 37c0 62 79 66 126 66h22 c91 0 175 -58 175 -142v-233c0 -13 10 -24 25 -24c12 0 26 12 26 33v34c0 13 11 24 24 24h10c13 0 24 -11 24 -24zM349 138v110c-165 -5 -232 -53 -232 -108c0 -45 43 -82 101 -82c76 0 131 34 131 80"],120459:[609,6,525,17,481,"160 585v-183c38 35 92 54 146 54c103 0 175 -111 175 -231c0 -122 -81 -231 -190 -231c-54 0 -99 24 -131 62v-32c0 -13 -11 -24 -24 -24h-10c-14 0 -25 11 -25 24v520h-60c-13 0 -24 11 -24 25v16c0 13 11 24 24 24h95c13 0 24 -11 24 -24zM160 310v-141 c12 -64 60 -111 117 -111c78 0 146 72 146 167c0 96 -65 167 -136 167c-63 0 -114 -35 -127 -82"],120460:[459,6,525,78,464,"464 131l-1 -7c-21 -77 -84 -130 -173 -130c-119 0 -212 106 -212 231c0 127 93 234 212 234h26c52 0 137 -5 137 -65c0 -25 -20 -37 -37 -37s-36 11 -37 34l-7 1c-23 3 -54 3 -82 3c-83 0 -154 -74 -154 -170c0 -91 77 -167 174 -167c50 0 83 32 97 79c2 10 12 18 23 18 h10c13 0 24 -11 24 -24"],120461:[609,6,525,41,505,"505 40v-16c0 -13 -10 -24 -24 -24h-94c-14 0 -24 11 -24 24v36c-35 -40 -85 -66 -143 -66c-105 0 -179 110 -179 231c0 122 79 231 187 231c51 0 100 -19 135 -52v140h-61c-13 0 -24 11 -24 25v16c0 13 11 24 24 24h95c13 0 24 -11 24 -24v-521h60c14 0 24 -11 24 -24z M363 170v141c-13 46 -60 81 -118 81c-78 0 -146 -72 -146 -167c0 -96 65 -167 136 -167c62 0 114 48 128 112"],120462:[459,6,525,60,462,"462 131l-1 -7c-23 -79 -97 -130 -178 -130c-124 0 -223 105 -223 233c0 125 91 232 208 232c122 0 194 -74 194 -197c0 -13 -11 -24 -24 -24h-319l-1 -11c0 -91 82 -169 187 -169c46 0 86 33 100 79c3 10 12 18 23 18h10c13 0 24 -11 24 -24zM132 296h269 c-11 64 -57 99 -133 99c-59 0 -112 -40 -136 -99"],120463:[615,0,525,42,437,"189 450v47c0 74 86 118 169 118c18 0 79 -2 79 -52c0 -24 -19 -36 -36 -36c-13 0 -28 8 -33 23h-33c-58 0 -88 -31 -88 -53v-47h144c13 0 24 -11 24 -24v-16c0 -13 -11 -24 -24 -24h-144v-322h117c13 0 24 -11 24 -24v-16c0 -13 -11 -24 -24 -24h-292 c-13 0 -24 11 -24 24v16c0 13 11 24 24 24h117v322h-123c-13 0 -24 11 -24 24v16c0 13 11 24 24 24h123"],120464:[461,228,525,29,508,"196 65h65c143 0 232 -38 232 -145c0 -92 -116 -148 -232 -148c-115 0 -232 56 -232 148c0 56 31 104 77 130c-15 20 -23 45 -23 70c0 24 7 49 22 72c-21 27 -33 62 -33 99c0 90 71 165 160 165c36 0 69 -12 96 -33c32 25 72 38 113 38c15 0 67 -3 67 -47 c0 -22 -18 -34 -33 -34c-10 0 -22 6 -29 17h-5c-26 0 -52 -5 -76 -15c17 -26 27 -57 27 -91c0 -90 -71 -164 -160 -164c-34 0 -65 10 -91 29c-6 -11 -8 -23 -8 -34c0 -26 13 -45 31 -53l18 1c5 0 10 -2 14 -5zM333 291c0 61 -46 108 -101 108s-101 -47 -101 -108 c0 -60 46 -107 101 -107s101 47 101 107zM261 13h-79c-56 0 -99 -43 -99 -93c0 -40 66 -91 178 -91s178 51 178 91c0 57 -39 93 -178 93"],120465:[609,0,525,17,505,"505 40v-16c0 -13 -10 -24 -24 -24h-179c-13 0 -24 11 -24 24v16c0 13 11 24 24 24h61v261c0 44 -20 67 -90 67c-63 0 -113 -48 -113 -106v-222h60c13 0 24 -11 24 -24v-16c0 -13 -11 -24 -24 -24h-179c-13 0 -24 11 -24 24v16c0 13 11 24 24 24h60v480h-60 c-13 0 -24 11 -24 25v16c0 13 11 24 24 24h95c13 0 24 -11 24 -24v-182c33 33 80 53 130 53c87 0 131 -44 131 -131v-261h60c14 0 24 -11 24 -24"],120466:[610,0,525,84,448,"304 569c0 -23 -18 -42 -41 -42c-24 0 -42 19 -42 42c0 22 18 41 42 41c23 0 41 -19 41 -41zM448 40v-16c0 -13 -11 -24 -24 -24h-316c-13 0 -24 11 -24 24v16c0 13 11 24 24 24h137v322h-129c-13 0 -24 11 -24 24v16c0 13 11 24 24 24h163c13 0 24 -11 24 -24v-362h121 c13 0 24 -11 24 -24"],120467:[610,227,525,47,362,"362 569c0 -23 -18 -42 -41 -42c-24 0 -42 19 -42 42c0 22 18 41 42 41c23 0 41 -19 41 -41zM361 426v-476c0 -96 -77 -177 -174 -177h-19c-45 0 -121 4 -121 70c0 24 20 37 37 37s37 -13 37 -37v-2h4c21 -4 50 -4 77 -4c55 0 101 50 101 113v436h-145 c-13 0 -24 11 -24 24v16c0 13 11 24 24 24h179c14 0 24 -11 24 -24"],120468:[609,0,525,24,505,"505 40v-16c0 -13 -10 -24 -24 -24h-142c-13 0 -24 11 -24 24v16c0 13 11 24 24 24h30l-129 179l-78 -70v-109h65c13 0 24 -11 24 -24v-16c0 -13 -11 -24 -24 -24h-178c-14 0 -25 11 -25 24v16c0 13 11 24 25 24h65v480h-65c-14 0 -25 11 -25 25v16c0 13 11 24 25 24h89 c13 0 24 -11 24 -24v-347l164 148h-44c-13 0 -24 11 -24 24v16c0 13 11 24 24 24h178c14 0 24 -11 24 -24v-16c0 -13 -10 -24 -24 -24h-62l-122 -110l153 -212h52c14 0 24 -11 24 -24"],120469:[609,0,525,63,459,"459 40v-16c0 -13 -10 -24 -24 -24h-348c-13 0 -24 11 -24 24v16c0 13 11 24 24 24h145v480h-145c-13 0 -24 11 -24 25v16c0 13 11 24 24 24h179c13 0 24 -11 24 -24v-521h145c14 0 24 -11 24 -24"],120470:[456,0,525,2,520,"520 40v-16c0 -13 -10 -24 -24 -24h-112c-13 0 -24 11 -24 24v16c0 13 11 24 24 24h32v261c0 53 -17 67 -54 67c-42 0 -77 -45 -77 -106v-222h33c13 0 24 -11 24 -24v-16c0 -13 -11 -24 -24 -24h-113c-13 0 -24 11 -24 24v16c0 13 11 24 24 24h32v261c0 53 -17 67 -54 67 c-42 0 -77 -45 -77 -106v-222h33c13 0 24 -11 24 -24v-16c0 -13 -11 -24 -24 -24h-113c-13 0 -24 11 -24 24v16c0 13 11 24 24 24h32v322h-32c-13 0 -24 11 -24 24v16c0 13 11 24 24 24h56c14 0 24 -11 24 -24v-9c23 24 53 39 90 39c41 0 65 -20 77 -53c24 31 58 53 102 53 c67 0 89 -56 89 -131v-261h32c14 0 24 -11 24 -24"],120471:[456,0,525,17,505,"505 40v-16c0 -13 -10 -24 -24 -24h-179c-13 0 -24 11 -24 24v16c0 13 11 24 24 24h61v261c0 44 -20 67 -90 67c-63 0 -113 -48 -113 -106v-222h60c13 0 24 -11 24 -24v-16c0 -13 -11 -24 -24 -24h-179c-13 0 -24 11 -24 24v16c0 13 11 24 24 24h60v322h-60 c-13 0 -24 11 -24 24v16c0 13 11 24 24 24h95c13 0 24 -11 24 -24v-23c33 33 80 53 130 53c87 0 131 -44 131 -131v-261h60c14 0 24 -11 24 -24"],120472:[459,6,525,62,460,"460 225c0 -128 -89 -231 -199 -231s-199 103 -199 231c0 129 89 234 199 234s199 -105 199 -234zM402 234c0 89 -63 161 -141 161s-141 -72 -141 -161c0 -97 63 -176 141 -176s141 79 141 176"],120473:[456,221,525,17,481,"160 426v-24c38 35 92 54 146 54c103 0 175 -111 175 -231c0 -122 -81 -231 -190 -231c-54 0 -99 24 -131 62v-213h60c13 0 24 -10 24 -24v-16c0 -13 -11 -24 -24 -24h-179c-13 0 -24 11 -24 24v16c0 14 11 24 24 24h60v543h-60c-13 0 -24 11 -24 24v16c0 13 11 24 24 24 h95c13 0 24 -11 24 -24zM160 310v-141c12 -64 60 -111 117 -111c78 0 146 72 146 167c0 96 -65 167 -136 167c-63 0 -114 -35 -127 -82"],120474:[456,221,525,45,530,"530 -181v-16c0 -13 -11 -24 -24 -24h-188c-13 0 -24 11 -24 24v16c0 14 11 24 24 24h65v226c-36 -45 -87 -75 -149 -75c-109 0 -189 109 -189 231c0 123 85 231 198 231c55 0 105 -24 140 -62v38c0 13 10 24 24 24h10c13 0 24 -11 24 -24v-589h65c13 0 24 -10 24 -24z M383 189v95c-10 61 -62 108 -125 108c-84 0 -155 -73 -155 -167c0 -95 68 -167 144 -167c68 0 122 56 136 131"],120475:[456,0,525,37,485,"392 456h8c26 0 85 -3 85 -54c0 -23 -19 -35 -35 -35c-13 0 -29 8 -34 24l-24 1c-97 0 -176 -68 -176 -154v-174h127c13 0 24 -11 24 -24v-16c0 -13 -11 -24 -24 -24h-282c-13 0 -24 11 -24 24v16c0 13 11 24 24 24h97v322h-97c-13 0 -24 11 -24 24v16c0 13 11 24 24 24 h131c13 0 24 -11 24 -24v-52c42 51 106 82 176 82"],120476:[459,6,525,72,457,"220 274l92 -16c65 -11 145 -50 145 -130c0 -91 -83 -134 -192 -134c-56 0 -100 18 -133 50l-10 -33c-2 -10 -12 -17 -23 -17h-3c-13 0 -24 11 -24 24v144c0 13 11 24 24 24h10c12 0 21 -8 24 -19c17 -72 62 -109 135 -109c98 0 134 35 134 76c0 36 -38 63 -97 73l-90 16 c-57 10 -140 39 -140 116c0 84 86 120 193 120c41 0 79 -10 108 -29l5 13c3 9 12 16 23 16h3c13 0 24 -11 24 -24v-115c0 -13 -11 -24 -24 -24h-10c-14 0 -25 11 -25 24c0 48 -36 75 -107 75c-100 0 -132 -32 -132 -62c0 -29 33 -49 90 -59"],120477:[580,6,525,25,448,"448 173v-42c0 -86 -84 -137 -164 -137s-126 54 -126 137v255h-109c-13 0 -24 11 -24 24v16c0 13 11 24 24 24h109v105c0 14 10 25 24 25h10c13 0 24 -11 24 -25v-105h185c13 0 24 -11 24 -24v-16c0 -13 -11 -24 -24 -24h-185v-255c0 -45 27 -73 87 -73c49 0 87 34 87 73 v42c0 13 11 24 24 24h10c13 0 24 -11 24 -24"],120478:[450,6,525,17,505,"505 40v-16c0 -13 -10 -24 -24 -24h-94c-14 0 -24 11 -24 24v26c-33 -34 -79 -56 -131 -56c-88 0 -131 47 -131 137v255h-60c-13 0 -24 11 -24 24v16c0 13 11 24 24 24h95c13 0 24 -11 24 -24v-295c0 -50 21 -73 88 -73c63 0 115 52 115 117v211h-61c-13 0 -24 11 -24 24 v16c0 13 11 24 24 24h95c13 0 24 -11 24 -24v-362h60c14 0 24 -11 24 -24"],120479:[450,4,525,22,500,"500 426v-16c0 -13 -10 -24 -24 -24h-48l-122 -366c-5 -14 -18 -24 -33 -24h-24c-15 0 -28 10 -33 24l-122 366h-48c-14 0 -24 11 -24 24v16c0 13 10 24 24 24h141c13 0 24 -11 24 -24v-16c0 -13 -11 -24 -24 -24h-42l116 -349l116 349h-41c-14 0 -25 11 -25 24v16 c0 13 11 24 25 24h140c14 0 24 -11 24 -24"],120480:[450,4,525,15,508,"508 426v-16c0 -13 -11 -24 -24 -24h-28l-64 -366c-2 -14 -15 -24 -29 -24h-19c-14 0 -28 10 -32 24c-17 59 -43 150 -43 178h-1c0 -28 -26 -119 -43 -178c-4 -14 -18 -24 -32 -24h-34c-14 0 -26 10 -28 24l-64 366h-28c-14 0 -24 11 -24 24v16c0 13 10 24 24 24h143 c13 0 24 -11 24 -24v-16c0 -13 -11 -24 -24 -24h-66l57 -326l53 186c4 14 18 24 32 24h21c14 0 28 -10 32 -24c17 -58 44 -152 44 -174h1c0 20 30 193 51 314h-67c-13 0 -24 11 -24 24v16c0 13 11 24 24 24h144c13 0 24 -11 24 -24"],120481:[450,0,525,23,498,"498 40v-16c0 -13 -11 -24 -24 -24h-141c-13 0 -24 11 -24 24v16c0 13 11 24 24 24h22l-97 135l-93 -135h23c13 0 24 -11 24 -24v-16c0 -13 -11 -24 -24 -24h-141c-13 0 -24 11 -24 24v16c0 13 11 24 24 24h62l126 168l-120 154h-62c-13 0 -24 11 -24 24v16 c0 13 11 24 24 24h141c13 0 24 -11 24 -24v-16c0 -13 -11 -24 -24 -24h-20l84 -113l83 113h-22c-13 0 -24 11 -24 24v16c0 13 11 24 24 24h141c13 0 24 -11 24 -24v-16c0 -13 -11 -24 -24 -24h-62l-116 -154l130 -168h62c13 0 24 -11 24 -24"],120482:[450,227,525,24,501,"501 426v-16c0 -13 -10 -24 -24 -24h-48l-156 -464c-25 -76 -72 -149 -148 -149c-44 0 -82 32 -82 75c0 24 18 36 36 36s36 -12 36 -36l-1 -10l11 -1c47 0 82 39 97 85l26 78l-149 386h-50c-14 0 -25 11 -25 24v16c0 13 11 24 25 24h140c14 0 24 -11 24 -24v-16 c0 -13 -10 -24 -24 -24h-39l122 -315l106 315h-42c-13 0 -24 11 -24 24v16c0 13 11 24 24 24h141c14 0 24 -11 24 -24"],120483:[450,0,525,32,473,"473 119v-95c0 -13 -11 -24 -24 -24h-393c-13 0 -24 11 -24 24v19c0 6 3 13 8 17l332 326h-265v-43c0 -14 -10 -25 -24 -25h-10c-13 0 -24 11 -24 25v83c0 13 11 24 24 24h373c13 0 24 -11 24 -24v-19c0 -6 -3 -13 -7 -17l-333 -326h285v55c0 13 11 24 24 24h10 c13 0 24 -11 24 -24"],120822:[681,11,525,55,467,"467 335c0 -191 -92 -346 -206 -346s-206 155 -206 346s92 346 206 346s206 -155 206 -346zM409 348c0 149 -66 269 -148 269c-81 0 -147 -120 -147 -269c0 -163 66 -295 147 -295c82 0 148 132 148 295"],120823:[681,0,525,110,435,"435 40v-16c0 -13 -11 -24 -24 -24h-271c-14 0 -24 11 -24 24v16c0 13 10 24 24 24h106v473c-28 -32 -65 -54 -112 -54c-14 0 -24 11 -24 24v16c0 13 10 24 24 24c54 0 97 50 121 118c3 9 12 16 23 16h2c14 0 24 -11 24 -24v-593h107c13 0 24 -11 24 -24"],120824:[681,0,525,52,470,"470 87v-63c0 -13 -11 -24 -24 -24h-370c-13 0 -24 11 -24 24v16c0 7 3 14 8 18l190 171c85 77 162 145 162 241c0 84 -70 147 -180 147c-58 0 -107 -45 -119 -104c8 -7 14 -16 14 -29c0 -25 -21 -37 -38 -37s-37 12 -37 37c0 108 86 197 195 197c132 0 223 -91 223 -211 s-94 -205 -174 -277l-143 -129h259v23c0 14 11 24 24 24h10c13 0 24 -10 24 -24"],120825:[681,11,525,43,479,"196 394l73 5c69 5 123 62 123 131c0 42 -49 87 -123 87c-66 0 -115 -20 -132 -52c6 -6 10 -14 10 -25c0 -25 -20 -38 -38 -38c-17 0 -37 13 -37 38c0 100 109 141 197 141c95 0 181 -63 181 -151c0 -71 -38 -135 -95 -169c72 -29 124 -92 124 -170 c0 -112 -95 -202 -210 -202c-108 0 -226 60 -226 175c0 24 20 37 37 37s38 -13 38 -37c0 -12 -5 -21 -12 -27c17 -50 82 -84 163 -84c86 0 152 64 152 138c0 75 -66 138 -152 138h-71c-13 0 -24 11 -24 25v16c0 12 10 23 22 24"],120826:[682,0,525,29,493,"493 228v-16c0 -13 -11 -24 -24 -24h-96v-124h77c13 0 24 -11 24 -24v-16c0 -13 -11 -24 -24 -24h-203c-13 0 -24 11 -24 24v16c0 13 11 24 24 24h77v124h-271c-13 0 -24 11 -24 24v34c0 4 1 8 4 12l238 412c4 7 12 12 21 12h57c13 0 24 -11 24 -24v-406h96 c13 0 24 -11 24 -24zM324 252v394l-228 -394h228"],120827:[670,11,525,52,470,"151 606v-219c36 25 80 38 130 38c108 0 189 -102 189 -218c0 -121 -99 -218 -221 -218c-98 0 -197 65 -197 169c0 24 20 37 37 37s38 -13 38 -37c0 -12 -5 -21 -12 -28c16 -44 69 -77 134 -77c91 0 163 70 163 154c0 88 -62 154 -131 154c-60 0 -104 -19 -131 -59 c-5 -7 -12 -11 -20 -11h-16c-13 0 -24 11 -24 24c0 5 1 9 3 12v319c0 13 11 24 24 24h294c13 0 24 -11 24 -24v-16c0 -14 -11 -24 -24 -24h-260"],120828:[681,11,525,58,464,"464 213c0 -121 -88 -224 -203 -224c-137 0 -203 143 -203 346c0 184 111 346 261 346c66 0 134 -27 134 -104c0 -25 -20 -38 -37 -38s-37 13 -37 38c0 9 3 17 7 22c-10 11 -31 18 -67 18c-100 0 -192 -107 -202 -256c38 47 98 77 164 77c106 0 183 -106 183 -225z M124 240l2 -24c21 -112 72 -163 135 -163c78 0 145 70 145 160c0 92 -65 161 -139 161c-80 0 -143 -62 -143 -134"],120829:[686,11,525,43,479,"479 646v-16c0 -7 -2 -13 -7 -17c-154 -160 -240 -373 -240 -595c0 -19 -16 -29 -29 -29s-29 10 -29 29c0 217 79 426 221 588h-294v-23c0 -14 -10 -25 -24 -25h-10c-13 0 -24 11 -24 25v79c0 13 11 24 24 24h10c11 0 20 -7 23 -16h355c13 0 24 -11 24 -24"],120830:[681,11,525,43,479,"479 191c0 -111 -97 -202 -218 -202c-120 0 -218 91 -218 202c0 79 60 145 143 171c-75 23 -128 78 -128 143c0 97 91 176 203 176s203 -79 203 -176c0 -65 -53 -120 -128 -143c84 -26 143 -92 143 -171zM406 505c0 62 -65 112 -145 112s-144 -50 -144 -112 c0 -61 64 -111 144 -111s145 50 145 111zM421 191c0 77 -72 139 -160 139s-160 -62 -160 -139c0 -76 72 -138 160 -138s160 62 160 138"],120831:[681,11,525,58,464,"464 335c0 -182 -103 -346 -246 -346c-68 0 -149 20 -149 104c0 25 20 38 37 38c18 0 38 -13 38 -38c0 -9 -3 -16 -8 -22c12 -12 37 -18 82 -18c91 0 178 105 187 256c-38 -47 -98 -77 -164 -77c-106 0 -183 106 -183 225c0 122 92 224 209 224c134 0 197 -143 197 -346z M399 430l-2 24c-20 112 -70 163 -130 163c-82 0 -150 -71 -150 -160c0 -92 64 -161 138 -161c81 0 144 62 144 134"]};MathJax.Ajax.loadComplete(MathJax.OutputJax.SVG.fontDir+"/Monospace/Regular/Main.js");
nvp2211/MathJax
jax/output/SVG/fonts/STIX-Web/Monospace/Regular/Main.js
JavaScript
apache-2.0
24,141
require File.expand_path('../helper', __FILE__) require 'rake/thread_history_display' class TestThreadHistoryDisplay < Rake::TestCase def setup super @time = 1_000_000 @stats = [] @display = Rake::ThreadHistoryDisplay.new(@stats) end def test_banner out, _ = capture_io do @display.show end assert_match(/Job History/i, out) end def test_item_queued @stats << event(:item_queued, :item_id => 123) out, _ = capture_io do @display.show end assert_match(/^ *1000000 +A +item_queued +item_id:1$/, out) end def test_item_dequeued @stats << event(:item_dequeued, :item_id => 123) out, _ = capture_io do @display.show end assert_match(/^ *1000000 +A +item_dequeued +item_id:1$/, out) end def test_multiple_items @stats << event(:item_queued, :item_id => 123) @stats << event(:item_queued, :item_id => 124) out, _ = capture_io do @display.show end assert_match(/^ *1000000 +A +item_queued +item_id:1$/, out) assert_match(/^ *1000001 +A +item_queued +item_id:2$/, out) end def test_waiting @stats << event(:waiting, :item_id => 123) out, _ = capture_io do @display.show end assert_match(/^ *1000000 +A +waiting +item_id:1$/, out) end def test_continue @stats << event(:continue, :item_id => 123) out, _ = capture_io do @display.show end assert_match(/^ *1000000 +A +continue +item_id:1$/, out) end def test_thread_deleted @stats << event( :thread_deleted, :deleted_thread => 123_456, :thread_count => 12) out, _ = capture_io do @display.show end assert_match( /^ *1000000 +A +thread_deleted( +deleted_thread:B| +thread_count:12){2}$/, out) end def test_thread_created @stats << event( :thread_created, :new_thread => 123_456, :thread_count => 13) out, _ = capture_io do @display.show end assert_match( /^ *1000000 +A +thread_created( +new_thread:B| +thread_count:13){2}$/, out) end private def event(type, data = {}) result = { :event => type, :time => @time / 1_000_000.0, :data => data, :thread => Thread.current.object_id } @time += 1 result end end
kunalch/gocd
server/webapp/WEB-INF/rails.new/vendor/bundle/jruby/1.9/gems/rake-10.4.2/test/test_thread_history_display.rb
Ruby
apache-2.0
2,301
/** * Module dependencies. */ var benchmark = require('benchmark') , colors = require('colors') , io = require('../') , parser = io.parser , suite = new benchmark.Suite('Decode packet'); suite.add('string', function () { parser.decodePacket('4:::"2"'); }); suite.add('event', function () { parser.decodePacket('5:::{"name":"woot"}'); }); suite.add('event+ack', function () { parser.decodePacket('5:1+::{"name":"tobi"}'); }); suite.add('event+data', function () { parser.decodePacket('5:::{"name":"edwald","args":[{"a": "b"},2,"3"]}'); }); suite.add('heartbeat', function () { parser.decodePacket('2:::'); }); suite.add('error', function () { parser.decodePacket('7:::2+0'); }); var payload = parser.encodePayload([ parser.encodePacket({ type: 'message', data: '5', endpoint: '' }) , parser.encodePacket({ type: 'message', data: '53d', endpoint: '' }) , parser.encodePacket({ type: 'message', data: 'foobar', endpoint: '' }) , parser.encodePacket({ type: 'message', data: 'foobarbaz', endpoint: '' }) , parser.encodePacket({ type: 'message', data: 'foobarbazfoobarbaz', endpoint: '' }) , parser.encodePacket({ type: 'message', data: 'foobarbaz', endpoint: '' }) , parser.encodePacket({ type: 'message', data: 'foobar', endpoint: '' }) ]); suite.add('payload', function () { parser.decodePayload(payload); }); suite.on('cycle', function (bench, details) { console.log('\n' + suite.name.grey, details.name.white.bold); console.log([ details.hz.toFixed(2).cyan + ' ops/sec'.grey , details.count.toString().white + ' times executed'.grey , 'benchmark took '.grey + details.times.elapsed.toString().white + ' sec.'.grey , ].join(', '.grey)); }); if (!module.parent) { suite.run(); } else { module.exports = suite; }
thebillkidy/WebRTC-Stream
server/node_modules/socket.io/benchmarks/decode.bench.js
JavaScript
apache-2.0
1,791
var baseToString = require('./_baseToString'), castSlice = require('./_castSlice'), hasUnicode = require('./_hasUnicode'), isObject = require('./isObject'), isRegExp = require('./isRegExp'), stringSize = require('./_stringSize'), stringToArray = require('./_stringToArray'), toInteger = require('./toInteger'), toString = require('./toString'); /** Used as default options for `_.truncate`. */ var DEFAULT_TRUNC_LENGTH = 30, DEFAULT_TRUNC_OMISSION = '...'; /** Used to match `RegExp` flags from their coerced string values. */ var reFlags = /\w*$/; /** * Truncates `string` if it's longer than the given maximum string length. * The last characters of the truncated string are replaced with the omission * string which defaults to "...". * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to truncate. * @param {Object} [options={}] The options object. * @param {number} [options.length=30] The maximum string length. * @param {string} [options.omission='...'] The string to indicate text is omitted. * @param {RegExp|string} [options.separator] The separator pattern to truncate to. * @returns {string} Returns the truncated string. * @example * * _.truncate('hi-diddly-ho there, neighborino'); * // => 'hi-diddly-ho there, neighbo...' * * _.truncate('hi-diddly-ho there, neighborino', { * 'length': 24, * 'separator': ' ' * }); * // => 'hi-diddly-ho there,...' * * _.truncate('hi-diddly-ho there, neighborino', { * 'length': 24, * 'separator': /,? +/ * }); * // => 'hi-diddly-ho there...' * * _.truncate('hi-diddly-ho there, neighborino', { * 'omission': ' [...]' * }); * // => 'hi-diddly-ho there, neig [...]' */ function truncate(string, options) { var length = DEFAULT_TRUNC_LENGTH, omission = DEFAULT_TRUNC_OMISSION; if (isObject(options)) { var separator = 'separator' in options ? options.separator : separator; length = 'length' in options ? toInteger(options.length) : length; omission = 'omission' in options ? baseToString(options.omission) : omission; } string = toString(string); var strLength = string.length; if (hasUnicode(string)) { var strSymbols = stringToArray(string); strLength = strSymbols.length; } if (length >= strLength) { return string; } var end = length - stringSize(omission); if (end < 1) { return omission; } var result = strSymbols ? castSlice(strSymbols, 0, end).join('') : string.slice(0, end); if (separator === undefined) { return result + omission; } if (strSymbols) { end += (result.length - end); } if (isRegExp(separator)) { if (string.slice(end).search(separator)) { var match, substring = result; if (!separator.global) { separator = RegExp(separator.source, toString(reFlags.exec(separator)) + 'g'); } separator.lastIndex = 0; while ((match = separator.exec(substring))) { var newEnd = match.index; } result = result.slice(0, newEnd === undefined ? end : newEnd); } } else if (string.indexOf(baseToString(separator), end) != end) { var index = result.lastIndexOf(separator); if (index > -1) { result = result.slice(0, index); } } return result + omission; } module.exports = truncate;
mjbradburn/masters_project
node_modules/lodash/truncate.js
JavaScript
apache-2.0
3,357
jasmine.HtmlReporter = function(_doc) { var self = this; var doc = _doc || window.document; var reporterView; var dom = {}; // Jasmine Reporter Public Interface self.logRunningSpecs = false; self.reportRunnerStarting = function(runner) { var specs = runner.specs() || []; if (specs.length == 0) { return; } createReporterDom(runner.env.versionString()); doc.body.appendChild(dom.reporter); reporterView = new jasmine.HtmlReporter.ReporterView(dom); reporterView.addSpecs(specs, self.specFilter); }; self.reportRunnerResults = function(runner) { reporterView && reporterView.complete(); }; self.reportSuiteResults = function(suite) { reporterView.suiteComplete(suite); }; self.reportSpecStarting = function(spec) { if (self.logRunningSpecs) { self.log('>> Jasmine Running ' + spec.suite.description + ' ' + spec.description + '...'); } }; self.reportSpecResults = function(spec) { reporterView.specComplete(spec); }; self.log = function() { var console = jasmine.getGlobal().console; if (console && console.log) { if (console.log.apply) { console.log.apply(console, arguments); } else { console.log(arguments); // ie fix: console.log.apply doesn't exist on ie } } }; self.specFilter = function(spec) { if (!focusedSpecName()) { return true; } return spec.getFullName().indexOf(focusedSpecName()) === 0; }; return self; function focusedSpecName() { var specName; (function memoizeFocusedSpec() { if (specName) { return; } var paramMap = []; var params = doc.location.search.substring(1).split('&'); for (var i = 0; i < params.length; i++) { var p = params[i].split('='); paramMap[decodeURIComponent(p[0])] = decodeURIComponent(p[1]); } specName = paramMap.spec; })(); return specName; } function createReporterDom(version) { dom.reporter = self.createDom('div', { id: 'HTMLReporter', className: 'jasmine_reporter' }, dom.banner = self.createDom('div', { className: 'banner' }, self.createDom('span', { className: 'title' }, "Jasmine "), self.createDom('span', { className: 'version' }, version)), dom.symbolSummary = self.createDom('ul', {className: 'symbolSummary'}), dom.alert = self.createDom('div', {className: 'alert'}), dom.results = self.createDom('div', {className: 'results'}, dom.summary = self.createDom('div', { className: 'summary' }), dom.details = self.createDom('div', { id: 'details' })) ); } }; jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter);
codletech/hitchhikeguard
hitchhikeguard/plugins/org.apache.cordova.core.network-information/test/autotest/html/HtmlReporter.js
JavaScript
apache-2.0
2,716
// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package atom provides integer codes (also known as atoms) for a fixed set of // frequently occurring HTML strings: tag names and attribute keys such as "p" // and "id". // // Sharing an atom's name between all elements with the same tag can result in // fewer string allocations when tokenizing and parsing HTML. Integer // comparisons are also generally faster than string comparisons. // // The value of an atom's particular code is not guaranteed to stay the same // between versions of this package. Neither is any ordering guaranteed: // whether atom.H1 < atom.H2 may also change. The codes are not guaranteed to // be dense. The only guarantees are that e.g. looking up "div" will yield // atom.Div, calling atom.Div.String will return "div", and atom.Div != 0. package atom // Atom is an integer code for a string. The zero value maps to "". type Atom uint32 // String returns the atom's name. func (a Atom) String() string { start := uint32(a >> 8) n := uint32(a & 0xff) if start+n > uint32(len(atomText)) { return "" } return atomText[start : start+n] } func (a Atom) string() string { return atomText[a>>8 : a>>8+a&0xff] } // fnv computes the FNV hash with an arbitrary starting value h. func fnv(h uint32, s []byte) uint32 { for i := range s { h ^= uint32(s[i]) h *= 16777619 } return h } func match(s string, t []byte) bool { for i, c := range t { if s[i] != c { return false } } return true } // Lookup returns the atom whose name is s. It returns zero if there is no // such atom. The lookup is case sensitive. func Lookup(s []byte) Atom { if len(s) == 0 || len(s) > maxAtomLen { return 0 } h := fnv(hash0, s) if a := table[h&uint32(len(table)-1)]; int(a&0xff) == len(s) && match(a.string(), s) { return a } if a := table[(h>>16)&uint32(len(table)-1)]; int(a&0xff) == len(s) && match(a.string(), s) { return a } return 0 } // String returns a string whose contents are equal to s. In that sense, it is // equivalent to string(s) but may be more efficient. func String(s []byte) string { if a := Lookup(s); a != 0 { return a.String() } return string(s) }
cezarsa/docker
vendor/src/code.google.com/p/go.net/html/atom/atom.go
GO
apache-2.0
2,282
// // RACTestScheduler.m // ReactiveCocoa // // Created by Justin Spahr-Summers on 2013-07-06. // Copyright (c) 2013 GitHub, Inc. All rights reserved. // #import "RACTestScheduler.h" #import "RACEXTScope.h" #import "RACCompoundDisposable.h" #import "RACDisposable.h" #import "RACScheduler+Private.h" @interface RACTestSchedulerAction : NSObject // The date at which the action should be executed. // // This absolute time will not actually be honored. This date is only used for // comparison, to determine which block should be run _next_. @property (nonatomic, copy, readonly) NSDate *date; // The scheduled block. @property (nonatomic, copy, readonly) void (^block)(void); // A disposable for this action. // // When disposed, the action should not start executing if it hasn't already. @property (nonatomic, strong, readonly) RACDisposable *disposable; // Initializes a new scheduler action. - (id)initWithDate:(NSDate *)date block:(void (^)(void))block; @end static CFComparisonResult RACCompareScheduledActions(const void *ptr1, const void *ptr2, void *info) { RACTestSchedulerAction *action1 = (__bridge id)ptr1; RACTestSchedulerAction *action2 = (__bridge id)ptr2; return CFDateCompare((__bridge CFDateRef)action1.date, (__bridge CFDateRef)action2.date, NULL); } static const void *RACRetainScheduledAction(CFAllocatorRef allocator, const void *ptr) { return CFRetain(ptr); } static void RACReleaseScheduledAction(CFAllocatorRef allocator, const void *ptr) { CFRelease(ptr); } @interface RACTestScheduler () // All of the RACTestSchedulerActions that have been enqueued and not yet // executed. // // The minimum value in the heap represents the action to execute next. // // This property should only be used while synchronized on self. @property (nonatomic, assign, readonly) CFBinaryHeapRef scheduledActions; // The number of blocks that have been directly enqueued with -schedule: so // far. // // This is used to ensure unique dates when two blocks are enqueued // simultaneously. // // This property should only be used while synchronized on self. @property (nonatomic, assign) NSUInteger numberOfDirectlyScheduledBlocks; @end @implementation RACTestScheduler #pragma mark Lifecycle - (instancetype)init { self = [super initWithName:@"org.reactivecocoa.ReactiveCocoa.RACTestScheduler"]; if (self == nil) return nil; CFBinaryHeapCallBacks callbacks = (CFBinaryHeapCallBacks){ .version = 0, .retain = &RACRetainScheduledAction, .release = &RACReleaseScheduledAction, .copyDescription = &CFCopyDescription, .compare = &RACCompareScheduledActions }; _scheduledActions = CFBinaryHeapCreate(NULL, 0, &callbacks, NULL); return self; } - (void)dealloc { [self stepAll]; if (_scheduledActions != NULL) { CFRelease(_scheduledActions); _scheduledActions = NULL; } } #pragma mark Execution - (void)step { [self step:1]; } - (void)step:(NSUInteger)ticks { @synchronized (self) { for (NSUInteger i = 0; i < ticks; i++) { const void *actionPtr = NULL; if (!CFBinaryHeapGetMinimumIfPresent(self.scheduledActions, &actionPtr)) break; RACTestSchedulerAction *action = (__bridge id)actionPtr; CFBinaryHeapRemoveMinimumValue(self.scheduledActions); if (action.disposable.disposed) continue; RACScheduler *previousScheduler = RACScheduler.currentScheduler; NSThread.currentThread.threadDictionary[RACSchedulerCurrentSchedulerKey] = self; action.block(); if (previousScheduler != nil) { NSThread.currentThread.threadDictionary[RACSchedulerCurrentSchedulerKey] = previousScheduler; } else { [NSThread.currentThread.threadDictionary removeObjectForKey:RACSchedulerCurrentSchedulerKey]; } } } } - (void)stepAll { [self step:NSUIntegerMax]; } #pragma mark RACScheduler - (RACDisposable *)schedule:(void (^)(void))block { NSCParameterAssert(block != nil); @synchronized (self) { NSDate *uniqueDate = [NSDate dateWithTimeIntervalSinceReferenceDate:self.numberOfDirectlyScheduledBlocks]; self.numberOfDirectlyScheduledBlocks++; RACTestSchedulerAction *action = [[RACTestSchedulerAction alloc] initWithDate:uniqueDate block:block]; CFBinaryHeapAddValue(self.scheduledActions, (__bridge void *)action); return action.disposable; } } - (RACDisposable *)after:(NSDate *)date schedule:(void (^)(void))block { NSCParameterAssert(date != nil); NSCParameterAssert(block != nil); @synchronized (self) { RACTestSchedulerAction *action = [[RACTestSchedulerAction alloc] initWithDate:date block:block]; CFBinaryHeapAddValue(self.scheduledActions, (__bridge void *)action); return action.disposable; } } - (RACDisposable *)after:(NSDate *)date repeatingEvery:(NSTimeInterval)interval withLeeway:(NSTimeInterval)leeway schedule:(void (^)(void))block { NSCParameterAssert(date != nil); NSCParameterAssert(block != nil); NSCParameterAssert(interval >= 0); NSCParameterAssert(leeway >= 0); RACCompoundDisposable *compoundDisposable = [RACCompoundDisposable compoundDisposable]; @weakify(self); @synchronized (self) { __block RACDisposable *thisDisposable = nil; void (^reschedulingBlock)(void) = ^{ @strongify(self); [compoundDisposable removeDisposable:thisDisposable]; // Schedule the next interval. RACDisposable *schedulingDisposable = [self after:[date dateByAddingTimeInterval:interval] repeatingEvery:interval withLeeway:leeway schedule:block]; [compoundDisposable addDisposable:schedulingDisposable]; block(); }; RACTestSchedulerAction *action = [[RACTestSchedulerAction alloc] initWithDate:date block:reschedulingBlock]; CFBinaryHeapAddValue(self.scheduledActions, (__bridge void *)action); thisDisposable = action.disposable; [compoundDisposable addDisposable:thisDisposable]; } return compoundDisposable; } @end @implementation RACTestSchedulerAction #pragma mark Lifecycle - (id)initWithDate:(NSDate *)date block:(void (^)(void))block { NSCParameterAssert(date != nil); NSCParameterAssert(block != nil); self = [super init]; if (self == nil) return nil; _date = [date copy]; _block = [block copy]; _disposable = [[RACDisposable alloc] init]; return self; } #pragma mark NSObject - (NSString *)description { return [NSString stringWithFormat:@"<%@: %p>{ date: %@ }", self.class, self, self.date]; } @end
wzy911229/ZYNativeiOS
Pods/ReactiveCocoa/ReactiveCocoa/RACTestScheduler.m
Matlab
apache-2.0
6,295
/* * This file has been commented to support Visual Studio Intellisense. * You should not use this file at runtime inside the browser--it is only * intended to be used only for design-time IntelliSense. Please use the * standard jQuery library for all production use. * * Comment version: 1.4.1a */ /*! * jQuery JavaScript Library v1.4.1 * http://jquery.com/ * * Distributed in whole under the terms of the MIT * * Copyright 2010, John Resig * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * Includes Sizzle.js * http://sizzlejs.com/ * Copyright 2010, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * * Date: Mon Jan 25 19:43:33 2010 -0500 */ (function( window, undefined ) { // Define a local copy of jQuery var jQuery = function( selector, context ) { /// <summary> /// 1: $(expression, context) - This function accepts a string containing a CSS selector which is then used to match a set of elements. /// 2: $(html) - Create DOM elements on-the-fly from the provided String of raw HTML. /// 3: $(elements) - Wrap jQuery functionality around a single or multiple DOM Element(s). /// 4: $(callback) - A shorthand for $(document).ready(). /// 5: $() - As of jQuery 1.4, if you pass no arguments in to the jQuery() method, an empty jQuery set will be returned. /// </summary> /// <param name="selector" type="String"> /// 1: expression - An expression to search with. /// 2: html - A string of HTML to create on the fly. /// 3: elements - DOM element(s) to be encapsulated by a jQuery object. /// 4: callback - The function to execute when the DOM is ready. /// </param> /// <param name="context" type="jQuery"> /// 1: context - A DOM Element, Document or jQuery to use as context. /// </param> /// <returns type="jQuery" /> // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context ); }, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // Use the correct document accordingly with window argument (sandbox) document = window.document, // A central reference to the root jQuery(document) rootjQuery, // A simple way to check for HTML strings or ID strings // (both of which we optimize for) quickExpr = /^[^<]*(<[\w\W]+>)[^>]*$|^#([\w-]+)$/, // Is it a simple selector isSimple = /^.[^:#\[\.,]*$/, // Check if a string has a non-whitespace character in it rnotwhite = /\S/, // Used for trimming whitespace rtrim = /^(\s|\u00A0)+|(\s|\u00A0)+$/g, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/, // Keep a UserAgent string for use with jQuery.browser userAgent = navigator.userAgent, // For matching the engine and version of the browser browserMatch, // Has the ready events already been bound? readyBound = false, // The functions to execute on DOM ready readyList = [], // The ready event handler DOMContentLoaded, // Save a reference to some core methods toString = Object.prototype.toString, hasOwnProperty = Object.prototype.hasOwnProperty, push = Array.prototype.push, slice = Array.prototype.slice, indexOf = Array.prototype.indexOf; jQuery.fn = jQuery.prototype = { init: function( selector, context ) { var match, elem, ret, doc; // Handle $(""), $(null), or $(undefined) if ( !selector ) { return this; } // Handle $(DOMElement) if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; } // Handle HTML strings if ( typeof selector === "string" ) { // Are we dealing with HTML string or an ID? match = quickExpr.exec( selector ); // Verify a match, and that no context was specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { doc = (context ? context.ownerDocument || context : document); // If a single string is passed in and it's a single tag // just do a createElement and skip the rest ret = rsingleTag.exec( selector ); if ( ret ) { if ( jQuery.isPlainObject( context ) ) { selector = [ document.createElement( ret[1] ) ]; jQuery.fn.attr.call( selector, context, true ); } else { selector = [ doc.createElement( ret[1] ) ]; } } else { ret = buildFragment( [ match[1] ], [ doc ] ); selector = (ret.cacheable ? ret.fragment.cloneNode(true) : ret.fragment).childNodes; } // HANDLE: $("#id") } else { elem = document.getElementById( match[2] ); if ( elem ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $("TAG") } else if ( !context && /^\w+$/.test( selector ) ) { this.selector = selector; this.context = document; selector = document.getElementsByTagName( selector ); // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return (context || rootjQuery).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return jQuery( context ).find( selector ); } // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if (selector.selector !== undefined) { this.selector = selector.selector; this.context = selector.context; } return jQuery.isArray( selector ) ? this.setArray( selector ) : jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The current version of jQuery being used jquery: "1.4.1", // The default length of a jQuery object is 0 length: 0, // The number of elements contained in the matched element set size: function() { /// <summary> /// The number of elements currently matched. /// Part of Core /// </summary> /// <returns type="Number" /> return this.length; }, toArray: function() { /// <summary> /// Retrieve all the DOM elements contained in the jQuery set, as an array. /// </summary> /// <returns type="Array" /> return slice.call( this, 0 ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { /// <summary> /// Access a single matched element. num is used to access the /// Nth element matched. /// Part of Core /// </summary> /// <returns type="Element" /> /// <param name="num" type="Number"> /// Access the element in the Nth position. /// </param> return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this.slice(num)[ 0 ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems, name, selector ) { /// <summary> /// Set the jQuery object to an array of elements, while maintaining /// the stack. /// Part of Core /// </summary> /// <returns type="jQuery" /> /// <param name="elems" type="Elements"> /// An array of elements /// </param> // Build a new jQuery matched element set var ret = jQuery( elems || null ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; if ( name === "find" ) { ret.selector = this.selector + (this.selector ? " " : "") + selector; } else if ( name ) { ret.selector = this.selector + "." + name + "(" + selector + ")"; } // Return the newly-formed element set return ret; }, // Force the current matched set of elements to become // the specified array of elements (destroying the stack in the process) // You should use pushStack() in order to do this, but maintain the stack setArray: function( elems ) { /// <summary> /// Set the jQuery object to an array of elements. This operation is /// completely destructive - be sure to use .pushStack() if you wish to maintain /// the jQuery stack. /// Part of Core /// </summary> /// <returns type="jQuery" /> /// <param name="elems" type="Elements"> /// An array of elements /// </param> // Resetting the length to 0, then using the native Array push // is a super-fast way to populate an object with array-like properties this.length = 0; push.apply( this, elems ); return this; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { /// <summary> /// Execute a function within the context of every matched element. /// This means that every time the passed-in function is executed /// (which is once for every element matched) the 'this' keyword /// points to the specific element. /// Additionally, the function, when executed, is passed a single /// argument representing the position of the element in the matched /// set. /// Part of Core /// </summary> /// <returns type="jQuery" /> /// <param name="callback" type="Function"> /// A function to execute /// </param> return jQuery.each( this, callback, args ); }, ready: function( fn ) { /// <summary> /// Binds a function to be executed whenever the DOM is ready to be traversed and manipulated. /// </summary> /// <param name="fn" type="Function">The function to be executed when the DOM is ready.</param> // Attach the listeners jQuery.bindReady(); // If the DOM is already ready if ( jQuery.isReady ) { // Execute the function immediately fn.call( document, jQuery ); // Otherwise, remember the function for later } else if ( readyList ) { // Add the function to the wait list readyList.push( fn ); } return this; }, eq: function( i ) { /// <summary> /// Reduce the set of matched elements to a single element. /// The position of the element in the set of matched elements /// starts at 0 and goes to length - 1. /// Part of Core /// </summary> /// <returns type="jQuery" /> /// <param name="num" type="Number"> /// pos The index of the element that you wish to limit to. /// </param> return i === -1 ? this.slice( i ) : this.slice( i, +i + 1 ); }, first: function() { /// <summary> /// Reduce the set of matched elements to the first in the set. /// </summary> /// <returns type="jQuery" /> return this.eq( 0 ); }, last: function() { /// <summary> /// Reduce the set of matched elements to the final one in the set. /// </summary> /// <returns type="jQuery" /> return this.eq( -1 ); }, slice: function() { /// <summary> /// Selects a subset of the matched elements. Behaves exactly like the built-in Array slice method. /// </summary> /// <param name="start" type="Number" integer="true">Where to start the subset (0-based).</param> /// <param name="end" optional="true" type="Number" integer="true">Where to end the subset (not including the end element itself). /// If omitted, ends at the end of the selection</param> /// <returns type="jQuery">The sliced elements</returns> return this.pushStack( slice.apply( this, arguments ), "slice", slice.call(arguments).join(",") ); }, map: function( callback ) { /// <summary> /// This member is internal. /// </summary> /// <private /> /// <returns type="jQuery" /> return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { /// <summary> /// End the most recent 'destructive' operation, reverting the list of matched elements /// back to its previous state. After an end operation, the list of matched elements will /// revert to the last state of matched elements. /// If there was no destructive operation before, an empty set is returned. /// Part of DOM/Traversing /// </summary> /// <returns type="jQuery" /> return this.prevObject || jQuery(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { /// <summary> /// Extend one object with one or more others, returning the original, /// modified, object. This is a great utility for simple inheritance. /// jQuery.extend(settings, options); /// var settings = jQuery.extend({}, defaults, options); /// Part of JavaScript /// </summary> /// <param name="target" type="Object"> /// The object to extend /// </param> /// <param name="prop1" type="Object"> /// The object that will be merged into the first. /// </param> /// <param name="propN" type="Object" optional="true" parameterArray="true"> /// (optional) More objects to merge into the first /// </param> /// <returns type="Object" /> // copy reference to target object var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options, name, src, copy; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging object literal values or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || jQuery.isArray(copy) ) ) { var clone = src && ( jQuery.isPlainObject(src) || jQuery.isArray(src) ) ? src : jQuery.isArray(copy) ? [] : {}; // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ noConflict: function( deep ) { /// <summary> /// Run this function to give control of the $ variable back /// to whichever library first implemented it. This helps to make /// sure that jQuery doesn't conflict with the $ object /// of other libraries. /// By using this function, you will only be able to access jQuery /// using the 'jQuery' variable. For example, where you used to do /// $(&quot;div p&quot;), you now must do jQuery(&quot;div p&quot;). /// Part of Core /// </summary> /// <returns type="undefined" /> window.$ = _$; if ( deep ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // Handle when the DOM is ready ready: function() { /// <summary> /// This method is internal. /// </summary> /// <private /> // Make sure that the DOM is not already loaded if ( !jQuery.isReady ) { // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready, 13 ); } // Remember that the DOM is ready jQuery.isReady = true; // If there are functions bound, to execute if ( readyList ) { // Execute all of them var fn, i = 0; while ( (fn = readyList[ i++ ]) ) { fn.call( document, jQuery ); } // Reset the list of functions readyList = null; } // Trigger any bound ready events if ( jQuery.fn.triggerHandler ) { jQuery( document ).triggerHandler( "ready" ); } } }, bindReady: function() { if ( readyBound ) { return; } readyBound = true; // Catch cases where $(document).ready() is called after the // browser event has already occurred. if ( document.readyState === "complete" ) { return jQuery.ready(); } // Mozilla, Opera and webkit nightlies currently support this event if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", jQuery.ready, false ); // If IE event model is used } else if ( document.attachEvent ) { // ensure firing before onload, // maybe late but safe also for iframes document.attachEvent("onreadystatechange", DOMContentLoaded); // A fallback to window.onload, that will always work window.attachEvent( "onload", jQuery.ready ); // If IE and not a frame // continually check to see if the document is ready var toplevel = false; try { toplevel = window.frameElement == null; } catch(e) {} if ( document.documentElement.doScroll && toplevel ) { doScrollCheck(); } } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { /// <summary> /// Determines if the parameter passed is a function. /// </summary> /// <param name="obj" type="Object">The object to check</param> /// <returns type="Boolean">True if the parameter is a function; otherwise false.</returns> return toString.call(obj) === "[object Function]"; }, isArray: function( obj ) { /// <summary> /// Determine if the parameter passed is an array. /// </summary> /// <param name="obj" type="Object">Object to test whether or not it is an array.</param> /// <returns type="Boolean">True if the parameter is a function; otherwise false.</returns> return toString.call(obj) === "[object Array]"; }, isPlainObject: function( obj ) { /// <summary> /// Check to see if an object is a plain object (created using "{}" or "new Object"). /// </summary> /// <param name="obj" type="Object"> /// The object that will be checked to see if it's a plain object. /// </param> /// <returns type="Boolean" /> // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || toString.call(obj) !== "[object Object]" || obj.nodeType || obj.setInterval ) { return false; } // Not own constructor property must be Object if ( obj.constructor && !hasOwnProperty.call(obj, "constructor") && !hasOwnProperty.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; for ( key in obj ) {} return key === undefined || hasOwnProperty.call( obj, key ); }, isEmptyObject: function( obj ) { /// <summary> /// Check to see if an object is empty (contains no properties). /// </summary> /// <param name="obj" type="Object"> /// The object that will be checked to see if it's empty. /// </param> /// <returns type="Boolean" /> for ( var name in obj ) { return false; } return true; }, error: function( msg ) { throw msg; }, parseJSON: function( data ) { if ( typeof data !== "string" || !data ) { return null; } // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( /^[\],:{}\s]*$/.test(data.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@") .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]") .replace(/(?:^|:|,)(?:\s*\[)+/g, "")) ) { // Try to use the native JSON parser first return window.JSON && window.JSON.parse ? window.JSON.parse( data ) : (new Function("return " + data))(); } else { jQuery.error( "Invalid JSON: " + data ); } }, noop: function() { /// <summary> /// An empty function. /// </summary> /// <returns type="Function" /> }, // Evalulates a script in a global context globalEval: function( data ) { /// <summary> /// Internally evaluates a script in a global context. /// </summary> /// <private /> if ( data && rnotwhite.test(data) ) { // Inspired by code by Andrea Giammarchi // http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html var head = document.getElementsByTagName("head")[0] || document.documentElement, script = document.createElement("script"); script.type = "text/javascript"; if ( jQuery.support.scriptEval ) { script.appendChild( document.createTextNode( data ) ); } else { script.text = data; } // Use insertBefore instead of appendChild to circumvent an IE6 bug. // This arises when a base node is used (#2709). head.insertBefore( script, head.firstChild ); head.removeChild( script ); } }, nodeName: function( elem, name ) { /// <summary> /// Checks whether the specified element has the specified DOM node name. /// </summary> /// <param name="elem" type="Element">The element to examine</param> /// <param name="name" type="String">The node name to check</param> /// <returns type="Boolean">True if the specified node name matches the node's DOM node name; otherwise false</returns> return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase(); }, // args is for internal usage only each: function( object, callback, args ) { /// <summary> /// A generic iterator function, which can be used to seemlessly /// iterate over both objects and arrays. This function is not the same /// as $().each() - which is used to iterate, exclusively, over a jQuery /// object. This function can be used to iterate over anything. /// The callback has two arguments:the key (objects) or index (arrays) as first /// the first, and the value as the second. /// Part of JavaScript /// </summary> /// <param name="obj" type="Object"> /// The object, or array, to iterate over. /// </param> /// <param name="fn" type="Function"> /// The function that will be executed on every object. /// </param> /// <returns type="Object" /> var name, i = 0, length = object.length, isObj = length === undefined || jQuery.isFunction(object); if ( args ) { if ( isObj ) { for ( name in object ) { if ( callback.apply( object[ name ], args ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.apply( object[ i++ ], args ) === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isObj ) { for ( name in object ) { if ( callback.call( object[ name ], name, object[ name ] ) === false ) { break; } } } else { for ( var value = object[0]; i < length && callback.call( value, i, value ) !== false; value = object[++i] ) {} } } return object; }, trim: function( text ) { /// <summary> /// Remove the whitespace from the beginning and end of a string. /// Part of JavaScript /// </summary> /// <returns type="String" /> /// <param name="text" type="String"> /// The string to trim. /// </param> return (text || "").replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( array, results ) { /// <summary> /// Turns anything into a true array. This is an internal method. /// </summary> /// <param name="array" type="Object">Anything to turn into an actual Array</param> /// <returns type="Array" /> /// <private /> var ret = results || []; if ( array != null ) { // The window, strings (and functions) also have 'length' // The extra typeof function check is to prevent crashes // in Safari 2 (See: #3039) if ( array.length == null || typeof array === "string" || jQuery.isFunction(array) || (typeof array !== "function" && array.setInterval) ) { push.call( ret, array ); } else { jQuery.merge( ret, array ); } } return ret; }, inArray: function( elem, array ) { if ( array.indexOf ) { return array.indexOf( elem ); } for ( var i = 0, length = array.length; i < length; i++ ) { if ( array[ i ] === elem ) { return i; } } return -1; }, merge: function( first, second ) { /// <summary> /// Merge two arrays together, removing all duplicates. /// The new array is: All the results from the first array, followed /// by the unique results from the second array. /// Part of JavaScript /// </summary> /// <returns type="Array" /> /// <param name="first" type="Array"> /// The first array to merge. /// </param> /// <param name="second" type="Array"> /// The second array to merge. /// </param> var i = first.length, j = 0; if ( typeof second.length === "number" ) { for ( var l = second.length; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { /// <summary> /// Filter items out of an array, by using a filter function. /// The specified function will be passed two arguments: The /// current array item and the index of the item in the array. The /// function must return 'true' to keep the item in the array, /// false to remove it. /// }); /// Part of JavaScript /// </summary> /// <returns type="Array" /> /// <param name="elems" type="Array"> /// array The Array to find items in. /// </param> /// <param name="fn" type="Function"> /// The function to process each item against. /// </param> /// <param name="inv" type="Boolean"> /// Invert the selection - select the opposite of the function. /// </param> var ret = []; // Go through the array, only saving the items // that pass the validator function for ( var i = 0, length = elems.length; i < length; i++ ) { if ( !inv !== !callback( elems[ i ], i ) ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { /// <summary> /// Translate all items in an array to another array of items. /// The translation function that is provided to this method is /// called for each item in the array and is passed one argument: /// The item to be translated. /// The function can then return the translated value, 'null' /// (to remove the item), or an array of values - which will /// be flattened into the full array. /// Part of JavaScript /// </summary> /// <returns type="Array" /> /// <param name="elems" type="Array"> /// array The Array to translate. /// </param> /// <param name="fn" type="Function"> /// The function to process each item against. /// </param> var ret = [], value; // Go through the array, translating each of the items to their // new value (or values). for ( var i = 0, length = elems.length; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } return ret.concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, proxy: function( fn, proxy, thisObject ) { /// <summary> /// Takes a function and returns a new one that will always have a particular scope. /// </summary> /// <param name="fn" type="Function"> /// The function whose scope will be changed. /// </param> /// <param name="proxy" type="Object"> /// The object to which the scope of the function should be set. /// </param> /// <returns type="Function" /> if ( arguments.length === 2 ) { if ( typeof proxy === "string" ) { thisObject = fn; fn = thisObject[ proxy ]; proxy = undefined; } else if ( proxy && !jQuery.isFunction( proxy ) ) { thisObject = proxy; proxy = undefined; } } if ( !proxy && fn ) { proxy = function() { return fn.apply( thisObject || this, arguments ); }; } // Set the guid of unique handler to the same of original handler, so it can be removed if ( fn ) { proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++; } // So proxy can be declared as an argument return proxy; }, // Use of jQuery.browser is frowned upon. // More details: http://docs.jquery.com/Utilities/jQuery.browser uaMatch: function( ua ) { ua = ua.toLowerCase(); var match = /(webkit)[ \/]([\w.]+)/.exec( ua ) || /(opera)(?:.*version)?[ \/]([\w.]+)/.exec( ua ) || /(msie) ([\w.]+)/.exec( ua ) || !/compatible/.test( ua ) && /(mozilla)(?:.*? rv:([\w.]+))?/.exec( ua ) || []; return { browser: match[1] || "", version: match[2] || "0" }; }, browser: {} }); browserMatch = jQuery.uaMatch( userAgent ); if ( browserMatch.browser ) { jQuery.browser[ browserMatch.browser ] = true; jQuery.browser.version = browserMatch.version; } // Deprecated, use jQuery.browser.webkit instead if ( jQuery.browser.webkit ) { jQuery.browser.safari = true; } if ( indexOf ) { jQuery.inArray = function( elem, array ) { /// <summary> /// Determines the index of the first parameter in the array. /// </summary> /// <param name="elem">The value to see if it exists in the array.</param> /// <param name="array" type="Array">The array to look through for the value</param> /// <returns type="Number" integer="true">The 0-based index of the item if it was found, otherwise -1.</returns> return indexOf.call( array, elem ); }; } // All jQuery objects should point back to these rootjQuery = jQuery(document); // Cleanup functions for the document ready method if ( document.addEventListener ) { DOMContentLoaded = function() { document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); jQuery.ready(); }; } else if ( document.attachEvent ) { DOMContentLoaded = function() { // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( document.readyState === "complete" ) { document.detachEvent( "onreadystatechange", DOMContentLoaded ); jQuery.ready(); } }; } // The DOM ready check for Internet Explorer function doScrollCheck() { if ( jQuery.isReady ) { return; } try { // If IE is used, use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ document.documentElement.doScroll("left"); } catch( error ) { setTimeout( doScrollCheck, 1 ); return; } // and execute any waiting functions jQuery.ready(); } function evalScript( i, elem ) { /// <summary> /// This method is internal. /// </summary> /// <private /> if ( elem.src ) { jQuery.ajax({ url: elem.src, async: false, dataType: "script" }); } else { jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } } // Mutifunctional method to get and set values to a collection // The value/s can be optionally by executed if its a function function access( elems, key, value, exec, fn, pass ) { var length = elems.length; // Setting many attributes if ( typeof key === "object" ) { for ( var k in key ) { access( elems, k, key[k], exec, fn, value ); } return elems; } // Setting one attribute if ( value !== undefined ) { // Optionally, function values get executed if exec is true exec = !pass && exec && jQuery.isFunction(value); for ( var i = 0; i < length; i++ ) { fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); } return elems; } // Getting an attribute return length ? fn( elems[0], key ) : null; } function now() { /// <summary> /// Gets the current date. /// </summary> /// <returns type="Date">The current date.</returns> return (new Date).getTime(); } // [vsdoc] The following function has been modified for IntelliSense. // [vsdoc] Stubbing support properties to "false" for IntelliSense compat. (function() { jQuery.support = {}; // var root = document.documentElement, // script = document.createElement("script"), // div = document.createElement("div"), // id = "script" + now(); // div.style.display = "none"; // div.innerHTML = " <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>"; // var all = div.getElementsByTagName("*"), // a = div.getElementsByTagName("a")[0]; // // Can't get basic test support // if ( !all || !all.length || !a ) { // return; // } jQuery.support = { // IE strips leading whitespace when .innerHTML is used leadingWhitespace: false, // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables tbody: false, // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE htmlSerialize: false, // Get the style information from getAttribute // (IE uses .cssText insted) style: false, // Make sure that URLs aren't manipulated // (IE normalizes it by default) hrefNormalized: false, // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 opacity: false, // Verify style float existence // (IE uses styleFloat instead of cssFloat) cssFloat: false, // Make sure that if no value is specified for a checkbox // that it defaults to "on". // (WebKit defaults to "" instead) checkOn: false, // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) optSelected: false, // Will be defined later checkClone: false, scriptEval: false, noCloneEvent: false, boxModel: false }; // script.type = "text/javascript"; // try { // script.appendChild( document.createTextNode( "window." + id + "=1;" ) ); // } catch(e) {} // root.insertBefore( script, root.firstChild ); // // Make sure that the execution of code works by injecting a script // // tag with appendChild/createTextNode // // (IE doesn't support this, fails, and uses .text instead) // if ( window[ id ] ) { // jQuery.support.scriptEval = true; // delete window[ id ]; // } // root.removeChild( script ); // if ( div.attachEvent && div.fireEvent ) { // div.attachEvent("onclick", function click() { // // Cloning a node shouldn't copy over any // // bound event handlers (IE does this) // jQuery.support.noCloneEvent = false; // div.detachEvent("onclick", click); // }); // div.cloneNode(true).fireEvent("onclick"); // } // div = document.createElement("div"); // div.innerHTML = "<input type='radio' name='radiotest' checked='checked'/>"; // var fragment = document.createDocumentFragment(); // fragment.appendChild( div.firstChild ); // // WebKit doesn't clone checked state correctly in fragments // jQuery.support.checkClone = fragment.cloneNode(true).cloneNode(true).lastChild.checked; // // Figure out if the W3C box model works as expected // // document.body must exist before we can do this // jQuery(function() { // var div = document.createElement("div"); // div.style.width = div.style.paddingLeft = "1px"; // document.body.appendChild( div ); // jQuery.boxModel = jQuery.support.boxModel = div.offsetWidth === 2; // document.body.removeChild( div ).style.display = 'none'; // div = null; // }); // // Technique from Juriy Zaytsev // // http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/ // var eventSupported = function( eventName ) { // var el = document.createElement("div"); // eventName = "on" + eventName; // var isSupported = (eventName in el); // if ( !isSupported ) { // el.setAttribute(eventName, "return;"); // isSupported = typeof el[eventName] === "function"; // } // el = null; // return isSupported; // }; jQuery.support.submitBubbles = false; jQuery.support.changeBubbles = false; // // release memory in IE // root = script = div = all = a = null; })(); jQuery.props = { "for": "htmlFor", "class": "className", readonly: "readOnly", maxlength: "maxLength", cellspacing: "cellSpacing", rowspan: "rowSpan", colspan: "colSpan", tabindex: "tabIndex", usemap: "useMap", frameborder: "frameBorder" }; var expando = "jQuery" + now(), uuid = 0, windowData = {}; var emptyObject = {}; jQuery.extend({ cache: {}, expando:expando, // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "embed": true, "object": true, "applet": true }, data: function( elem, name, data ) { /// <summary> /// Store arbitrary data associated with the specified element. /// </summary> /// <param name="elem" type="Element"> /// The DOM element to associate with the data. /// </param> /// <param name="name" type="String"> /// A string naming the piece of data to set. /// </param> /// <param name="value" type="Object"> /// The new data value. /// </param> /// <returns type="jQuery" /> if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) { return; } elem = elem == window ? windowData : elem; var id = elem[ expando ], cache = jQuery.cache, thisCache; // Handle the case where there's no name immediately if ( !name && !id ) { return null; } // Compute a unique ID for the element if ( !id ) { id = ++uuid; } // Avoid generating a new cache unless none exists and we // want to manipulate it. if ( typeof name === "object" ) { elem[ expando ] = id; thisCache = cache[ id ] = jQuery.extend(true, {}, name); } else if ( cache[ id ] ) { thisCache = cache[ id ]; } else if ( typeof data === "undefined" ) { thisCache = emptyObject; } else { thisCache = cache[ id ] = {}; } // Prevent overriding the named cache with undefined values if ( data !== undefined ) { elem[ expando ] = id; thisCache[ name ] = data; } return typeof name === "string" ? thisCache[ name ] : thisCache; }, removeData: function( elem, name ) { if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) { return; } elem = elem == window ? windowData : elem; var id = elem[ expando ], cache = jQuery.cache, thisCache = cache[ id ]; // If we want to remove a specific section of the element's data if ( name ) { if ( thisCache ) { // Remove the section of cache data delete thisCache[ name ]; // If we've removed all the data, remove the element's cache if ( jQuery.isEmptyObject(thisCache) ) { jQuery.removeData( elem ); } } // Otherwise, we want to remove all of the element's data } else { // Clean up the element expando try { delete elem[ expando ]; } catch( e ) { // IE has trouble directly removing the expando // but it's ok with using removeAttribute if ( elem.removeAttribute ) { elem.removeAttribute( expando ); } } // Completely remove the data cache delete cache[ id ]; } } }); jQuery.fn.extend({ data: function( key, value ) { /// <summary> /// Store arbitrary data associated with the matched elements. /// </summary> /// <param name="key" type="String"> /// A string naming the piece of data to set. /// </param> /// <param name="value" type="Object"> /// The new data value. /// </param> /// <returns type="jQuery" /> if ( typeof key === "undefined" && this.length ) { return jQuery.data( this[0] ); } else if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } var parts = key.split("."); parts[1] = parts[1] ? "." + parts[1] : ""; if ( value === undefined ) { var data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]); if ( data === undefined && this.length ) { data = jQuery.data( this[0], key ); } return data === undefined && parts[1] ? this.data( parts[0] ) : data; } else { return this.trigger("setData" + parts[1] + "!", [parts[0], value]).each(function() { jQuery.data( this, key, value ); }); } }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); jQuery.extend({ queue: function( elem, type, data ) { if ( !elem ) { return; } type = (type || "fx") + "queue"; var q = jQuery.data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( !data ) { return q || []; } if ( !q || jQuery.isArray(data) ) { q = jQuery.data( elem, type, jQuery.makeArray(data) ); } else { q.push( data ); } return q; }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), fn = queue.shift(); // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift("inprogress"); } fn.call(elem, function() { jQuery.dequeue(elem, type); }); } } }); jQuery.fn.extend({ queue: function( type, data ) { /// <summary> /// 1: queue() - Returns a reference to the first element's queue (which is an array of functions). /// 2: queue(callback) - Adds a new function, to be executed, onto the end of the queue of all matched elements. /// 3: queue(queue) - Replaces the queue of all matched element with this new queue (the array of functions). /// </summary> /// <param name="type" type="Function">The function to add to the queue.</param> /// <returns type="jQuery" /> if ( typeof type !== "string" ) { data = type; type = "fx"; } if ( data === undefined ) { return jQuery.queue( this[0], type ); } return this.each(function( i, elem ) { var queue = jQuery.queue( this, type, data ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { /// <summary> /// Removes a queued function from the front of the queue and executes it. /// </summary> /// <param name="type" type="String" optional="true">The type of queue to access.</param> /// <returns type="jQuery" /> return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function( time, type ) { /// <summary> /// Set a timer to delay execution of subsequent items in the queue. /// </summary> /// <param name="time" type="Number"> /// An integer indicating the number of milliseconds to delay execution of the next item in the queue. /// </param> /// <param name="type" type="String"> /// A string containing the name of the queue. Defaults to fx, the standard effects queue. /// </param> /// <returns type="jQuery" /> time = jQuery.fx ? jQuery.fx.speeds[time] || time : time; type = type || "fx"; return this.queue( type, function() { var elem = this; setTimeout(function() { jQuery.dequeue( elem, type ); }, time ); }); }, clearQueue: function( type ) { /// <summary> /// Remove from the queue all items that have not yet been run. /// </summary> /// <param name="type" type="String" optional="true"> /// A string containing the name of the queue. Defaults to fx, the standard effects queue. /// </param> /// <returns type="jQuery" /> return this.queue( type || "fx", [] ); } }); var rclass = /[\n\t]/g, rspace = /\s+/, rreturn = /\r/g, rspecialurl = /href|src|style/, rtype = /(button|input)/i, rfocusable = /(button|input|object|select|textarea)/i, rclickable = /^(a|area)$/i, rradiocheck = /radio|checkbox/; jQuery.fn.extend({ attr: function( name, value ) { /// <summary> /// Set a single property to a computed value, on all matched elements. /// Instead of a value, a function is provided, that computes the value. /// Part of DOM/Attributes /// </summary> /// <returns type="jQuery" /> /// <param name="name" type="String"> /// The name of the property to set. /// </param> /// <param name="value" type="Function"> /// A function returning the value to set. /// </param> return access( this, name, value, true, jQuery.attr ); }, removeAttr: function( name, fn ) { /// <summary> /// Remove an attribute from each of the matched elements. /// Part of DOM/Attributes /// </summary> /// <param name="name" type="String"> /// An attribute to remove. /// </param> /// <returns type="jQuery" /> return this.each(function(){ jQuery.attr( this, name, "" ); if ( this.nodeType === 1 ) { this.removeAttribute( name ); } }); }, addClass: function( value ) { /// <summary> /// Adds the specified class(es) to each of the set of matched elements. /// Part of DOM/Attributes /// </summary> /// <param name="value" type="String"> /// One or more class names to be added to the class attribute of each matched element. /// </param> /// <returns type="jQuery" /> if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); self.addClass( value.call(this, i, self.attr("class")) ); }); } if ( value && typeof value === "string" ) { var classNames = (value || "").split( rspace ); for ( var i = 0, l = this.length; i < l; i++ ) { var elem = this[i]; if ( elem.nodeType === 1 ) { if ( !elem.className ) { elem.className = value; } else { var className = " " + elem.className + " "; for ( var c = 0, cl = classNames.length; c < cl; c++ ) { if ( className.indexOf( " " + classNames[c] + " " ) < 0 ) { elem.className += " " + classNames[c]; } } } } } } return this; }, removeClass: function( value ) { /// <summary> /// Removes all or the specified class(es) from the set of matched elements. /// Part of DOM/Attributes /// </summary> /// <param name="value" type="String" optional="true"> /// (Optional) A class name to be removed from the class attribute of each matched element. /// </param> /// <returns type="jQuery" /> if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); self.removeClass( value.call(this, i, self.attr("class")) ); }); } if ( (value && typeof value === "string") || value === undefined ) { var classNames = (value || "").split(rspace); for ( var i = 0, l = this.length; i < l; i++ ) { var elem = this[i]; if ( elem.nodeType === 1 && elem.className ) { if ( value ) { var className = (" " + elem.className + " ").replace(rclass, " "); for ( var c = 0, cl = classNames.length; c < cl; c++ ) { className = className.replace(" " + classNames[c] + " ", " "); } elem.className = className.substring(1, className.length - 1); } else { elem.className = ""; } } } } return this; }, toggleClass: function( value, stateVal ) { /// <summary> /// Add or remove a class from each element in the set of matched elements, depending /// on either the class's presence or the value of the switch argument. /// </summary> /// <param name="value" type="Object"> /// A class name to be toggled for each element in the matched set. /// </param> /// <param name="stateVal" type="Object"> /// A boolean value to determine whether the class should be added or removed. /// </param> /// <returns type="jQuery" /> var type = typeof value, isBool = typeof stateVal === "boolean"; if ( jQuery.isFunction( value ) ) { return this.each(function(i) { var self = jQuery(this); self.toggleClass( value.call(this, i, self.attr("class"), stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery(this), state = stateVal, classNames = value.split( rspace ); while ( (className = classNames[ i++ ]) ) { // check each className given, space seperated list state = isBool ? state : !self.hasClass( className ); self[ state ? "addClass" : "removeClass" ]( className ); } } else if ( type === "undefined" || type === "boolean" ) { if ( this.className ) { // store className if set jQuery.data( this, "__className__", this.className ); } // toggle whole className this.className = this.className || value === false ? "" : jQuery.data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { /// <summary> /// Checks the current selection against a class and returns whether at least one selection has a given class. /// </summary> /// <param name="selector" type="String">The class to check against</param> /// <returns type="Boolean">True if at least one element in the selection has the class, otherwise false.</returns> var className = " " + selector + " "; for ( var i = 0, l = this.length; i < l; i++ ) { if ( (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) { return true; } } return false; }, val: function( value ) { /// <summary> /// Set the value of every matched element. /// Part of DOM/Attributes /// </summary> /// <returns type="jQuery" /> /// <param name="value" type="String"> /// A string of text or an array of strings to set as the value property of each /// matched element. /// </param> if ( value === undefined ) { var elem = this[0]; if ( elem ) { if ( jQuery.nodeName( elem, "option" ) ) { return (elem.attributes.value || {}).specified ? elem.value : elem.text; } // We need to handle select boxes special if ( jQuery.nodeName( elem, "select" ) ) { var index = elem.selectedIndex, values = [], options = elem.options, one = elem.type === "select-one"; // Nothing was selected if ( index < 0 ) { return null; } // Loop through all the selected options for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) { var option = options[ i ]; if ( option.selected ) { // Get the specifc value for the option value = jQuery(option).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; } // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified if ( rradiocheck.test( elem.type ) && !jQuery.support.checkOn ) { return elem.getAttribute("value") === null ? "on" : elem.value; } // Everything else, we just grab the value return (elem.value || "").replace(rreturn, ""); } return undefined; } var isFunction = jQuery.isFunction(value); return this.each(function(i) { var self = jQuery(this), val = value; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call(this, i, self.val()); } // Typecast each time if the value is a Function and the appended // value is therefore different each time. if ( typeof val === "number" ) { val += ""; } if ( jQuery.isArray(val) && rradiocheck.test( this.type ) ) { this.checked = jQuery.inArray( self.val(), val ) >= 0; } else if ( jQuery.nodeName( this, "select" ) ) { var values = jQuery.makeArray(val); jQuery( "option", this ).each(function() { this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; }); if ( !values.length ) { this.selectedIndex = -1; } } else { this.value = val; } }); } }); jQuery.extend({ attrFn: { val: true, css: true, html: true, text: true, data: true, width: true, height: true, offset: true }, attr: function( elem, name, value, pass ) { /// <summary> /// This method is internal. /// </summary> /// <private /> // don't set attributes on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) { return undefined; } if ( pass && name in jQuery.attrFn ) { return jQuery(elem)[name](value); } var notxml = elem.nodeType !== 1 || !jQuery.isXMLDoc( elem ), // Whether we are setting (or getting) set = value !== undefined; // Try to normalize/fix the name name = notxml && jQuery.props[ name ] || name; // Only do all the following if this is a node (faster for style) if ( elem.nodeType === 1 ) { // These attributes require special treatment var special = rspecialurl.test( name ); // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( name === "selected" && !jQuery.support.optSelected ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } } // If applicable, access the attribute via the DOM 0 way if ( name in elem && notxml && !special ) { if ( set ) { // We can't allow the type property to be changed (since it causes problems in IE) if ( name === "type" && rtype.test( elem.nodeName ) && elem.parentNode ) { jQuery.error( "type property can't be changed" ); } elem[ name ] = value; } // browsers index elements by id/name on forms, give priority to attributes. if ( jQuery.nodeName( elem, "form" ) && elem.getAttributeNode(name) ) { return elem.getAttributeNode( name ).nodeValue; } // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ if ( name === "tabIndex" ) { var attributeNode = elem.getAttributeNode( "tabIndex" ); return attributeNode && attributeNode.specified ? attributeNode.value : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : undefined; } return elem[ name ]; } if ( !jQuery.support.style && notxml && name === "style" ) { if ( set ) { elem.style.cssText = "" + value; } return elem.style.cssText; } if ( set ) { // convert the value to a string (all browsers do this but IE) see #1070 elem.setAttribute( name, "" + value ); } var attr = !jQuery.support.hrefNormalized && notxml && special ? // Some attributes require a special call on IE elem.getAttribute( name, 2 ) : elem.getAttribute( name ); // Non-existent attributes return null, we normalize to undefined return attr === null ? undefined : attr; } // elem is actually elem.style ... set the style // Using attr for specific style information is now deprecated. Use style insead. return jQuery.style( elem, name, value ); } }); var fcleanup = function( nm ) { return nm.replace(/[^\w\s\.\|`]/g, function( ch ) { return "\\" + ch; }); }; /* * A number of helper functions used for managing events. * Many of the ideas behind this code originated from * Dean Edwards' addEvent library. */ jQuery.event = { // Bind an event to an element // Original by Dean Edwards add: function( elem, types, handler, data ) { /// <summary> /// This method is internal. /// </summary> /// <private /> if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // For whatever reason, IE has trouble passing the window object // around, causing it to be cloned in the process if ( elem.setInterval && ( elem !== window && !elem.frameElement ) ) { elem = window; } // Make sure that the function being executed has a unique ID if ( !handler.guid ) { handler.guid = jQuery.guid++; } // if data is passed, bind to handler if ( data !== undefined ) { // Create temporary function pointer to original handler var fn = handler; // Create unique handler function, wrapped around original handler handler = jQuery.proxy( fn ); // Store data in unique handler handler.data = data; } // Init the element's event structure var events = jQuery.data( elem, "events" ) || jQuery.data( elem, "events", {} ), handle = jQuery.data( elem, "handle" ), eventHandle; if ( !handle ) { eventHandle = function() { // Handle the second event of a trigger and when // an event is called after a page has unloaded return typeof jQuery !== "undefined" && !jQuery.event.triggered ? jQuery.event.handle.apply( eventHandle.elem, arguments ) : undefined; }; handle = jQuery.data( elem, "handle", eventHandle ); } // If no handle is found then we must be trying to bind to one of the // banned noData elements if ( !handle ) { return; } // Add elem as a property of the handle function // This is to prevent a memory leak with non-native // event in IE. handle.elem = elem; // Handle multiple events separated by a space // jQuery(...).bind("mouseover mouseout", fn); types = types.split( /\s+/ ); var type, i = 0; while ( (type = types[ i++ ]) ) { // Namespaced event handlers var namespaces = type.split("."); type = namespaces.shift(); if ( i > 1 ) { handler = jQuery.proxy( handler ); if ( data !== undefined ) { handler.data = data; } } handler.type = namespaces.slice(0).sort().join("."); // Get the current list of functions bound to this event var handlers = events[ type ], special = this.special[ type ] || {}; // Init the event handler queue if ( !handlers ) { handlers = events[ type ] = {}; // Check for a special event handler // Only use addEventListener/attachEvent if the special // events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, handler) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, handle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, handle ); } } } if ( special.add ) { var modifiedHandler = special.add.call( elem, handler, data, namespaces, handlers ); if ( modifiedHandler && jQuery.isFunction( modifiedHandler ) ) { modifiedHandler.guid = modifiedHandler.guid || handler.guid; modifiedHandler.data = modifiedHandler.data || handler.data; modifiedHandler.type = modifiedHandler.type || handler.type; handler = modifiedHandler; } } // Add the function to the element's handler list handlers[ handler.guid ] = handler; // Keep track of which events have been used, for global triggering this.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, global: {}, // Detach an event or set of events from an element remove: function( elem, types, handler ) { /// <summary> /// This method is internal. /// </summary> /// <private /> // don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } var events = jQuery.data( elem, "events" ), ret, type, fn; if ( events ) { // Unbind all events for the element if ( types === undefined || (typeof types === "string" && types.charAt(0) === ".") ) { for ( type in events ) { this.remove( elem, type + (types || "") ); } } else { // types is actually an event object here if ( types.type ) { handler = types.handler; types = types.type; } // Handle multiple events separated by a space // jQuery(...).unbind("mouseover mouseout", fn); types = types.split(/\s+/); var i = 0; while ( (type = types[ i++ ]) ) { // Namespaced event handlers var namespaces = type.split("."); type = namespaces.shift(); var all = !namespaces.length, cleaned = jQuery.map( namespaces.slice(0).sort(), fcleanup ), namespace = new RegExp("(^|\\.)" + cleaned.join("\\.(?:.*\\.)?") + "(\\.|$)"), special = this.special[ type ] || {}; if ( events[ type ] ) { // remove the given handler for the given type if ( handler ) { fn = events[ type ][ handler.guid ]; delete events[ type ][ handler.guid ]; // remove all handlers for the given type } else { for ( var handle in events[ type ] ) { // Handle the removal of namespaced events if ( all || namespace.test( events[ type ][ handle ].type ) ) { delete events[ type ][ handle ]; } } } if ( special.remove ) { special.remove.call( elem, namespaces, fn); } // remove generic event handler if no more handlers exist for ( ret in events[ type ] ) { break; } if ( !ret ) { if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, jQuery.data( elem, "handle" ), false ); } else if ( elem.detachEvent ) { elem.detachEvent( "on" + type, jQuery.data( elem, "handle" ) ); } } ret = null; delete events[ type ]; } } } } // Remove the expando if it's no longer used for ( ret in events ) { break; } if ( !ret ) { var handle = jQuery.data( elem, "handle" ); if ( handle ) { handle.elem = null; } jQuery.removeData( elem, "events" ); jQuery.removeData( elem, "handle" ); } } }, // bubbling is internal trigger: function( event, data, elem /*, bubbling */ ) { /// <summary> /// This method is internal. /// </summary> /// <private /> // Event object or event type var type = event.type || event, bubbling = arguments[3]; if ( !bubbling ) { event = typeof event === "object" ? // jQuery.Event object event[expando] ? event : // Object literal jQuery.extend( jQuery.Event(type), event ) : // Just the event type (string) jQuery.Event(type); if ( type.indexOf("!") >= 0 ) { event.type = type = type.slice(0, -1); event.exclusive = true; } // Handle a global trigger if ( !elem ) { // Don't bubble custom events when global (to avoid too much overhead) event.stopPropagation(); // Only trigger if we've ever bound an event for it if ( this.global[ type ] ) { jQuery.each( jQuery.cache, function() { if ( this.events && this.events[type] ) { jQuery.event.trigger( event, data, this.handle.elem ); } }); } } // Handle triggering a single element // don't do events on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) { return undefined; } // Clean up in case it is reused event.result = undefined; event.target = elem; // Clone the incoming data, if any data = jQuery.makeArray( data ); data.unshift( event ); } event.currentTarget = elem; // Trigger the event, it is assumed that "handle" is a function var handle = jQuery.data( elem, "handle" ); if ( handle ) { handle.apply( elem, data ); } var parent = elem.parentNode || elem.ownerDocument; // Trigger an inline bound script try { if ( !(elem && elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()]) ) { if ( elem[ "on" + type ] && elem[ "on" + type ].apply( elem, data ) === false ) { event.result = false; } } // prevent IE from throwing an error for some elements with some event types, see #3533 } catch (e) {} if ( !event.isPropagationStopped() && parent ) { jQuery.event.trigger( event, data, parent, true ); } else if ( !event.isDefaultPrevented() ) { var target = event.target, old, isClick = jQuery.nodeName(target, "a") && type === "click"; if ( !isClick && !(target && target.nodeName && jQuery.noData[target.nodeName.toLowerCase()]) ) { try { if ( target[ type ] ) { // Make sure that we don't accidentally re-trigger the onFOO events old = target[ "on" + type ]; if ( old ) { target[ "on" + type ] = null; } this.triggered = true; target[ type ](); } // prevent IE from throwing an error for some elements with some event types, see #3533 } catch (e) {} if ( old ) { target[ "on" + type ] = old; } this.triggered = false; } } }, handle: function( event ) { /// <summary> /// This method is internal. /// </summary> /// <private /> // returned undefined or false var all, handlers; event = arguments[0] = jQuery.event.fix( event || window.event ); event.currentTarget = this; // Namespaced event handlers var namespaces = event.type.split("."); event.type = namespaces.shift(); // Cache this now, all = true means, any handler all = !namespaces.length && !event.exclusive; var namespace = new RegExp("(^|\\.)" + namespaces.slice(0).sort().join("\\.(?:.*\\.)?") + "(\\.|$)"); handlers = ( jQuery.data(this, "events") || {} )[ event.type ]; for ( var j in handlers ) { var handler = handlers[ j ]; // Filter the functions by class if ( all || namespace.test(handler.type) ) { // Pass in a reference to the handler function itself // So that we can later remove it event.handler = handler; event.data = handler.data; var ret = handler.apply( this, arguments ); if ( ret !== undefined ) { event.result = ret; if ( ret === false ) { event.preventDefault(); event.stopPropagation(); } } if ( event.isImmediatePropagationStopped() ) { break; } } } return event.result; }, props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "), fix: function( event ) { /// <summary> /// This method is internal. /// </summary> /// <private /> if ( event[ expando ] ) { return event; } // store a copy of the original event object // and "clone" to set read-only properties var originalEvent = event; event = jQuery.Event( originalEvent ); for ( var i = this.props.length, prop; i; ) { prop = this.props[ --i ]; event[ prop ] = originalEvent[ prop ]; } // Fix target property, if necessary if ( !event.target ) { event.target = event.srcElement || document; // Fixes #1925 where srcElement might not be defined either } // check if target is a textnode (safari) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // Add relatedTarget, if necessary if ( !event.relatedTarget && event.fromElement ) { event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement; } // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && event.clientX != null ) { var doc = document.documentElement, body = document.body; event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0); event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0); } // Add which for key events if ( !event.which && ((event.charCode || event.charCode === 0) ? event.charCode : event.keyCode) ) { event.which = event.charCode || event.keyCode; } // Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs) if ( !event.metaKey && event.ctrlKey ) { event.metaKey = event.ctrlKey; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && event.button !== undefined ) { event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) )); } return event; }, // Deprecated, use jQuery.guid instead guid: 1E8, // Deprecated, use jQuery.proxy instead proxy: jQuery.proxy, special: { ready: { // Make sure the ready event is setup setup: jQuery.bindReady, teardown: jQuery.noop }, live: { add: function( proxy, data, namespaces, live ) { jQuery.extend( proxy, data || {} ); proxy.guid += data.selector + data.live; data.liveProxy = proxy; jQuery.event.add( this, data.live, liveHandler, data ); }, remove: function( namespaces ) { if ( namespaces.length ) { var remove = 0, name = new RegExp("(^|\\.)" + namespaces[0] + "(\\.|$)"); jQuery.each( (jQuery.data(this, "events").live || {}), function() { if ( name.test(this.type) ) { remove++; } }); if ( remove < 1 ) { jQuery.event.remove( this, namespaces[0], liveHandler ); } } }, special: {} }, beforeunload: { setup: function( data, namespaces, fn ) { // We only want to do this special case on windows if ( this.setInterval ) { this.onbeforeunload = fn; } return false; }, teardown: function( namespaces, fn ) { if ( this.onbeforeunload === fn ) { this.onbeforeunload = null; } } } } }; jQuery.Event = function( src ) { // Allow instantiation without the 'new' keyword if ( !this.preventDefault ) { return new jQuery.Event( src ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Event type } else { this.type = src; } // timeStamp is buggy for some events on Firefox(#3843) // So we won't rely on the native value this.timeStamp = now(); // Mark it as fixed this[ expando ] = true; }; function returnFalse() { return false; } function returnTrue() { return true; } // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { preventDefault: function() { this.isDefaultPrevented = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if preventDefault exists run it on the original event if ( e.preventDefault ) { e.preventDefault(); } // otherwise set the returnValue property of the original event to false (IE) e.returnValue = false; }, stopPropagation: function() { this.isPropagationStopped = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if stopPropagation exists run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // otherwise set the cancelBubble property of the original event to true (IE) e.cancelBubble = true; }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); }, isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse }; // Checks if an event happened on an element within another element // Used in jQuery.event.special.mouseenter and mouseleave handlers var withinElement = function( event ) { // Check if mouse(over|out) are still within the same parent element var parent = event.relatedTarget; // Traverse up the tree while ( parent && parent !== this ) { // Firefox sometimes assigns relatedTarget a XUL element // which we cannot access the parentNode property of try { parent = parent.parentNode; // assuming we've left the element since we most likely mousedover a xul element } catch(e) { break; } } if ( parent !== this ) { // set the correct event type event.type = event.data; // handle event if we actually just moused on to a non sub-element jQuery.event.handle.apply( this, arguments ); } }, // In case of event delegation, we only need to rename the event.type, // liveHandler will take care of the rest. delegate = function( event ) { event.type = event.data; jQuery.event.handle.apply( this, arguments ); }; // Create mouseenter and mouseleave events jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { setup: function( data ) { jQuery.event.add( this, fix, data && data.selector ? delegate : withinElement, orig ); }, teardown: function( data ) { jQuery.event.remove( this, fix, data && data.selector ? delegate : withinElement ); } }; }); // submit delegation if ( !jQuery.support.submitBubbles ) { jQuery.event.special.submit = { setup: function( data, namespaces, fn ) { if ( this.nodeName.toLowerCase() !== "form" ) { jQuery.event.add(this, "click.specialSubmit." + fn.guid, function( e ) { var elem = e.target, type = elem.type; if ( (type === "submit" || type === "image") && jQuery( elem ).closest("form").length ) { return trigger( "submit", this, arguments ); } }); jQuery.event.add(this, "keypress.specialSubmit." + fn.guid, function( e ) { var elem = e.target, type = elem.type; if ( (type === "text" || type === "password") && jQuery( elem ).closest("form").length && e.keyCode === 13 ) { return trigger( "submit", this, arguments ); } }); } else { return false; } }, remove: function( namespaces, fn ) { jQuery.event.remove( this, "click.specialSubmit" + (fn ? "."+fn.guid : "") ); jQuery.event.remove( this, "keypress.specialSubmit" + (fn ? "."+fn.guid : "") ); } }; } // change delegation, happens here so we have bind. if ( !jQuery.support.changeBubbles ) { var formElems = /textarea|input|select/i; function getVal( elem ) { var type = elem.type, val = elem.value; if ( type === "radio" || type === "checkbox" ) { val = elem.checked; } else if ( type === "select-multiple" ) { val = elem.selectedIndex > -1 ? jQuery.map( elem.options, function( elem ) { return elem.selected; }).join("-") : ""; } else if ( elem.nodeName.toLowerCase() === "select" ) { val = elem.selectedIndex; } return val; } function testChange( e ) { var elem = e.target, data, val; if ( !formElems.test( elem.nodeName ) || elem.readOnly ) { return; } data = jQuery.data( elem, "_change_data" ); val = getVal(elem); // the current data will be also retrieved by beforeactivate if ( e.type !== "focusout" || elem.type !== "radio" ) { jQuery.data( elem, "_change_data", val ); } if ( data === undefined || val === data ) { return; } if ( data != null || val ) { e.type = "change"; return jQuery.event.trigger( e, arguments[1], elem ); } } jQuery.event.special.change = { filters: { focusout: testChange, click: function( e ) { var elem = e.target, type = elem.type; if ( type === "radio" || type === "checkbox" || elem.nodeName.toLowerCase() === "select" ) { return testChange.call( this, e ); } }, // Change has to be called before submit // Keydown will be called before keypress, which is used in submit-event delegation keydown: function( e ) { var elem = e.target, type = elem.type; if ( (e.keyCode === 13 && elem.nodeName.toLowerCase() !== "textarea") || (e.keyCode === 32 && (type === "checkbox" || type === "radio")) || type === "select-multiple" ) { return testChange.call( this, e ); } }, // Beforeactivate happens also before the previous element is blurred // with this event you can't trigger a change event, but you can store // information/focus[in] is not needed anymore beforeactivate: function( e ) { var elem = e.target; if ( elem.nodeName.toLowerCase() === "input" && elem.type === "radio" ) { jQuery.data( elem, "_change_data", getVal(elem) ); } } }, setup: function( data, namespaces, fn ) { for ( var type in changeFilters ) { jQuery.event.add( this, type + ".specialChange." + fn.guid, changeFilters[type] ); } return formElems.test( this.nodeName ); }, remove: function( namespaces, fn ) { for ( var type in changeFilters ) { jQuery.event.remove( this, type + ".specialChange" + (fn ? "."+fn.guid : ""), changeFilters[type] ); } return formElems.test( this.nodeName ); } }; var changeFilters = jQuery.event.special.change.filters; } function trigger( type, elem, args ) { args[0].type = type; return jQuery.event.handle.apply( elem, args ); } // Create "bubbling" focus and blur events if ( document.addEventListener ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { jQuery.event.special[ fix ] = { setup: function() { /// <summary> /// This method is internal. /// </summary> /// <private /> this.addEventListener( orig, handler, true ); }, teardown: function() { /// <summary> /// This method is internal. /// </summary> /// <private /> this.removeEventListener( orig, handler, true ); } }; function handler( e ) { e = jQuery.event.fix( e ); e.type = fix; return jQuery.event.handle.call( this, e ); } }); } // jQuery.each(["bind", "one"], function( i, name ) { // jQuery.fn[ name ] = function( type, data, fn ) { // // Handle object literals // if ( typeof type === "object" ) { // for ( var key in type ) { // this[ name ](key, data, type[key], fn); // } // return this; // } // // if ( jQuery.isFunction( data ) ) { // fn = data; // data = undefined; // } // // var handler = name === "one" ? jQuery.proxy( fn, function( event ) { // jQuery( this ).unbind( event, handler ); // return fn.apply( this, arguments ); // }) : fn; // // return type === "unload" && name !== "one" ? // this.one( type, data, fn ) : // this.each(function() { // jQuery.event.add( this, type, handler, data ); // }); // }; // }); jQuery.fn[ "bind" ] = function( type, data, fn ) { /// <summary> /// Binds a handler to one or more events for each matched element. Can also bind custom events. /// </summary> /// <param name="type" type="String">One or more event types separated by a space. Built-in event type values are: blur, focus, load, resize, scroll, unload, click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, error .</param> /// <param name="data" optional="true" type="Object">Additional data passed to the event handler as event.data</param> /// <param name="fn" type="Function">A function to bind to the event on each of the set of matched elements. function callback(eventObject) such that this corresponds to the dom element.</param> // Handle object literals if ( typeof type === "object" ) { for ( var key in type ) { this[ "bind" ](key, data, type[key], fn); } return this; } if ( jQuery.isFunction( data ) ) { fn = data; data = undefined; } var handler = "bind" === "one" ? jQuery.proxy( fn, function( event ) { jQuery( this ).unbind( event, handler ); return fn.apply( this, arguments ); }) : fn; return type === "unload" && "bind" !== "one" ? this.one( type, data, fn ) : this.each(function() { jQuery.event.add( this, type, handler, data ); }); }; jQuery.fn[ "one" ] = function( type, data, fn ) { /// <summary> /// Binds a handler to one or more events to be executed exactly once for each matched element. /// </summary> /// <param name="type" type="String">One or more event types separated by a space. Built-in event type values are: blur, focus, load, resize, scroll, unload, click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, error .</param> /// <param name="data" optional="true" type="Object">Additional data passed to the event handler as event.data</param> /// <param name="fn" type="Function">A function to bind to the event on each of the set of matched elements. function callback(eventObject) such that this corresponds to the dom element.</param> // Handle object literals if ( typeof type === "object" ) { for ( var key in type ) { this[ "one" ](key, data, type[key], fn); } return this; } if ( jQuery.isFunction( data ) ) { fn = data; data = undefined; } var handler = "one" === "one" ? jQuery.proxy( fn, function( event ) { jQuery( this ).unbind( event, handler ); return fn.apply( this, arguments ); }) : fn; return type === "unload" && "one" !== "one" ? this.one( type, data, fn ) : this.each(function() { jQuery.event.add( this, type, handler, data ); }); }; jQuery.fn.extend({ unbind: function( type, fn ) { /// <summary> /// Unbinds a handler from one or more events for each matched element. /// </summary> /// <param name="type" type="String">One or more event types separated by a space. Built-in event type values are: blur, focus, load, resize, scroll, unload, click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, error .</param> /// <param name="fn" type="Function">A function to bind to the event on each of the set of matched elements. function callback(eventObject) such that this corresponds to the dom element.</param> // Handle object literals if ( typeof type === "object" && !type.preventDefault ) { for ( var key in type ) { this.unbind(key, type[key]); } return this; } return this.each(function() { jQuery.event.remove( this, type, fn ); }); }, trigger: function( type, data ) { /// <summary> /// Triggers a type of event on every matched element. /// </summary> /// <param name="type" type="String">One or more event types separated by a space. Built-in event type values are: blur, focus, load, resize, scroll, unload, click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, error .</param> /// <param name="data" optional="true" type="Array">Additional data passed to the event handler as additional arguments.</param> /// <param name="fn" type="Function">This parameter is undocumented.</param> return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { /// <summary> /// Triggers all bound event handlers on an element for a specific event type without executing the browser's default actions. /// </summary> /// <param name="type" type="String">One or more event types separated by a space. Built-in event type values are: blur, focus, load, resize, scroll, unload, click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, error .</param> /// <param name="data" optional="true" type="Array">Additional data passed to the event handler as additional arguments.</param> /// <param name="fn" type="Function">This parameter is undocumented.</param> if ( this[0] ) { var event = jQuery.Event( type ); event.preventDefault(); event.stopPropagation(); jQuery.event.trigger( event, data, this[0] ); return event.result; } }, toggle: function( fn ) { /// <summary> /// Toggles among two or more function calls every other click. /// </summary> /// <param name="fn" type="Function">The functions among which to toggle execution</param> // Save reference to arguments for access in closure var args = arguments, i = 1; // link all the functions, so any of them can unbind this click handler while ( i < args.length ) { jQuery.proxy( fn, args[ i++ ] ); } return this.click( jQuery.proxy( fn, function( event ) { // Figure out which function to execute var lastToggle = ( jQuery.data( this, "lastToggle" + fn.guid ) || 0 ) % i; jQuery.data( this, "lastToggle" + fn.guid, lastToggle + 1 ); // Make sure that clicks stop event.preventDefault(); // and execute the function return args[ lastToggle ].apply( this, arguments ) || false; })); }, hover: function( fnOver, fnOut ) { /// <summary> /// Simulates hovering (moving the mouse on or off of an object). /// </summary> /// <param name="fnOver" type="Function">The function to fire when the mouse is moved over a matched element.</param> /// <param name="fnOut" type="Function">The function to fire when the mouse is moved off of a matched element.</param> return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); } }); // jQuery.each(["live", "die"], function( i, name ) { // jQuery.fn[ name ] = function( types, data, fn ) { // var type, i = 0; // // if ( jQuery.isFunction( data ) ) { // fn = data; // data = undefined; // } // // types = (types || "").split( /\s+/ ); // // while ( (type = types[ i++ ]) != null ) { // type = type === "focus" ? "focusin" : // focus --> focusin // type === "blur" ? "focusout" : // blur --> focusout // type === "hover" ? types.push("mouseleave") && "mouseenter" : // hover support // type; // // if ( name === "live" ) { // // bind live handler // jQuery( this.context ).bind( liveConvert( type, this.selector ), { // data: data, selector: this.selector, live: type // }, fn ); // // } else { // // unbind live handler // jQuery( this.context ).unbind( liveConvert( type, this.selector ), fn ? { guid: fn.guid + this.selector + type } : null ); // } // } // // return this; // } // }); jQuery.fn[ "live" ] = function( types, data, fn ) { /// <summary> /// Attach a handler to the event for all elements which match the current selector, now or /// in the future. /// </summary> /// <param name="types" type="String"> /// A string containing a JavaScript event type, such as "click" or "keydown". /// </param> /// <param name="data" type="Object"> /// A map of data that will be passed to the event handler. /// </param> /// <param name="fn" type="Function"> /// A function to execute at the time the event is triggered. /// </param> /// <returns type="jQuery" /> var type, i = 0; if ( jQuery.isFunction( data ) ) { fn = data; data = undefined; } types = (types || "").split( /\s+/ ); while ( (type = types[ i++ ]) != null ) { type = type === "focus" ? "focusin" : // focus --> focusin type === "blur" ? "focusout" : // blur --> focusout type === "hover" ? types.push("mouseleave") && "mouseenter" : // hover support type; if ( "live" === "live" ) { // bind live handler jQuery( this.context ).bind( liveConvert( type, this.selector ), { data: data, selector: this.selector, live: type }, fn ); } else { // unbind live handler jQuery( this.context ).unbind( liveConvert( type, this.selector ), fn ? { guid: fn.guid + this.selector + type } : null ); } } return this; } jQuery.fn[ "die" ] = function( types, data, fn ) { /// <summary> /// Remove all event handlers previously attached using .live() from the elements. /// </summary> /// <param name="types" type="String"> /// A string containing a JavaScript event type, such as click or keydown. /// </param> /// <param name="data" type="Object"> /// The function that is to be no longer executed. /// </param> /// <returns type="jQuery" /> var type, i = 0; if ( jQuery.isFunction( data ) ) { fn = data; data = undefined; } types = (types || "").split( /\s+/ ); while ( (type = types[ i++ ]) != null ) { type = type === "focus" ? "focusin" : // focus --> focusin type === "blur" ? "focusout" : // blur --> focusout type === "hover" ? types.push("mouseleave") && "mouseenter" : // hover support type; if ( "die" === "live" ) { // bind live handler jQuery( this.context ).bind( liveConvert( type, this.selector ), { data: data, selector: this.selector, live: type }, fn ); } else { // unbind live handler jQuery( this.context ).unbind( liveConvert( type, this.selector ), fn ? { guid: fn.guid + this.selector + type } : null ); } } return this; } function liveHandler( event ) { var stop, elems = [], selectors = [], args = arguments, related, match, fn, elem, j, i, l, data, live = jQuery.extend({}, jQuery.data( this, "events" ).live); // Make sure we avoid non-left-click bubbling in Firefox (#3861) if ( event.button && event.type === "click" ) { return; } for ( j in live ) { fn = live[j]; if ( fn.live === event.type || fn.altLive && jQuery.inArray(event.type, fn.altLive) > -1 ) { data = fn.data; if ( !(data.beforeFilter && data.beforeFilter[event.type] && !data.beforeFilter[event.type](event)) ) { selectors.push( fn.selector ); } } else { delete live[j]; } } match = jQuery( event.target ).closest( selectors, event.currentTarget ); for ( i = 0, l = match.length; i < l; i++ ) { for ( j in live ) { fn = live[j]; elem = match[i].elem; related = null; if ( match[i].selector === fn.selector ) { // Those two events require additional checking if ( fn.live === "mouseenter" || fn.live === "mouseleave" ) { related = jQuery( event.relatedTarget ).closest( fn.selector )[0]; } if ( !related || related !== elem ) { elems.push({ elem: elem, fn: fn }); } } } } for ( i = 0, l = elems.length; i < l; i++ ) { match = elems[i]; event.currentTarget = match.elem; event.data = match.fn.data; if ( match.fn.apply( match.elem, args ) === false ) { stop = false; break; } } return stop; } function liveConvert( type, selector ) { return "live." + (type ? type + "." : "") + selector.replace(/\./g, "`").replace(/ /g, "&"); } // jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + // "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + // "change select submit keydown keypress keyup error").split(" "), function( i, name ) { // // // Handle event binding // jQuery.fn[ name ] = function( fn ) { // return fn ? this.bind( name, fn ) : this.trigger( name ); // }; // // if ( jQuery.attrFn ) { // jQuery.attrFn[ name ] = true; // } // }); jQuery.fn[ "blur" ] = function( fn ) { /// <summary> /// 1: blur() - Triggers the blur event of each matched element. /// 2: blur(fn) - Binds a function to the blur event of each matched element. /// </summary> /// <param name="fn" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return fn ? this.bind( "blur", fn ) : this.trigger( "blur" ); }; jQuery.fn[ "focus" ] = function( fn ) { /// <summary> /// 1: focus() - Triggers the focus event of each matched element. /// 2: focus(fn) - Binds a function to the focus event of each matched element. /// </summary> /// <param name="fn" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return fn ? this.bind( "focus", fn ) : this.trigger( "focus" ); }; jQuery.fn[ "focusin" ] = function( fn ) { /// <summary> /// Bind an event handler to the "focusin" JavaScript event. /// </summary> /// <param name="fn" type="Function"> /// A function to execute each time the event is triggered. /// </param> /// <returns type="jQuery" /> return fn ? this.bind( "focusin", fn ) : this.trigger( "focusin" ); }; jQuery.fn[ "focusout" ] = function( fn ) { /// <summary> /// Bind an event handler to the "focusout" JavaScript event. /// </summary> /// <param name="fn" type="Function"> /// A function to execute each time the event is triggered. /// </param> /// <returns type="jQuery" /> return fn ? this.bind( "focusout", fn ) : this.trigger( "focusout" ); }; jQuery.fn[ "load" ] = function( fn ) { /// <summary> /// 1: load() - Triggers the load event of each matched element. /// 2: load(fn) - Binds a function to the load event of each matched element. /// </summary> /// <param name="fn" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return fn ? this.bind( "load", fn ) : this.trigger( "load" ); }; jQuery.fn[ "resize" ] = function( fn ) { /// <summary> /// 1: resize() - Triggers the resize event of each matched element. /// 2: resize(fn) - Binds a function to the resize event of each matched element. /// </summary> /// <param name="fn" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return fn ? this.bind( "resize", fn ) : this.trigger( "resize" ); }; jQuery.fn[ "scroll" ] = function( fn ) { /// <summary> /// 1: scroll() - Triggers the scroll event of each matched element. /// 2: scroll(fn) - Binds a function to the scroll event of each matched element. /// </summary> /// <param name="fn" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return fn ? this.bind( "scroll", fn ) : this.trigger( "scroll" ); }; jQuery.fn[ "unload" ] = function( fn ) { /// <summary> /// 1: unload() - Triggers the unload event of each matched element. /// 2: unload(fn) - Binds a function to the unload event of each matched element. /// </summary> /// <param name="fn" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return fn ? this.bind( "unload", fn ) : this.trigger( "unload" ); }; jQuery.fn[ "click" ] = function( fn ) { /// <summary> /// 1: click() - Triggers the click event of each matched element. /// 2: click(fn) - Binds a function to the click event of each matched element. /// </summary> /// <param name="fn" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return fn ? this.bind( "click", fn ) : this.trigger( "click" ); }; jQuery.fn[ "dblclick" ] = function( fn ) { /// <summary> /// 1: dblclick() - Triggers the dblclick event of each matched element. /// 2: dblclick(fn) - Binds a function to the dblclick event of each matched element. /// </summary> /// <param name="fn" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return fn ? this.bind( "dblclick", fn ) : this.trigger( "dblclick" ); }; jQuery.fn[ "mousedown" ] = function( fn ) { /// <summary> /// Binds a function to the mousedown event of each matched element. /// </summary> /// <param name="fn" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return fn ? this.bind( "mousedown", fn ) : this.trigger( "mousedown" ); }; jQuery.fn[ "mouseup" ] = function( fn ) { /// <summary> /// Bind a function to the mouseup event of each matched element. /// </summary> /// <param name="fn" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return fn ? this.bind( "mouseup", fn ) : this.trigger( "mouseup" ); }; jQuery.fn[ "mousemove" ] = function( fn ) { /// <summary> /// Bind a function to the mousemove event of each matched element. /// </summary> /// <param name="fn" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return fn ? this.bind( "mousemove", fn ) : this.trigger( "mousemove" ); }; jQuery.fn[ "mouseover" ] = function( fn ) { /// <summary> /// Bind a function to the mouseover event of each matched element. /// </summary> /// <param name="fn" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return fn ? this.bind( "mouseover", fn ) : this.trigger( "mouseover" ); }; jQuery.fn[ "mouseout" ] = function( fn ) { /// <summary> /// Bind a function to the mouseout event of each matched element. /// </summary> /// <param name="fn" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return fn ? this.bind( "mouseout", fn ) : this.trigger( "mouseout" ); }; jQuery.fn[ "mouseenter" ] = function( fn ) { /// <summary> /// Bind a function to the mouseenter event of each matched element. /// </summary> /// <param name="fn" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return fn ? this.bind( "mouseenter", fn ) : this.trigger( "mouseenter" ); }; jQuery.fn[ "mouseleave" ] = function( fn ) { /// <summary> /// Bind a function to the mouseleave event of each matched element. /// </summary> /// <param name="fn" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return fn ? this.bind( "mouseleave", fn ) : this.trigger( "mouseleave" ); }; jQuery.fn[ "change" ] = function( fn ) { /// <summary> /// 1: change() - Triggers the change event of each matched element. /// 2: change(fn) - Binds a function to the change event of each matched element. /// </summary> /// <param name="fn" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return fn ? this.bind( "change", fn ) : this.trigger( "change" ); }; jQuery.fn[ "select" ] = function( fn ) { /// <summary> /// 1: select() - Triggers the select event of each matched element. /// 2: select(fn) - Binds a function to the select event of each matched element. /// </summary> /// <param name="fn" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return fn ? this.bind( "select", fn ) : this.trigger( "select" ); }; jQuery.fn[ "submit" ] = function( fn ) { /// <summary> /// 1: submit() - Triggers the submit event of each matched element. /// 2: submit(fn) - Binds a function to the submit event of each matched element. /// </summary> /// <param name="fn" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return fn ? this.bind( "submit", fn ) : this.trigger( "submit" ); }; jQuery.fn[ "keydown" ] = function( fn ) { /// <summary> /// 1: keydown() - Triggers the keydown event of each matched element. /// 2: keydown(fn) - Binds a function to the keydown event of each matched element. /// </summary> /// <param name="fn" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return fn ? this.bind( "keydown", fn ) : this.trigger( "keydown" ); }; jQuery.fn[ "keypress" ] = function( fn ) { /// <summary> /// 1: keypress() - Triggers the keypress event of each matched element. /// 2: keypress(fn) - Binds a function to the keypress event of each matched element. /// </summary> /// <param name="fn" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return fn ? this.bind( "keypress", fn ) : this.trigger( "keypress" ); }; jQuery.fn[ "keyup" ] = function( fn ) { /// <summary> /// 1: keyup() - Triggers the keyup event of each matched element. /// 2: keyup(fn) - Binds a function to the keyup event of each matched element. /// </summary> /// <param name="fn" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return fn ? this.bind( "keyup", fn ) : this.trigger( "keyup" ); }; jQuery.fn[ "error" ] = function( fn ) { /// <summary> /// 1: error() - Triggers the error event of each matched element. /// 2: error(fn) - Binds a function to the error event of each matched element. /// </summary> /// <param name="fn" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return fn ? this.bind( "error", fn ) : this.trigger( "error" ); }; // Prevent memory leaks in IE // Window isn't included so as not to unbind existing unload events // More info: // - http://isaacschlueter.com/2006/10/msie-memory-leaks/ if ( window.attachEvent && !window.addEventListener ) { window.attachEvent("onunload", function() { for ( var id in jQuery.cache ) { if ( jQuery.cache[ id ].handle ) { // Try/Catch is to handle iframes being unloaded, see #4280 try { jQuery.event.remove( jQuery.cache[ id ].handle.elem ); } catch(e) {} } } }); } /*! * Sizzle CSS Selector Engine - v1.0 * Copyright 2009, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * More information: http://sizzlejs.com/ */ (function(){ var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, done = 0, toString = Object.prototype.toString, hasDuplicate = false, baseHasDuplicate = true; // Here we check if the JavaScript engine is using some sort of // optimization where it does not always call our comparision // function. If that is the case, discard the hasDuplicate value. // Thus far that includes Google Chrome. [0, 0].sort(function(){ baseHasDuplicate = false; return 0; }); var Sizzle = function(selector, context, results, seed) { results = results || []; var origContext = context = context || document; if ( context.nodeType !== 1 && context.nodeType !== 9 ) { return []; } if ( !selector || typeof selector !== "string" ) { return results; } var parts = [], m, set, checkSet, extra, prune = true, contextXML = isXML(context), soFar = selector; // Reset the position of the chunker regexp (start from head) while ( (chunker.exec(""), m = chunker.exec(soFar)) !== null ) { soFar = m[3]; parts.push( m[1] ); if ( m[2] ) { extra = m[3]; break; } } if ( parts.length > 1 && origPOS.exec( selector ) ) { if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { set = posProcess( parts[0] + parts[1], context ); } else { set = Expr.relative[ parts[0] ] ? [ context ] : Sizzle( parts.shift(), context ); while ( parts.length ) { selector = parts.shift(); if ( Expr.relative[ selector ] ) { selector += parts.shift(); } set = posProcess( selector, set ); } } } else { // Take a shortcut and set the context if the root selector is an ID // (but not if it'll be faster if the inner selector is an ID) if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) { var ret = Sizzle.find( parts.shift(), context, contextXML ); context = ret.expr ? Sizzle.filter( ret.expr, ret.set )[0] : ret.set[0]; } if ( context ) { var ret = seed ? { expr: parts.pop(), set: makeArray(seed) } : Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); set = ret.expr ? Sizzle.filter( ret.expr, ret.set ) : ret.set; if ( parts.length > 0 ) { checkSet = makeArray(set); } else { prune = false; } while ( parts.length ) { var cur = parts.pop(), pop = cur; if ( !Expr.relative[ cur ] ) { cur = ""; } else { pop = parts.pop(); } if ( pop == null ) { pop = context; } Expr.relative[ cur ]( checkSet, pop, contextXML ); } } else { checkSet = parts = []; } } if ( !checkSet ) { checkSet = set; } if ( !checkSet ) { Sizzle.error( cur || selector ); } if ( toString.call(checkSet) === "[object Array]" ) { if ( !prune ) { results.push.apply( results, checkSet ); } else if ( context && context.nodeType === 1 ) { for ( var i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && contains(context, checkSet[i])) ) { results.push( set[i] ); } } } else { for ( var i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && checkSet[i].nodeType === 1 ) { results.push( set[i] ); } } } } else { makeArray( checkSet, results ); } if ( extra ) { Sizzle( extra, origContext, results, seed ); Sizzle.uniqueSort( results ); } return results; }; Sizzle.uniqueSort = function(results){ /// <summary> /// Removes all duplicate elements from an array of elements. /// </summary> /// <param name="array" type="Array&lt;Element&gt;">The array to translate</param> /// <returns type="Array&lt;Element&gt;">The array after translation.</returns> if ( sortOrder ) { hasDuplicate = baseHasDuplicate; results.sort(sortOrder); if ( hasDuplicate ) { for ( var i = 1; i < results.length; i++ ) { if ( results[i] === results[i-1] ) { results.splice(i--, 1); } } } } return results; }; Sizzle.matches = function(expr, set){ return Sizzle(expr, null, null, set); }; Sizzle.find = function(expr, context, isXML){ var set, match; if ( !expr ) { return []; } for ( var i = 0, l = Expr.order.length; i < l; i++ ) { var type = Expr.order[i], match; if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { var left = match[1]; match.splice(1,1); if ( left.substr( left.length - 1 ) !== "\\" ) { match[1] = (match[1] || "").replace(/\\/g, ""); set = Expr.find[ type ]( match, context, isXML ); if ( set != null ) { expr = expr.replace( Expr.match[ type ], "" ); break; } } } } if ( !set ) { set = context.getElementsByTagName("*"); } return {set: set, expr: expr}; }; Sizzle.filter = function(expr, set, inplace, not){ var old = expr, result = [], curLoop = set, match, anyFound, isXMLFilter = set && set[0] && isXML(set[0]); while ( expr && set.length ) { for ( var type in Expr.filter ) { if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { var filter = Expr.filter[ type ], found, item, left = match[1]; anyFound = false; match.splice(1,1); if ( left.substr( left.length - 1 ) === "\\" ) { continue; } if ( curLoop === result ) { result = []; } if ( Expr.preFilter[ type ] ) { match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); if ( !match ) { anyFound = found = true; } else if ( match === true ) { continue; } } if ( match ) { for ( var i = 0; (item = curLoop[i]) != null; i++ ) { if ( item ) { found = filter( item, match, i, curLoop ); var pass = not ^ !!found; if ( inplace && found != null ) { if ( pass ) { anyFound = true; } else { curLoop[i] = false; } } else if ( pass ) { result.push( item ); anyFound = true; } } } } if ( found !== undefined ) { if ( !inplace ) { curLoop = result; } expr = expr.replace( Expr.match[ type ], "" ); if ( !anyFound ) { return []; } break; } } } // Improper expression if ( expr === old ) { if ( anyFound == null ) { Sizzle.error( expr ); } else { break; } } old = expr; } return curLoop; }; Sizzle.error = function( msg ) { throw "Syntax error, unrecognized expression: " + msg; }; var Expr = Sizzle.selectors = { order: [ "ID", "NAME", "TAG" ], match: { ID: /#((?:[\w\u00c0-\uFFFF-]|\\.)+)/, CLASS: /\.((?:[\w\u00c0-\uFFFF-]|\\.)+)/, NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF-]|\\.)+)['"]*\]/, ATTR: /\[\s*((?:[\w\u00c0-\uFFFF-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/, TAG: /^((?:[\w\u00c0-\uFFFF\*-]|\\.)+)/, CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/, POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/, PSEUDO: /:((?:[\w\u00c0-\uFFFF-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/ }, leftMatch: {}, attrMap: { "class": "className", "for": "htmlFor" }, attrHandle: { href: function(elem){ return elem.getAttribute("href"); } }, relative: { "+": function(checkSet, part){ var isPartStr = typeof part === "string", isTag = isPartStr && !/\W/.test(part), isPartStrNotTag = isPartStr && !isTag; if ( isTag ) { part = part.toLowerCase(); } for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { if ( (elem = checkSet[i]) ) { while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ? elem || false : elem === part; } } if ( isPartStrNotTag ) { Sizzle.filter( part, checkSet, true ); } }, ">": function(checkSet, part){ var isPartStr = typeof part === "string"; if ( isPartStr && !/\W/.test(part) ) { part = part.toLowerCase(); for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { var parent = elem.parentNode; checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; } } } else { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { checkSet[i] = isPartStr ? elem.parentNode : elem.parentNode === part; } } if ( isPartStr ) { Sizzle.filter( part, checkSet, true ); } } }, "": function(checkSet, part, isXML){ var doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !/\W/.test(part) ) { var nodeCheck = part = part.toLowerCase(); checkFn = dirNodeCheck; } checkFn("parentNode", part, doneName, checkSet, nodeCheck, isXML); }, "~": function(checkSet, part, isXML){ var doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !/\W/.test(part) ) { var nodeCheck = part = part.toLowerCase(); checkFn = dirNodeCheck; } checkFn("previousSibling", part, doneName, checkSet, nodeCheck, isXML); } }, find: { ID: function(match, context, isXML){ if ( typeof context.getElementById !== "undefined" && !isXML ) { var m = context.getElementById(match[1]); return m ? [m] : []; } }, NAME: function(match, context){ if ( typeof context.getElementsByName !== "undefined" ) { var ret = [], results = context.getElementsByName(match[1]); for ( var i = 0, l = results.length; i < l; i++ ) { if ( results[i].getAttribute("name") === match[1] ) { ret.push( results[i] ); } } return ret.length === 0 ? null : ret; } }, TAG: function(match, context){ return context.getElementsByTagName(match[1]); } }, preFilter: { CLASS: function(match, curLoop, inplace, result, not, isXML){ match = " " + match[1].replace(/\\/g, "") + " "; if ( isXML ) { return match; } for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { if ( elem ) { if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n]/g, " ").indexOf(match) >= 0) ) { if ( !inplace ) { result.push( elem ); } } else if ( inplace ) { curLoop[i] = false; } } } return false; }, ID: function(match){ return match[1].replace(/\\/g, ""); }, TAG: function(match, curLoop){ return match[1].toLowerCase(); }, CHILD: function(match){ if ( match[1] === "nth" ) { // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6' var test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec( match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" || !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); // calculate the numbers (first)n+(last) including if they are negative match[2] = (test[1] + (test[2] || 1)) - 0; match[3] = test[3] - 0; } // TODO: Move to normal caching system match[0] = done++; return match; }, ATTR: function(match, curLoop, inplace, result, not, isXML){ var name = match[1].replace(/\\/g, ""); if ( !isXML && Expr.attrMap[name] ) { match[1] = Expr.attrMap[name]; } if ( match[2] === "~=" ) { match[4] = " " + match[4] + " "; } return match; }, PSEUDO: function(match, curLoop, inplace, result, not){ if ( match[1] === "not" ) { // If we're dealing with a complex expression, or a simple one if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) { match[3] = Sizzle(match[3], null, null, curLoop); } else { var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); if ( !inplace ) { result.push.apply( result, ret ); } return false; } } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { return true; } return match; }, POS: function(match){ match.unshift( true ); return match; } }, filters: { enabled: function(elem){ return elem.disabled === false && elem.type !== "hidden"; }, disabled: function(elem){ return elem.disabled === true; }, checked: function(elem){ return elem.checked === true; }, selected: function(elem){ // Accessing this property makes selected-by-default // options in Safari work properly elem.parentNode.selectedIndex; return elem.selected === true; }, parent: function(elem){ return !!elem.firstChild; }, empty: function(elem){ return !elem.firstChild; }, has: function(elem, i, match){ /// <summary> /// Internal use only; use hasClass('class') /// </summary> /// <private /> return !!Sizzle( match[3], elem ).length; }, header: function(elem){ return /h\d/i.test( elem.nodeName ); }, text: function(elem){ return "text" === elem.type; }, radio: function(elem){ return "radio" === elem.type; }, checkbox: function(elem){ return "checkbox" === elem.type; }, file: function(elem){ return "file" === elem.type; }, password: function(elem){ return "password" === elem.type; }, submit: function(elem){ return "submit" === elem.type; }, image: function(elem){ return "image" === elem.type; }, reset: function(elem){ return "reset" === elem.type; }, button: function(elem){ return "button" === elem.type || elem.nodeName.toLowerCase() === "button"; }, input: function(elem){ return /input|select|textarea|button/i.test(elem.nodeName); } }, setFilters: { first: function(elem, i){ return i === 0; }, last: function(elem, i, match, array){ return i === array.length - 1; }, even: function(elem, i){ return i % 2 === 0; }, odd: function(elem, i){ return i % 2 === 1; }, lt: function(elem, i, match){ return i < match[3] - 0; }, gt: function(elem, i, match){ return i > match[3] - 0; }, nth: function(elem, i, match){ return match[3] - 0 === i; }, eq: function(elem, i, match){ return match[3] - 0 === i; } }, filter: { PSEUDO: function(elem, match, i, array){ var name = match[1], filter = Expr.filters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } else if ( name === "contains" ) { return (elem.textContent || elem.innerText || getText([ elem ]) || "").indexOf(match[3]) >= 0; } else if ( name === "not" ) { var not = match[3]; for ( var i = 0, l = not.length; i < l; i++ ) { if ( not[i] === elem ) { return false; } } return true; } else { Sizzle.error( "Syntax error, unrecognized expression: " + name ); } }, CHILD: function(elem, match){ var type = match[1], node = elem; switch (type) { case 'only': case 'first': while ( (node = node.previousSibling) ) { if ( node.nodeType === 1 ) { return false; } } if ( type === "first" ) { return true; } node = elem; case 'last': while ( (node = node.nextSibling) ) { if ( node.nodeType === 1 ) { return false; } } return true; case 'nth': var first = match[2], last = match[3]; if ( first === 1 && last === 0 ) { return true; } var doneName = match[0], parent = elem.parentNode; if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) { var count = 0; for ( node = parent.firstChild; node; node = node.nextSibling ) { if ( node.nodeType === 1 ) { node.nodeIndex = ++count; } } parent.sizcache = doneName; } var diff = elem.nodeIndex - last; if ( first === 0 ) { return diff === 0; } else { return ( diff % first === 0 && diff / first >= 0 ); } } }, ID: function(elem, match){ return elem.nodeType === 1 && elem.getAttribute("id") === match; }, TAG: function(elem, match){ return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match; }, CLASS: function(elem, match){ return (" " + (elem.className || elem.getAttribute("class")) + " ") .indexOf( match ) > -1; }, ATTR: function(elem, match){ var name = match[1], result = Expr.attrHandle[ name ] ? Expr.attrHandle[ name ]( elem ) : elem[ name ] != null ? elem[ name ] : elem.getAttribute( name ), value = result + "", type = match[2], check = match[4]; return result == null ? type === "!=" : type === "=" ? value === check : type === "*=" ? value.indexOf(check) >= 0 : type === "~=" ? (" " + value + " ").indexOf(check) >= 0 : !check ? value && result !== false : type === "!=" ? value !== check : type === "^=" ? value.indexOf(check) === 0 : type === "$=" ? value.substr(value.length - check.length) === check : type === "|=" ? value === check || value.substr(0, check.length + 1) === check + "-" : false; }, POS: function(elem, match, i, array){ var name = match[2], filter = Expr.setFilters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } } } }; var origPOS = Expr.match.POS; for ( var type in Expr.match ) { Expr.match[ type ] = new RegExp( Expr.match[ type ].source + /(?![^\[]*\])(?![^\(]*\))/.source ); Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, function(all, num){ return "\\" + (num - 0 + 1); })); } var makeArray = function(array, results) { array = Array.prototype.slice.call( array, 0 ); if ( results ) { results.push.apply( results, array ); return results; } return array; }; // Perform a simple check to determine if the browser is capable of // converting a NodeList to an array using builtin methods. try { Array.prototype.slice.call( document.documentElement.childNodes, 0 ); // Provide a fallback method if it does not work } catch(e){ makeArray = function(array, results) { var ret = results || []; if ( toString.call(array) === "[object Array]" ) { Array.prototype.push.apply( ret, array ); } else { if ( typeof array.length === "number" ) { for ( var i = 0, l = array.length; i < l; i++ ) { ret.push( array[i] ); } } else { for ( var i = 0; array[i]; i++ ) { ret.push( array[i] ); } } } return ret; }; } var sortOrder; if ( document.documentElement.compareDocumentPosition ) { sortOrder = function( a, b ) { if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { if ( a == b ) { hasDuplicate = true; } return a.compareDocumentPosition ? -1 : 1; } var ret = a.compareDocumentPosition(b) & 4 ? -1 : a === b ? 0 : 1; if ( ret === 0 ) { hasDuplicate = true; } return ret; }; } else if ( "sourceIndex" in document.documentElement ) { sortOrder = function( a, b ) { if ( !a.sourceIndex || !b.sourceIndex ) { if ( a == b ) { hasDuplicate = true; } return a.sourceIndex ? -1 : 1; } var ret = a.sourceIndex - b.sourceIndex; if ( ret === 0 ) { hasDuplicate = true; } return ret; }; } else if ( document.createRange ) { sortOrder = function( a, b ) { if ( !a.ownerDocument || !b.ownerDocument ) { if ( a == b ) { hasDuplicate = true; } return a.ownerDocument ? -1 : 1; } var aRange = a.ownerDocument.createRange(), bRange = b.ownerDocument.createRange(); aRange.setStart(a, 0); aRange.setEnd(a, 0); bRange.setStart(b, 0); bRange.setEnd(b, 0); var ret = aRange.compareBoundaryPoints(Range.START_TO_END, bRange); if ( ret === 0 ) { hasDuplicate = true; } return ret; }; } // Utility function for retreiving the text value of an array of DOM nodes function getText( elems ) { var ret = "", elem; for ( var i = 0; elems[i]; i++ ) { elem = elems[i]; // Get the text from text nodes and CDATA nodes if ( elem.nodeType === 3 || elem.nodeType === 4 ) { ret += elem.nodeValue; // Traverse everything else, except comment nodes } else if ( elem.nodeType !== 8 ) { ret += getText( elem.childNodes ); } } return ret; } // [vsdoc] The following function has been modified for IntelliSense. // Check to see if the browser returns elements by name when // querying by getElementById (and provide a workaround) (function(){ // We're going to inject a fake input element with a specified name // var form = document.createElement("div"), // id = "script" + (new Date).getTime(); // form.innerHTML = "<a name='" + id + "'/>"; // // Inject it into the root element, check its status, and remove it quickly // var root = document.documentElement; // root.insertBefore( form, root.firstChild ); // The workaround has to do additional checks after a getElementById // Which slows things down for other browsers (hence the branching) // if ( document.getElementById( id ) ) { Expr.find.ID = function(match, context, isXML){ if ( typeof context.getElementById !== "undefined" && !isXML ) { var m = context.getElementById(match[1]); return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : []; } }; Expr.filter.ID = function(elem, match){ var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); return elem.nodeType === 1 && node && node.nodeValue === match; }; // } // root.removeChild( form ); root = form = null; // release memory in IE })(); // [vsdoc] The following function has been modified for IntelliSense. (function(){ // Check to see if the browser returns only elements // when doing getElementsByTagName("*") // Create a fake element // var div = document.createElement("div"); // div.appendChild( document.createComment("") ); // Make sure no comments are found // if ( div.getElementsByTagName("*").length > 0 ) { Expr.find.TAG = function(match, context){ var results = context.getElementsByTagName(match[1]); // Filter out possible comments if ( match[1] === "*" ) { var tmp = []; for ( var i = 0; results[i]; i++ ) { if ( results[i].nodeType === 1 ) { tmp.push( results[i] ); } } results = tmp; } return results; }; // } // Check to see if an attribute returns normalized href attributes // div.innerHTML = "<a href='#'></a>"; // if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && // div.firstChild.getAttribute("href") !== "#" ) { Expr.attrHandle.href = function(elem){ return elem.getAttribute("href", 2); }; // } div = null; // release memory in IE })(); if ( document.querySelectorAll ) { (function(){ var oldSizzle = Sizzle, div = document.createElement("div"); div.innerHTML = "<p class='TEST'></p>"; // Safari can't handle uppercase or unicode characters when // in quirks mode. if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) { return; } Sizzle = function(query, context, extra, seed){ context = context || document; // Only use querySelectorAll on non-XML documents // (ID selectors don't work in non-HTML documents) if ( !seed && context.nodeType === 9 && !isXML(context) ) { try { return makeArray( context.querySelectorAll(query), extra ); } catch(e){} } return oldSizzle(query, context, extra, seed); }; for ( var prop in oldSizzle ) { Sizzle[ prop ] = oldSizzle[ prop ]; } div = null; // release memory in IE })(); } (function(){ var div = document.createElement("div"); div.innerHTML = "<div class='test e'></div><div class='test'></div>"; // Opera can't find a second classname (in 9.6) // Also, make sure that getElementsByClassName actually exists if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) { return; } // Safari caches class attributes, doesn't catch changes (in 3.2) div.lastChild.className = "e"; if ( div.getElementsByClassName("e").length === 1 ) { return; } Expr.order.splice(1, 0, "CLASS"); Expr.find.CLASS = function(match, context, isXML) { if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) { return context.getElementsByClassName(match[1]); } }; div = null; // release memory in IE })(); function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { elem = elem[dir]; var match = false; while ( elem ) { if ( elem.sizcache === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 && !isXML ){ elem.sizcache = doneName; elem.sizset = i; } if ( elem.nodeName.toLowerCase() === cur ) { match = elem; break; } elem = elem[dir]; } checkSet[i] = match; } } } function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { elem = elem[dir]; var match = false; while ( elem ) { if ( elem.sizcache === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 ) { if ( !isXML ) { elem.sizcache = doneName; elem.sizset = i; } if ( typeof cur !== "string" ) { if ( elem === cur ) { match = true; break; } } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) { match = elem; break; } } elem = elem[dir]; } checkSet[i] = match; } } } var contains = document.compareDocumentPosition ? function(a, b){ /// <summary> /// Check to see if a DOM node is within another DOM node. /// </summary> /// <param name="a" type="Object"> /// The DOM element that may contain the other element. /// </param> /// <param name="b" type="Object"> /// The DOM node that may be contained by the other element. /// </param> /// <returns type="Boolean" /> return a.compareDocumentPosition(b) & 16; } : function(a, b){ /// <summary> /// Check to see if a DOM node is within another DOM node. /// </summary> /// <param name="a" type="Object"> /// The DOM element that may contain the other element. /// </param> /// <param name="b" type="Object"> /// The DOM node that may be contained by the other element. /// </param> /// <returns type="Boolean" /> return a !== b && (a.contains ? a.contains(b) : true); }; var isXML = function(elem){ /// <summary> /// Determines if the parameter passed is an XML document. /// </summary> /// <param name="elem" type="Object">The object to test</param> /// <returns type="Boolean">True if the parameter is an XML document; otherwise false.</returns> // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; var posProcess = function(selector, context){ var tmpSet = [], later = "", match, root = context.nodeType ? [context] : context; // Position selectors must be done after the filter // And so must :not(positional) so we move all PSEUDOs to the end while ( (match = Expr.match.PSEUDO.exec( selector )) ) { later += match[0]; selector = selector.replace( Expr.match.PSEUDO, "" ); } selector = Expr.relative[selector] ? selector + "*" : selector; for ( var i = 0, l = root.length; i < l; i++ ) { Sizzle( selector, root[i], tmpSet ); } return Sizzle.filter( later, tmpSet ); }; // EXPOSE jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.filters; jQuery.unique = Sizzle.uniqueSort; jQuery.getText = getText; jQuery.isXMLDoc = isXML; jQuery.contains = contains; return; window.Sizzle = Sizzle; })(); var runtil = /Until$/, rparentsprev = /^(?:parents|prevUntil|prevAll)/, // Note: This RegExp should be improved, or likely pulled from Sizzle rmultiselector = /,/, slice = Array.prototype.slice; // Implement the identical functionality for filter and not var winnow = function( elements, qualifier, keep ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep(elements, function( elem, i ) { return !!qualifier.call( elem, i, elem ) === keep; }); } else if ( qualifier.nodeType ) { return jQuery.grep(elements, function( elem, i ) { return (elem === qualifier) === keep; }); } else if ( typeof qualifier === "string" ) { var filtered = jQuery.grep(elements, function( elem ) { return elem.nodeType === 1; }); if ( isSimple.test( qualifier ) ) { return jQuery.filter(qualifier, filtered, !keep); } else { qualifier = jQuery.filter( qualifier, filtered ); } } return jQuery.grep(elements, function( elem, i ) { return (jQuery.inArray( elem, qualifier ) >= 0) === keep; }); }; jQuery.fn.extend({ find: function( selector ) { /// <summary> /// Searches for all elements that match the specified expression. /// This method is a good way to find additional descendant /// elements with which to process. /// All searching is done using a jQuery expression. The expression can be /// written using CSS 1-3 Selector syntax, or basic XPath. /// Part of DOM/Traversing /// </summary> /// <returns type="jQuery" /> /// <param name="selector" type="String"> /// An expression to search with. /// </param> /// <returns type="jQuery" /> var ret = this.pushStack( "", "find", selector ), length = 0; for ( var i = 0, l = this.length; i < l; i++ ) { length = ret.length; jQuery.find( selector, this[i], ret ); if ( i > 0 ) { // Make sure that the results are unique for ( var n = length; n < ret.length; n++ ) { for ( var r = 0; r < length; r++ ) { if ( ret[r] === ret[n] ) { ret.splice(n--, 1); break; } } } } } return ret; }, has: function( target ) { /// <summary> /// Reduce the set of matched elements to those that have a descendant that matches the /// selector or DOM element. /// </summary> /// <param name="target" type="String"> /// A string containing a selector expression to match elements against. /// </param> /// <returns type="jQuery" /> var targets = jQuery( target ); return this.filter(function() { for ( var i = 0, l = targets.length; i < l; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { /// <summary> /// Removes any elements inside the array of elements from the set /// of matched elements. This method is used to remove one or more /// elements from a jQuery object. /// Part of DOM/Traversing /// </summary> /// <param name="selector" type="jQuery"> /// A set of elements to remove from the jQuery set of matched elements. /// </param> /// <returns type="jQuery" /> return this.pushStack( winnow(this, selector, false), "not", selector); }, filter: function( selector ) { /// <summary> /// Removes all elements from the set of matched elements that do not /// pass the specified filter. This method is used to narrow down /// the results of a search. /// }) /// Part of DOM/Traversing /// </summary> /// <returns type="jQuery" /> /// <param name="selector" type="Function"> /// A function to use for filtering /// </param> /// <returns type="jQuery" /> return this.pushStack( winnow(this, selector, true), "filter", selector ); }, is: function( selector ) { /// <summary> /// Checks the current selection against an expression and returns true, /// if at least one element of the selection fits the given expression. /// Does return false, if no element fits or the expression is not valid. /// filter(String) is used internally, therefore all rules that apply there /// apply here, too. /// Part of DOM/Traversing /// </summary> /// <returns type="Boolean" /> /// <param name="expr" type="String"> /// The expression with which to filter /// </param> return !!selector && jQuery.filter( selector, this ).length > 0; }, closest: function( selectors, context ) { /// <summary> /// Get a set of elements containing the closest parent element that matches the specified selector, the starting element included. /// </summary> /// <param name="selectors" type="String"> /// A string containing a selector expression to match elements against. /// </param> /// <param name="context" type="Element"> /// A DOM element within which a matching element may be found. If no context is passed /// in then the context of the jQuery set will be used instead. /// </param> /// <returns type="jQuery" /> if ( jQuery.isArray( selectors ) ) { var ret = [], cur = this[0], match, matches = {}, selector; if ( cur && selectors.length ) { for ( var i = 0, l = selectors.length; i < l; i++ ) { selector = selectors[i]; if ( !matches[selector] ) { matches[selector] = jQuery.expr.match.POS.test( selector ) ? jQuery( selector, context || this.context ) : selector; } } while ( cur && cur.ownerDocument && cur !== context ) { for ( selector in matches ) { match = matches[selector]; if ( match.jquery ? match.index(cur) > -1 : jQuery(cur).is(match) ) { ret.push({ selector: selector, elem: cur }); delete matches[selector]; } } cur = cur.parentNode; } } return ret; } var pos = jQuery.expr.match.POS.test( selectors ) ? jQuery( selectors, context || this.context ) : null; return this.map(function( i, cur ) { while ( cur && cur.ownerDocument && cur !== context ) { if ( pos ? pos.index(cur) > -1 : jQuery(cur).is(selectors) ) { return cur; } cur = cur.parentNode; } return null; }); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { /// <summary> /// Searches every matched element for the object and returns /// the index of the element, if found, starting with zero. /// Returns -1 if the object wasn't found. /// Part of Core /// </summary> /// <returns type="Number" /> /// <param name="elem" type="Element"> /// Object to search for /// </param> if ( !elem || typeof elem === "string" ) { return jQuery.inArray( this[0], // If it receives a string, the selector is used // If it receives nothing, the siblings are used elem ? jQuery( elem ) : this.parent().children() ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this ); }, add: function( selector, context ) { /// <summary> /// Adds one or more Elements to the set of matched elements. /// Part of DOM/Traversing /// </summary> /// <param name="selector" type="String"> /// A string containing a selector expression to match additional elements against. /// </param> /// <param name="context" type="Element"> /// Add some elements rooted against the specified context. /// </param> /// <returns type="jQuery" /> var set = typeof selector === "string" ? jQuery( selector, context || this.context ) : jQuery.makeArray( selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? all : jQuery.unique( all ) ); }, andSelf: function() { /// <summary> /// Adds the previous selection to the current selection. /// </summary> /// <returns type="jQuery" /> return this.add( this.prevObject ); } }); // A painfully simple check to see if an element is disconnected // from a document (should be improved, where feasible). function isDisconnected( node ) { return !node || !node.parentNode || node.parentNode.nodeType === 11; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, next: function( elem ) { return jQuery.nth( elem, 2, "nextSibling" ); }, prev: function( elem ) { return jQuery.nth( elem, 2, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, siblings: function( elem ) { return jQuery.sibling( elem.parentNode.firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.makeArray( elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ); if ( !runtil.test( name ) ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } ret = this.length > 1 ? jQuery.unique( ret ) : ret; if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) { ret = ret.reverse(); } return this.pushStack( ret, name, slice.call(arguments).join(",") ); }; }); jQuery.fn[ "parentsUntil" ] = function( until, selector ) { /// <summary> /// Get the ancestors of each element in the current set of matched elements, up to but not /// including the element matched by the selector. /// </summary> /// <param name="until" type="String"> /// A string containing a selector expression to indicate where to stop matching ancestor /// elements. /// </param> /// <returns type="jQuery" /> var fn = function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); } var ret = jQuery.map( this, fn, until ); if ( !runtil.test( "parentsUntil" ) ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } ret = this.length > 1 ? jQuery.unique( ret ) : ret; if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( "parentsUntil" ) ) { ret = ret.reverse(); } return this.pushStack( ret, "parentsUntil", slice.call(arguments).join(",") ); }; jQuery.fn[ "nextUntil" ] = function( until, selector ) { /// <summary> /// Get all following siblings of each element up to but not including the element matched /// by the selector. /// </summary> /// <param name="until" type="String"> /// A string containing a selector expression to indicate where to stop matching following /// sibling elements. /// </param> /// <returns type="jQuery" /> var fn = function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); } var ret = jQuery.map( this, fn, until ); if ( !runtil.test( "nextUntil" ) ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } ret = this.length > 1 ? jQuery.unique( ret ) : ret; if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( "nextUntil" ) ) { ret = ret.reverse(); } return this.pushStack( ret, "nextUntil", slice.call(arguments).join(",") ); }; jQuery.fn[ "prevUntil" ] = function( until, selector ) { /// <summary> /// Get all preceding siblings of each element up to but not including the element matched /// by the selector. /// </summary> /// <param name="until" type="String"> /// A string containing a selector expression to indicate where to stop matching preceding /// sibling elements. /// </param> /// <returns type="jQuery" /> var fn = function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); } var ret = jQuery.map( this, fn, until ); if ( !runtil.test( "prevUntil" ) ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } ret = this.length > 1 ? jQuery.unique( ret ) : ret; if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( "prevUntil" ) ) { ret = ret.reverse(); } return this.pushStack( ret, "prevUntil", slice.call(arguments).join(",") ); }; jQuery.extend({ filter: function( expr, elems, not ) { if ( not ) { expr = ":not(" + expr + ")"; } return jQuery.find.matches(expr, elems); }, dir: function( elem, dir, until ) { /// <summary> /// This member is internal only. /// </summary> /// <private /> var matched = [], cur = elem[dir]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, nth: function( cur, result, dir, elem ) { /// <summary> /// This member is internal only. /// </summary> /// <private /> result = result || 1; var num = 0; for ( ; cur; cur = cur[dir] ) { if ( cur.nodeType === 1 && ++num === result ) { break; } } return cur; }, sibling: function( n, elem ) { /// <summary> /// This member is internal only. /// </summary> /// <private /> var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); var rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g, rleadingWhitespace = /^\s+/, rxhtmlTag = /(<([\w:]+)[^>]*?)\/>/g, rselfClosing = /^(?:area|br|col|embed|hr|img|input|link|meta|param)$/i, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&\w+;/, rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, // checked="checked" or checked (html5) fcloseTag = function( all, front, tag ) { return rselfClosing.test( tag ) ? all : front + "></" + tag + ">"; }, wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], area: [ 1, "<map>", "</map>" ], _default: [ 0, "", "" ] }; wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; // IE can't serialize <link> and <script> tags normally if ( !jQuery.support.htmlSerialize ) { wrapMap._default = [ 1, "div<div>", "</div>" ]; } jQuery.fn.extend({ text: function( text ) { /// <summary> /// Set the text contents of all matched elements. /// Similar to html(), but escapes HTML (replace &quot;&lt;&quot; and &quot;&gt;&quot; with their /// HTML entities). /// Part of DOM/Attributes /// </summary> /// <returns type="jQuery" /> /// <param name="text" type="String"> /// The text value to set the contents of the element to. /// </param> if ( jQuery.isFunction(text) ) { return this.each(function(i) { var self = jQuery(this); self.text( text.call(this, i, self.text()) ); }); } if ( typeof text !== "object" && text !== undefined ) { return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) ); } return jQuery.getText( this ); }, wrapAll: function( html ) { /// <summary> /// Wrap all matched elements with a structure of other elements. /// This wrapping process is most useful for injecting additional /// stucture into a document, without ruining the original semantic /// qualities of a document. /// This works by going through the first element /// provided and finding the deepest ancestor element within its /// structure - it is that element that will en-wrap everything else. /// This does not work with elements that contain text. Any necessary text /// must be added after the wrapping is done. /// Part of DOM/Manipulation /// </summary> /// <returns type="jQuery" /> /// <param name="html" type="Element"> /// A DOM element that will be wrapped around the target. /// </param> if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapAll( html.call(this, i) ); }); } if ( this[0] ) { // The elements to wrap the target around var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); if ( this[0].parentNode ) { wrap.insertBefore( this[0] ); } wrap.map(function() { var elem = this; while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { elem = elem.firstChild; } return elem; }).append(this); } return this; }, wrapInner: function( html ) { /// <summary> /// Wraps the inner child contents of each matched elemenht (including text nodes) with an HTML structure. /// </summary> /// <param name="html" type="String"> /// A string of HTML or a DOM element that will be wrapped around the target contents. /// </param> /// <returns type="jQuery" /> if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { /// <summary> /// Wrap all matched elements with a structure of other elements. /// This wrapping process is most useful for injecting additional /// stucture into a document, without ruining the original semantic /// qualities of a document. /// This works by going through the first element /// provided and finding the deepest ancestor element within its /// structure - it is that element that will en-wrap everything else. /// This does not work with elements that contain text. Any necessary text /// must be added after the wrapping is done. /// Part of DOM/Manipulation /// </summary> /// <returns type="jQuery" /> /// <param name="html" type="Element"> /// A DOM element that will be wrapped around the target. /// </param> return this.each(function() { jQuery( this ).wrapAll( html ); }); }, unwrap: function() { /// <summary> /// Remove the parents of the set of matched elements from the DOM, leaving the matched /// elements in their place. /// </summary> /// <returns type="jQuery" /> return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); }, append: function() { /// <summary> /// Append content to the inside of every matched element. /// This operation is similar to doing an appendChild to all the /// specified elements, adding them into the document. /// Part of DOM/Manipulation /// </summary> /// <returns type="jQuery" /> return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 ) { this.appendChild( elem ); } }); }, prepend: function() { /// <summary> /// Prepend content to the inside of every matched element. /// This operation is the best way to insert elements /// inside, at the beginning, of all matched elements. /// Part of DOM/Manipulation /// </summary> /// <returns type="jQuery" /> return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 ) { this.insertBefore( elem, this.firstChild ); } }); }, before: function() { /// <summary> /// Insert content before each of the matched elements. /// Part of DOM/Manipulation /// </summary> /// <returns type="jQuery" /> if ( this[0] && this[0].parentNode ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this ); }); } else if ( arguments.length ) { var set = jQuery(arguments[0]); set.push.apply( set, this.toArray() ); return this.pushStack( set, "before", arguments ); } }, after: function() { /// <summary> /// Insert content after each of the matched elements. /// Part of DOM/Manipulation /// </summary> /// <returns type="jQuery" /> if ( this[0] && this[0].parentNode ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this.nextSibling ); }); } else if ( arguments.length ) { var set = this.pushStack( this, "after", arguments ); set.push.apply( set, jQuery(arguments[0]).toArray() ); return set; } }, clone: function( events ) { /// <summary> /// Clone matched DOM Elements and select the clones. /// This is useful for moving copies of the elements to another /// location in the DOM. /// Part of DOM/Manipulation /// </summary> /// <returns type="jQuery" /> /// <param name="deep" type="Boolean" optional="true"> /// (Optional) Set to false if you don't want to clone all descendant nodes, in addition to the element itself. /// </param> // Do the clone var ret = this.map(function() { if ( !jQuery.support.noCloneEvent && !jQuery.isXMLDoc(this) ) { // IE copies events bound via attachEvent when // using cloneNode. Calling detachEvent on the // clone will also remove the events from the orignal // In order to get around this, we use innerHTML. // Unfortunately, this means some modifications to // attributes in IE that are actually only stored // as properties will not be copied (such as the // the name attribute on an input). var html = this.outerHTML, ownerDocument = this.ownerDocument; if ( !html ) { var div = ownerDocument.createElement("div"); div.appendChild( this.cloneNode(true) ); html = div.innerHTML; } return jQuery.clean([html.replace(rinlinejQuery, "") .replace(rleadingWhitespace, "")], ownerDocument)[0]; } else { return this.cloneNode(true); } }); // Copy the events from the original to the clone if ( events === true ) { cloneCopyEvent( this, ret ); cloneCopyEvent( this.find("*"), ret.find("*") ); } // Return the cloned set return ret; }, html: function( value ) { /// <summary> /// Set the html contents of every matched element. /// This property is not available on XML documents. /// Part of DOM/Attributes /// </summary> /// <returns type="jQuery" /> /// <param name="value" type="String"> /// A string of HTML to set as the content of each matched element. /// </param> if ( value === undefined ) { return this[0] && this[0].nodeType === 1 ? this[0].innerHTML.replace(rinlinejQuery, "") : null; // See if we can take a shortcut and just use innerHTML } else if ( typeof value === "string" && !/<script/i.test( value ) && (jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) && !wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) { value = value.replace(rxhtmlTag, fcloseTag); try { for ( var i = 0, l = this.length; i < l; i++ ) { // Remove element nodes and prevent memory leaks if ( this[i].nodeType === 1 ) { jQuery.cleanData( this[i].getElementsByTagName("*") ); this[i].innerHTML = value; } } // If using innerHTML throws an exception, use the fallback method } catch(e) { this.empty().append( value ); } } else if ( jQuery.isFunction( value ) ) { this.each(function(i){ var self = jQuery(this), old = self.html(); self.empty().append(function(){ return value.call( this, i, old ); }); }); } else { this.empty().append( value ); } return this; }, replaceWith: function( value ) { /// <summary> /// Replaces all matched element with the specified HTML or DOM elements. /// </summary> /// <param name="value" type="Object"> /// The content to insert. May be an HTML string, DOM element, or jQuery object. /// </param> /// <returns type="jQuery">The element that was just replaced.</returns> if ( this[0] && this[0].parentNode ) { // Make sure that the elements are removed from the DOM before they are inserted // this can help fix replacing a parent with child elements if ( !jQuery.isFunction( value ) ) { value = jQuery( value ).detach(); } else { return this.each(function(i) { var self = jQuery(this), old = self.html(); self.replaceWith( value.call( this, i, old ) ); }); } return this.each(function() { var next = this.nextSibling, parent = this.parentNode; jQuery(this).remove(); if ( next ) { jQuery(next).before( value ); } else { jQuery(parent).append( value ); } }); } else { return this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ); } }, detach: function( selector ) { /// <summary> /// Remove the set of matched elements from the DOM. /// </summary> /// <param name="selector" type="String"> /// A selector expression that filters the set of matched elements to be removed. /// </param> /// <returns type="jQuery" /> return this.remove( selector, true ); }, domManip: function( args, table, callback ) { /// <param name="args" type="Array"> /// Args /// </param> /// <param name="table" type="Boolean"> /// Insert TBODY in TABLEs if one is not found. /// </param> /// <param name="dir" type="Number"> /// If dir&lt;0, process args in reverse order. /// </param> /// <param name="fn" type="Function"> /// The function doing the DOM manipulation. /// </param> /// <returns type="jQuery" /> /// <summary> /// Part of Core /// </summary> var results, first, value = args[0], scripts = []; // We can't cloneNode fragments that contain checked, in WebKit if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) { return this.each(function() { jQuery(this).domManip( args, table, callback, true ); }); } if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); args[0] = value.call(this, i, table ? self.html() : undefined); self.domManip( args, table, callback ); }); } if ( this[0] ) { // If we're in a fragment, just use that instead of building a new one if ( args[0] && args[0].parentNode && args[0].parentNode.nodeType === 11 ) { results = { fragment: args[0].parentNode }; } else { results = buildFragment( args, this, scripts ); } first = results.fragment.firstChild; if ( first ) { table = table && jQuery.nodeName( first, "tr" ); for ( var i = 0, l = this.length; i < l; i++ ) { callback.call( table ? root(this[i], first) : this[i], results.cacheable || this.length > 1 || i > 0 ? results.fragment.cloneNode(true) : results.fragment ); } } if ( scripts ) { jQuery.each( scripts, evalScript ); } } return this; function root( elem, cur ) { return jQuery.nodeName(elem, "table") ? (elem.getElementsByTagName("tbody")[0] || elem.appendChild(elem.ownerDocument.createElement("tbody"))) : elem; } } }); function cloneCopyEvent(orig, ret) { var i = 0; ret.each(function() { if ( this.nodeName !== (orig[i] && orig[i].nodeName) ) { return; } var oldData = jQuery.data( orig[i++] ), curData = jQuery.data( this, oldData ), events = oldData && oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( var type in events ) { for ( var handler in events[ type ] ) { jQuery.event.add( this, type, events[ type ][ handler ], events[ type ][ handler ].data ); } } } }); } function buildFragment( args, nodes, scripts ) { var fragment, cacheable, cacheresults, doc; // webkit does not clone 'checked' attribute of radio inputs on cloneNode, so don't cache if string has a checked if ( args.length === 1 && typeof args[0] === "string" && args[0].length < 512 && args[0].indexOf("<option") < 0 && (jQuery.support.checkClone || !rchecked.test( args[0] )) ) { cacheable = true; cacheresults = jQuery.fragments[ args[0] ]; if ( cacheresults ) { if ( cacheresults !== 1 ) { fragment = cacheresults; } } } if ( !fragment ) { doc = (nodes && nodes[0] ? nodes[0].ownerDocument || nodes[0] : document); fragment = doc.createDocumentFragment(); jQuery.clean( args, doc, fragment, scripts ); } if ( cacheable ) { jQuery.fragments[ args[0] ] = cacheresults ? fragment : 1; } return { fragment: fragment, cacheable: cacheable }; } jQuery.fragments = {}; // jQuery.each({ // appendTo: "append", // prependTo: "prepend", // insertBefore: "before", // insertAfter: "after", // replaceAll: "replaceWith" // }, function( name, original ) { // jQuery.fn[ name ] = function( selector ) { // var ret = [], insert = jQuery( selector ); // for ( var i = 0, l = insert.length; i < l; i++ ) { // var elems = (i > 0 ? this.clone(true) : this).get(); // jQuery.fn[ original ].apply( jQuery(insert[i]), elems ); // ret = ret.concat( elems ); // } // return this.pushStack( ret, name, insert.selector ); // }; // }); jQuery.fn[ "appendTo" ] = function( selector ) { /// <summary> /// Append all of the matched elements to another, specified, set of elements. /// As of jQuery 1.3.2, returns all of the inserted elements. /// This operation is, essentially, the reverse of doing a regular /// $(A).append(B), in that instead of appending B to A, you're appending /// A to B. /// </summary> /// <param name="selector" type="Selector"> /// target to which the content will be appended. /// </param> /// <returns type="jQuery" /> var ret = [], insert = jQuery( selector ); for ( var i = 0, l = insert.length; i < l; i++ ) { var elems = (i > 0 ? this.clone(true) : this).get(); jQuery.fn[ "append" ].apply( jQuery(insert[i]), elems ); ret = ret.concat( elems ); } return this.pushStack( ret, "appendTo", insert.selector ); }; jQuery.fn[ "prependTo" ] = function( selector ) { /// <summary> /// Prepend all of the matched elements to another, specified, set of elements. /// As of jQuery 1.3.2, returns all of the inserted elements. /// This operation is, essentially, the reverse of doing a regular /// $(A).prepend(B), in that instead of prepending B to A, you're prepending /// A to B. /// </summary> /// <param name="selector" type="Selector"> /// target to which the content will be appended. /// </param> /// <returns type="jQuery" /> var ret = [], insert = jQuery( selector ); for ( var i = 0, l = insert.length; i < l; i++ ) { var elems = (i > 0 ? this.clone(true) : this).get(); jQuery.fn[ "prepend" ].apply( jQuery(insert[i]), elems ); ret = ret.concat( elems ); } return this.pushStack( ret, "prependTo", insert.selector ); }; jQuery.fn[ "insertBefore" ] = function( selector ) { /// <summary> /// Insert all of the matched elements before another, specified, set of elements. /// As of jQuery 1.3.2, returns all of the inserted elements. /// This operation is, essentially, the reverse of doing a regular /// $(A).before(B), in that instead of inserting B before A, you're inserting /// A before B. /// </summary> /// <param name="content" type="String"> /// Content after which the selected element(s) is inserted. /// </param> /// <returns type="jQuery" /> var ret = [], insert = jQuery( selector ); for ( var i = 0, l = insert.length; i < l; i++ ) { var elems = (i > 0 ? this.clone(true) : this).get(); jQuery.fn[ "before" ].apply( jQuery(insert[i]), elems ); ret = ret.concat( elems ); } return this.pushStack( ret, "insertBefore", insert.selector ); }; jQuery.fn[ "insertAfter" ] = function( selector ) { /// <summary> /// Insert all of the matched elements after another, specified, set of elements. /// As of jQuery 1.3.2, returns all of the inserted elements. /// This operation is, essentially, the reverse of doing a regular /// $(A).after(B), in that instead of inserting B after A, you're inserting /// A after B. /// </summary> /// <param name="content" type="String"> /// Content after which the selected element(s) is inserted. /// </param> /// <returns type="jQuery" /> var ret = [], insert = jQuery( selector ); for ( var i = 0, l = insert.length; i < l; i++ ) { var elems = (i > 0 ? this.clone(true) : this).get(); jQuery.fn[ "after" ].apply( jQuery(insert[i]), elems ); ret = ret.concat( elems ); } return this.pushStack( ret, "insertAfter", insert.selector ); }; jQuery.fn[ "replaceAll" ] = function( selector ) { /// <summary> /// Replaces the elements matched by the specified selector with the matched elements. /// As of jQuery 1.3.2, returns all of the inserted elements. /// </summary> /// <param name="selector" type="Selector">The elements to find and replace the matched elements with.</param> /// <returns type="jQuery" /> var ret = [], insert = jQuery( selector ); for ( var i = 0, l = insert.length; i < l; i++ ) { var elems = (i > 0 ? this.clone(true) : this).get(); jQuery.fn[ "replaceWith" ].apply( jQuery(insert[i]), elems ); ret = ret.concat( elems ); } return this.pushStack( ret, "replaceAll", insert.selector ); }; jQuery.each({ // keepData is for internal use only--do not document remove: function( selector, keepData ) { if ( !selector || jQuery.filter( selector, [ this ] ).length ) { if ( !keepData && this.nodeType === 1 ) { jQuery.cleanData( this.getElementsByTagName("*") ); jQuery.cleanData( [ this ] ); } if ( this.parentNode ) { this.parentNode.removeChild( this ); } } }, empty: function() { /// <summary> /// Removes all child nodes from the set of matched elements. /// Part of DOM/Manipulation /// </summary> /// <returns type="jQuery" /> // Remove element nodes and prevent memory leaks if ( this.nodeType === 1 ) { jQuery.cleanData( this.getElementsByTagName("*") ); } // Remove any remaining nodes while ( this.firstChild ) { this.removeChild( this.firstChild ); } } }, function( name, fn ) { jQuery.fn[ name ] = function() { return this.each( fn, arguments ); }; }); jQuery.extend({ clean: function( elems, context, fragment, scripts ) { /// <summary> /// This method is internal only. /// </summary> /// <private /> context = context || document; // !context.createElement fails in IE with an error but returns typeof 'object' if ( typeof context.createElement === "undefined" ) { context = context.ownerDocument || context[0] && context[0].ownerDocument || document; } var ret = []; jQuery.each(elems, function( i, elem ) { if ( typeof elem === "number" ) { elem += ""; } if ( !elem ) { return; } // Convert html string into DOM nodes if ( typeof elem === "string" && !rhtml.test( elem ) ) { elem = context.createTextNode( elem ); } else if ( typeof elem === "string" ) { // Fix "XHTML"-style tags in all browsers elem = elem.replace(rxhtmlTag, fcloseTag); // Trim whitespace, otherwise indexOf won't work as expected var tag = (rtagName.exec( elem ) || ["", ""])[1].toLowerCase(), wrap = wrapMap[ tag ] || wrapMap._default, depth = wrap[0], div = context.createElement("div"); // Go to html and back, then peel off extra wrappers div.innerHTML = wrap[1] + elem + wrap[2]; // Move to the right depth while ( depth-- ) { div = div.lastChild; } // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.support.tbody ) { // String was a <table>, *may* have spurious <tbody> var hasBody = rtbody.test(elem), tbody = tag === "table" && !hasBody ? div.firstChild && div.firstChild.childNodes : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !hasBody ? div.childNodes : []; for ( var j = tbody.length - 1; j >= 0 ; --j ) { if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) { tbody[ j ].parentNode.removeChild( tbody[ j ] ); } } } // IE completely kills leading whitespace when innerHTML is used if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild ); } elem = jQuery.makeArray( div.childNodes ); } if ( elem.nodeType ) { ret.push( elem ); } else { ret = jQuery.merge( ret, elem ); } }); if ( fragment ) { for ( var i = 0; ret[i]; i++ ) { if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) { scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] ); } else { if ( ret[i].nodeType === 1 ) { ret.splice.apply( ret, [i + 1, 0].concat(jQuery.makeArray(ret[i].getElementsByTagName("script"))) ); } fragment.appendChild( ret[i] ); } } } return ret; }, cleanData: function( elems ) { for ( var i = 0, elem, id; (elem = elems[i]) != null; i++ ) { jQuery.event.remove( elem ); jQuery.removeData( elem ); } } }); // exclude the following css properties to add px var rexclude = /z-?index|font-?weight|opacity|zoom|line-?height/i, ralpha = /alpha\([^)]*\)/, ropacity = /opacity=([^)]*)/, rfloat = /float/i, rdashAlpha = /-([a-z])/ig, rupper = /([A-Z])/g, rnumpx = /^-?\d+(?:px)?$/i, rnum = /^-?\d/, cssShow = { position: "absolute", visibility: "hidden", display:"block" }, cssWidth = [ "Left", "Right" ], cssHeight = [ "Top", "Bottom" ], // cache check for defaultView.getComputedStyle getComputedStyle = document.defaultView && document.defaultView.getComputedStyle, // normalize float css property styleFloat = jQuery.support.cssFloat ? "cssFloat" : "styleFloat", fcamelCase = function( all, letter ) { return letter.toUpperCase(); }; jQuery.fn.css = function( name, value ) { /// <summary> /// Set a single style property to a value, on all matched elements. /// If a number is provided, it is automatically converted into a pixel value. /// Part of CSS /// </summary> /// <returns type="jQuery" /> /// <param name="name" type="String"> /// A CSS property name. /// </param> /// <param name="value" type="String"> /// A value to set for the property. /// </param> return access( this, name, value, true, function( elem, name, value ) { if ( value === undefined ) { return jQuery.curCSS( elem, name ); } if ( typeof value === "number" && !rexclude.test(name) ) { value += "px"; } jQuery.style( elem, name, value ); }); }; jQuery.extend({ style: function( elem, name, value ) { // don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) { return undefined; } // ignore negative width and height values #1599 if ( (name === "width" || name === "height") && parseFloat(value) < 0 ) { value = undefined; } var style = elem.style || elem, set = value !== undefined; // IE uses filters for opacity if ( !jQuery.support.opacity && name === "opacity" ) { if ( set ) { // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // Set the alpha filter to set the opacity var opacity = parseInt( value, 10 ) + "" === "NaN" ? "" : "alpha(opacity=" + value * 100 + ")"; var filter = style.filter || jQuery.curCSS( elem, "filter" ) || ""; style.filter = ralpha.test(filter) ? filter.replace(ralpha, opacity) : opacity; } return style.filter && style.filter.indexOf("opacity=") >= 0 ? (parseFloat( ropacity.exec(style.filter)[1] ) / 100) + "": ""; } // Make sure we're using the right name for getting the float value if ( rfloat.test( name ) ) { name = styleFloat; } name = name.replace(rdashAlpha, fcamelCase); if ( set ) { style[ name ] = value; } return style[ name ]; }, css: function( elem, name, force, extra ) { /// <summary> /// This method is internal only. /// </summary> /// <private /> if ( name === "width" || name === "height" ) { var val, props = cssShow, which = name === "width" ? cssWidth : cssHeight; function getWH() { val = name === "width" ? elem.offsetWidth : elem.offsetHeight; if ( extra === "border" ) { return; } jQuery.each( which, function() { if ( !extra ) { val -= parseFloat(jQuery.curCSS( elem, "padding" + this, true)) || 0; } if ( extra === "margin" ) { val += parseFloat(jQuery.curCSS( elem, "margin" + this, true)) || 0; } else { val -= parseFloat(jQuery.curCSS( elem, "border" + this + "Width", true)) || 0; } }); } if ( elem.offsetWidth !== 0 ) { getWH(); } else { jQuery.swap( elem, props, getWH ); } return Math.max(0, Math.round(val)); } return jQuery.curCSS( elem, name, force ); }, curCSS: function( elem, name, force ) { /// <summary> /// This method is internal only. /// </summary> /// <private /> var ret, style = elem.style, filter; // IE uses filters for opacity if ( !jQuery.support.opacity && name === "opacity" && elem.currentStyle ) { ret = ropacity.test(elem.currentStyle.filter || "") ? (parseFloat(RegExp.$1) / 100) + "" : ""; return ret === "" ? "1" : ret; } // Make sure we're using the right name for getting the float value if ( rfloat.test( name ) ) { name = styleFloat; } if ( !force && style && style[ name ] ) { ret = style[ name ]; } else if ( getComputedStyle ) { // Only "float" is needed here if ( rfloat.test( name ) ) { name = "float"; } name = name.replace( rupper, "-$1" ).toLowerCase(); var defaultView = elem.ownerDocument.defaultView; if ( !defaultView ) { return null; } var computedStyle = defaultView.getComputedStyle( elem, null ); if ( computedStyle ) { ret = computedStyle.getPropertyValue( name ); } // We should always get a number back from opacity if ( name === "opacity" && ret === "" ) { ret = "1"; } } else if ( elem.currentStyle ) { var camelCase = name.replace(rdashAlpha, fcamelCase); ret = elem.currentStyle[ name ] || elem.currentStyle[ camelCase ]; // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels if ( !rnumpx.test( ret ) && rnum.test( ret ) ) { // Remember the original values var left = style.left, rsLeft = elem.runtimeStyle.left; // Put in the new values to get a computed value out elem.runtimeStyle.left = elem.currentStyle.left; style.left = camelCase === "fontSize" ? "1em" : (ret || 0); ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; elem.runtimeStyle.left = rsLeft; } } return ret; }, // A method for quickly swapping in/out CSS properties to get correct calculations swap: function( elem, options, callback ) { /// <summary> /// Swap in/out style options. /// </summary> var old = {}; // Remember the old values, and insert the new ones for ( var name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } callback.call( elem ); // Revert the old values for ( var name in options ) { elem.style[ name ] = old[ name ]; } } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { var width = elem.offsetWidth, height = elem.offsetHeight, skip = elem.nodeName.toLowerCase() === "tr"; return width === 0 && height === 0 && !skip ? true : width > 0 && height > 0 && !skip ? false : jQuery.curCSS(elem, "display") === "none"; }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } var jsc = now(), rscript = /<script(.|\s)*?\/script>/gi, rselectTextarea = /select|textarea/i, rinput = /color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week/i, jsre = /=\?(&|$)/, rquery = /\?/, rts = /(\?|&)_=.*?(&|$)/, rurl = /^(\w+:)?\/\/([^\/?#]+)/, r20 = /%20/g; jQuery.fn.extend({ // Keep a copy of the old load _load: jQuery.fn.load, load: function( url, params, callback ) { /// <summary> /// Loads HTML from a remote file and injects it into the DOM. By default performs a GET request, but if parameters are included /// then a POST will be performed. /// </summary> /// <param name="url" type="String">The URL of the HTML page to load.</param> /// <param name="data" optional="true" type="Map">Key/value pairs that will be sent to the server.</param> /// <param name="callback" optional="true" type="Function">The function called when the AJAX request is complete. It should map function(responseText, textStatus, XMLHttpRequest) such that this maps the injected DOM element.</param> /// <returns type="jQuery" /> if ( typeof url !== "string" ) { return this._load( url ); // Don't do a request if no elements are being requested } else if ( !this.length ) { return this; } var off = url.indexOf(" "); if ( off >= 0 ) { var selector = url.slice(off, url.length); url = url.slice(0, off); } // Default to a GET request var type = "GET"; // If the second parameter was provided if ( params ) { // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = null; // Otherwise, build a param string } else if ( typeof params === "object" ) { params = jQuery.param( params, jQuery.ajaxSettings.traditional ); type = "POST"; } } var self = this; // Request the remote document jQuery.ajax({ url: url, type: type, dataType: "html", data: params, complete: function( res, status ) { // If successful, inject the HTML into all the matched elements if ( status === "success" || status === "notmodified" ) { // See if a selector was specified self.html( selector ? // Create a dummy div to hold the results jQuery("<div />") // inject the contents of the document in, removing the scripts // to avoid any 'Permission Denied' errors in IE .append(res.responseText.replace(rscript, "")) // Locate the specified elements .find(selector) : // If not, just inject the full result res.responseText ); } if ( callback ) { self.each( callback, [res.responseText, status, res] ); } } }); return this; }, serialize: function() { /// <summary> /// Serializes a set of input elements into a string of data. /// </summary> /// <returns type="String">The serialized result</returns> return jQuery.param(this.serializeArray()); }, serializeArray: function() { /// <summary> /// Serializes all forms and form elements but returns a JSON data structure. /// </summary> /// <returns type="String">A JSON data structure representing the serialized items.</returns> return this.map(function() { return this.elements ? jQuery.makeArray(this.elements) : this; }) .filter(function() { return this.name && !this.disabled && (this.checked || rselectTextarea.test(this.nodeName) || rinput.test(this.type)); }) .map(function( i, elem ) { var val = jQuery(this).val(); return val == null ? null : jQuery.isArray(val) ? jQuery.map( val, function( val, i ) { return { name: elem.name, value: val }; }) : { name: elem.name, value: val }; }).get(); } }); // Attach a bunch of functions for handling common AJAX events // jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "), function( i, o ) { // jQuery.fn[o] = function( f ) { // return this.bind(o, f); // }; // }); jQuery.fn["ajaxStart"] = function( f ) { /// <summary> /// Attach a function to be executed whenever an AJAX request begins and there is none already active. This is an Ajax Event. /// </summary> /// <param name="f" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return this.bind("ajaxStart", f); }; jQuery.fn["ajaxStop"] = function( f ) { /// <summary> /// Attach a function to be executed whenever all AJAX requests have ended. This is an Ajax Event. /// </summary> /// <param name="f" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return this.bind("ajaxStop", f); }; jQuery.fn["ajaxComplete"] = function( f ) { /// <summary> /// Attach a function to be executed whenever an AJAX request completes. This is an Ajax Event. /// </summary> /// <param name="f" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return this.bind("ajaxComplete", f); }; jQuery.fn["ajaxError"] = function( f ) { /// <summary> /// Attach a function to be executed whenever an AJAX request fails. This is an Ajax Event. /// </summary> /// <param name="f" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return this.bind("ajaxError", f); }; jQuery.fn["ajaxSuccess"] = function( f ) { /// <summary> /// Attach a function to be executed whenever an AJAX request completes successfully. This is an Ajax Event. /// </summary> /// <param name="f" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return this.bind("ajaxSuccess", f); }; jQuery.fn["ajaxSend"] = function( f ) { /// <summary> /// Attach a function to be executed before an AJAX request is sent. This is an Ajax Event. /// </summary> /// <param name="f" type="Function">The function to execute.</param> /// <returns type="jQuery" /> return this.bind("ajaxSend", f); }; jQuery.extend({ get: function( url, data, callback, type ) { /// <summary> /// Loads a remote page using an HTTP GET request. /// </summary> /// <param name="url" type="String">The URL of the HTML page to load.</param> /// <param name="data" optional="true" type="Map">Key/value pairs that will be sent to the server.</param> /// <param name="callback" optional="true" type="Function">The function called when the AJAX request is complete. It should map function(responseText, textStatus) such that this maps the options for this AJAX request.</param> /// <param name="type" optional="true" type="String">Type of data to be returned to callback function. Valid valiues are xml, html, script, json, text, _default.</param> /// <returns type="XMLHttpRequest" /> // shift arguments if data argument was omited if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = null; } return jQuery.ajax({ type: "GET", url: url, data: data, success: callback, dataType: type }); }, getScript: function( url, callback ) { /// <summary> /// Loads and executes a local JavaScript file using an HTTP GET request. /// </summary> /// <param name="url" type="String">The URL of the script to load.</param> /// <param name="callback" optional="true" type="Function">The function called when the AJAX request is complete. It should map function(data, textStatus) such that this maps the options for the AJAX request.</param> /// <returns type="XMLHttpRequest" /> return jQuery.get(url, null, callback, "script"); }, getJSON: function( url, data, callback ) { /// <summary> /// Loads JSON data using an HTTP GET request. /// </summary> /// <param name="url" type="String">The URL of the JSON data to load.</param> /// <param name="data" optional="true" type="Map">Key/value pairs that will be sent to the server.</param> /// <param name="callback" optional="true" type="Function">The function called when the AJAX request is complete if the data is loaded successfully. It should map function(data, textStatus) such that this maps the options for this AJAX request.</param> /// <returns type="XMLHttpRequest" /> return jQuery.get(url, data, callback, "json"); }, post: function( url, data, callback, type ) { /// <summary> /// Loads a remote page using an HTTP POST request. /// </summary> /// <param name="url" type="String">The URL of the HTML page to load.</param> /// <param name="data" optional="true" type="Map">Key/value pairs that will be sent to the server.</param> /// <param name="callback" optional="true" type="Function">The function called when the AJAX request is complete. It should map function(responseText, textStatus) such that this maps the options for this AJAX request.</param> /// <param name="type" optional="true" type="String">Type of data to be returned to callback function. Valid valiues are xml, html, script, json, text, _default.</param> /// <returns type="XMLHttpRequest" /> // shift arguments if data argument was omited if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = {}; } return jQuery.ajax({ type: "POST", url: url, data: data, success: callback, dataType: type }); }, ajaxSetup: function( settings ) { /// <summary> /// Sets up global settings for AJAX requests. /// </summary> /// <param name="settings" type="Options">A set of key/value pairs that configure the default Ajax request.</param> jQuery.extend( jQuery.ajaxSettings, settings ); }, ajaxSettings: { url: location.href, global: true, type: "GET", contentType: "application/x-www-form-urlencoded", processData: true, async: true, /* timeout: 0, data: null, username: null, password: null, traditional: false, */ // Create the request object; Microsoft failed to properly // implement the XMLHttpRequest in IE7 (can't request local files), // so we use the ActiveXObject when it is available // This function can be overriden by calling jQuery.ajaxSetup xhr: window.XMLHttpRequest && (window.location.protocol !== "file:" || !window.ActiveXObject) ? function() { return new window.XMLHttpRequest(); } : function() { try { return new window.ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} }, accepts: { xml: "application/xml, text/xml", html: "text/html", script: "text/javascript, application/javascript", json: "application/json, text/javascript", text: "text/plain", _default: "*/*" } }, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajax: function( origSettings ) { /// <summary> /// Load a remote page using an HTTP request. /// </summary> /// <private /> var s = jQuery.extend(true, {}, jQuery.ajaxSettings, origSettings); var jsonp, status, data, callbackContext = origSettings && origSettings.context || s, type = s.type.toUpperCase(); // convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Handle JSONP Parameter Callbacks if ( s.dataType === "jsonp" ) { if ( type === "GET" ) { if ( !jsre.test( s.url ) ) { s.url += (rquery.test( s.url ) ? "&" : "?") + (s.jsonp || "callback") + "=?"; } } else if ( !s.data || !jsre.test(s.data) ) { s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?"; } s.dataType = "json"; } // Build temporary JSONP function if ( s.dataType === "json" && (s.data && jsre.test(s.data) || jsre.test(s.url)) ) { jsonp = s.jsonpCallback || ("jsonp" + jsc++); // Replace the =? sequence both in the query string and the data if ( s.data ) { s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1"); } s.url = s.url.replace(jsre, "=" + jsonp + "$1"); // We need to make sure // that a JSONP style response is executed properly s.dataType = "script"; // Handle JSONP-style loading window[ jsonp ] = window[ jsonp ] || function( tmp ) { data = tmp; success(); complete(); // Garbage collect window[ jsonp ] = undefined; try { delete window[ jsonp ]; } catch(e) {} if ( head ) { head.removeChild( script ); } }; } if ( s.dataType === "script" && s.cache === null ) { s.cache = false; } if ( s.cache === false && type === "GET" ) { var ts = now(); // try replacing _= if it is there var ret = s.url.replace(rts, "$1_=" + ts + "$2"); // if nothing was replaced, add timestamp to the end s.url = ret + ((ret === s.url) ? (rquery.test(s.url) ? "&" : "?") + "_=" + ts : ""); } // If data is available, append data to url for get requests if ( s.data && type === "GET" ) { s.url += (rquery.test(s.url) ? "&" : "?") + s.data; } // Watch for a new set of requests if ( s.global && ! jQuery.active++ ) { jQuery.event.trigger( "ajaxStart" ); } // Matches an absolute URL, and saves the domain var parts = rurl.exec( s.url ), remote = parts && (parts[1] && parts[1] !== location.protocol || parts[2] !== location.host); // If we're requesting a remote document // and trying to load JSON or Script with a GET if ( s.dataType === "script" && type === "GET" && remote ) { var head = document.getElementsByTagName("head")[0] || document.documentElement; var script = document.createElement("script"); script.src = s.url; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } // Handle Script loading if ( !jsonp ) { var done = false; // Attach handlers for all browsers script.onload = script.onreadystatechange = function() { if ( !done && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete") ) { done = true; success(); complete(); // Handle memory leak in IE script.onload = script.onreadystatechange = null; if ( head && script.parentNode ) { head.removeChild( script ); } } }; } // Use insertBefore instead of appendChild to circumvent an IE6 bug. // This arises when a base node is used (#2709 and #4378). head.insertBefore( script, head.firstChild ); // We handle everything using the script element injection return undefined; } var requestDone = false; // Create the request object var xhr = s.xhr(); if ( !xhr ) { return; } // Open the socket // Passing null username, generates a login popup on Opera (#2865) if ( s.username ) { xhr.open(type, s.url, s.async, s.username, s.password); } else { xhr.open(type, s.url, s.async); } // Need an extra try/catch for cross domain requests in Firefox 3 try { // Set the correct header, if data is being sent if ( s.data || origSettings && origSettings.contentType ) { xhr.setRequestHeader("Content-Type", s.contentType); } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[s.url] ) { xhr.setRequestHeader("If-Modified-Since", jQuery.lastModified[s.url]); } if ( jQuery.etag[s.url] ) { xhr.setRequestHeader("If-None-Match", jQuery.etag[s.url]); } } // Set header so the called script knows that it's an XMLHttpRequest // Only send the header if it's not a remote XHR if ( !remote ) { xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); } // Set the Accepts header for the server, depending on the dataType xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ? s.accepts[ s.dataType ] + ", */*" : s.accepts._default ); } catch(e) {} // Allow custom headers/mimetypes and early abort if ( s.beforeSend && s.beforeSend.call(callbackContext, xhr, s) === false ) { // Handle the global AJAX counter if ( s.global && ! --jQuery.active ) { jQuery.event.trigger( "ajaxStop" ); } // close opended socket xhr.abort(); return false; } if ( s.global ) { trigger("ajaxSend", [xhr, s]); } // Wait for a response to come back var onreadystatechange = xhr.onreadystatechange = function( isTimeout ) { // The request was aborted if ( !xhr || xhr.readyState === 0 || isTimeout === "abort" ) { // Opera doesn't call onreadystatechange before this point // so we simulate the call if ( !requestDone ) { complete(); } requestDone = true; if ( xhr ) { xhr.onreadystatechange = jQuery.noop; } // The transfer is complete and the data is available, or the request timed out } else if ( !requestDone && xhr && (xhr.readyState === 4 || isTimeout === "timeout") ) { requestDone = true; xhr.onreadystatechange = jQuery.noop; status = isTimeout === "timeout" ? "timeout" : !jQuery.httpSuccess( xhr ) ? "error" : s.ifModified && jQuery.httpNotModified( xhr, s.url ) ? "notmodified" : "success"; var errMsg; if ( status === "success" ) { // Watch for, and catch, XML document parse errors try { // process the data (runs the xml through httpData regardless of callback) data = jQuery.httpData( xhr, s.dataType, s ); } catch(err) { status = "parsererror"; errMsg = err; } } // Make sure that the request was successful or notmodified if ( status === "success" || status === "notmodified" ) { // JSONP handles its own success callback if ( !jsonp ) { success(); } } else { jQuery.handleError(s, xhr, status, errMsg); } // Fire the complete handlers complete(); if ( isTimeout === "timeout" ) { xhr.abort(); } // Stop memory leaks if ( s.async ) { xhr = null; } } }; // Override the abort handler, if we can (IE doesn't allow it, but that's OK) // Opera doesn't fire onreadystatechange at all on abort try { var oldAbort = xhr.abort; xhr.abort = function() { if ( xhr ) { oldAbort.call( xhr ); } onreadystatechange( "abort" ); }; } catch(e) { } // Timeout checker if ( s.async && s.timeout > 0 ) { setTimeout(function() { // Check to see if the request is still happening if ( xhr && !requestDone ) { onreadystatechange( "timeout" ); } }, s.timeout); } // Send the data try { xhr.send( type === "POST" || type === "PUT" || type === "DELETE" ? s.data : null ); } catch(e) { jQuery.handleError(s, xhr, null, e); // Fire the complete handlers complete(); } // firefox 1.5 doesn't fire statechange for sync requests if ( !s.async ) { onreadystatechange(); } function success() { // If a local callback was specified, fire it and pass it the data if ( s.success ) { s.success.call( callbackContext, data, status, xhr ); } // Fire the global callback if ( s.global ) { trigger( "ajaxSuccess", [xhr, s] ); } } function complete() { // Process result if ( s.complete ) { s.complete.call( callbackContext, xhr, status); } // The request was completed if ( s.global ) { trigger( "ajaxComplete", [xhr, s] ); } // Handle the global AJAX counter if ( s.global && ! --jQuery.active ) { jQuery.event.trigger( "ajaxStop" ); } } function trigger(type, args) { (s.context ? jQuery(s.context) : jQuery.event).trigger(type, args); } // return XMLHttpRequest to allow aborting the request etc. return xhr; }, handleError: function( s, xhr, status, e ) { /// <summary> /// This method is internal. /// </summary> /// <private /> // If a local callback was specified, fire it if ( s.error ) { s.error.call( s.context || s, xhr, status, e ); } // Fire the global callback if ( s.global ) { (s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] ); } }, // Counter for holding the number of active queries active: 0, // Determines if an XMLHttpRequest was successful or not httpSuccess: function( xhr ) { /// <summary> /// This method is internal. /// </summary> /// <private /> try { // IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450 return !xhr.status && location.protocol === "file:" || // Opera returns 0 when status is 304 ( xhr.status >= 200 && xhr.status < 300 ) || xhr.status === 304 || xhr.status === 1223 || xhr.status === 0; } catch(e) {} return false; }, // Determines if an XMLHttpRequest returns NotModified httpNotModified: function( xhr, url ) { /// <summary> /// This method is internal. /// </summary> /// <private /> var lastModified = xhr.getResponseHeader("Last-Modified"), etag = xhr.getResponseHeader("Etag"); if ( lastModified ) { jQuery.lastModified[url] = lastModified; } if ( etag ) { jQuery.etag[url] = etag; } // Opera returns 0 when status is 304 return xhr.status === 304 || xhr.status === 0; }, httpData: function( xhr, type, s ) { /// <summary> /// This method is internal. /// </summary> /// <private /> var ct = xhr.getResponseHeader("content-type") || "", xml = type === "xml" || !type && ct.indexOf("xml") >= 0, data = xml ? xhr.responseXML : xhr.responseText; if ( xml && data.documentElement.nodeName === "parsererror" ) { jQuery.error( "parsererror" ); } // Allow a pre-filtering function to sanitize the response // s is checked to keep backwards compatibility if ( s && s.dataFilter ) { data = s.dataFilter( data, type ); } // The filter can actually parse the response if ( typeof data === "string" ) { // Get the JavaScript object, if JSON is used. if ( type === "json" || !type && ct.indexOf("json") >= 0 ) { data = jQuery.parseJSON( data ); // If the type is "script", eval it in global context } else if ( type === "script" || !type && ct.indexOf("javascript") >= 0 ) { jQuery.globalEval( data ); } } return data; }, // Serialize an array of form elements or a set of // key/values into a query string param: function( a, traditional ) { /// <summary> /// Create a serialized representation of an array or object, suitable for use in a URL /// query string or Ajax request. /// </summary> /// <param name="a" type="Object"> /// An array or object to serialize. /// </param> /// <param name="traditional" type="Boolean"> /// A Boolean indicating whether to perform a traditional "shallow" serialization. /// </param> /// <returns type="String" /> var s = []; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray(a) || a.jquery ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( var prefix in a ) { buildParams( prefix, a[prefix] ); } } // Return the resulting serialization return s.join("&").replace(r20, "+"); function buildParams( prefix, obj ) { if ( jQuery.isArray(obj) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional ) { // Treat each array item as a scalar. add( prefix, v ); } else { // If array item is non-scalar (array or object), encode its // numeric index to resolve deserialization ambiguity issues. // Note that rack (as of 1.0.0) can't currently deserialize // nested arrays properly, and attempting to do so may cause // a server error. Possible fixes are to modify rack's // deserialization algorithm or to provide an option or flag // to force array serialization to be shallow. buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v ); } }); } else if ( !traditional && obj != null && typeof obj === "object" ) { // Serialize object item. jQuery.each( obj, function( k, v ) { buildParams( prefix + "[" + k + "]", v ); }); } else { // Serialize scalar item. add( prefix, obj ); } } function add( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction(value) ? value() : value; s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value); } } }); var elemdisplay = {}, rfxtypes = /toggle|show|hide/, rfxnum = /^([+-]=)?([\d+-.]+)(.*)$/, timerId, fxAttrs = [ // height animations [ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ], // width animations [ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ], // opacity animations [ "opacity" ] ]; jQuery.fn.extend({ show: function( speed, callback ) { /// <summary> /// Show all matched elements using a graceful animation and firing an optional callback after completion. /// </summary> /// <param name="speed" type="String">A string representing one of three predefined speeds ('slow', 'normal', or 'fast'), or /// the number of milliseconds to run the animation</param> /// <param name="callback" optional="true" type="Function">A function to be executed whenever the animation completes, once for each animated element. It should map function callback() such that this is the DOM element being animated.</param> /// <returns type="jQuery" /> if ( speed || speed === 0) { return this.animate( genFx("show", 3), speed, callback); } else { for ( var i = 0, l = this.length; i < l; i++ ) { var old = jQuery.data(this[i], "olddisplay"); this[i].style.display = old || ""; if ( jQuery.css(this[i], "display") === "none" ) { var nodeName = this[i].nodeName, display; if ( elemdisplay[ nodeName ] ) { display = elemdisplay[ nodeName ]; } else { var elem = jQuery("<" + nodeName + " />").appendTo("body"); display = elem.css("display"); if ( display === "none" ) { display = "block"; } elem.remove(); elemdisplay[ nodeName ] = display; } jQuery.data(this[i], "olddisplay", display); } } // Set the display of the elements in a second loop // to avoid the constant reflow for ( var j = 0, k = this.length; j < k; j++ ) { this[j].style.display = jQuery.data(this[j], "olddisplay") || ""; } return this; } }, hide: function( speed, callback ) { /// <summary> /// Hides all matched elements using a graceful animation and firing an optional callback after completion. /// </summary> /// <param name="speed" type="String">A string representing one of three predefined speeds ('slow', 'normal', or 'fast'), or /// the number of milliseconds to run the animation</param> /// <param name="callback" optional="true" type="Function">A function to be executed whenever the animation completes, once for each animated element. It should map function callback() such that this is the DOM element being animated.</param> /// <returns type="jQuery" /> if ( speed || speed === 0 ) { return this.animate( genFx("hide", 3), speed, callback); } else { for ( var i = 0, l = this.length; i < l; i++ ) { var old = jQuery.data(this[i], "olddisplay"); if ( !old && old !== "none" ) { jQuery.data(this[i], "olddisplay", jQuery.css(this[i], "display")); } } // Set the display of the elements in a second loop // to avoid the constant reflow for ( var j = 0, k = this.length; j < k; j++ ) { this[j].style.display = "none"; } return this; } }, // Save the old toggle function _toggle: jQuery.fn.toggle, toggle: function( fn, fn2 ) { /// <summary> /// Toggles displaying each of the set of matched elements. /// </summary> /// <returns type="jQuery" /> var bool = typeof fn === "boolean"; if ( jQuery.isFunction(fn) && jQuery.isFunction(fn2) ) { this._toggle.apply( this, arguments ); } else if ( fn == null || bool ) { this.each(function() { var state = bool ? fn : jQuery(this).is(":hidden"); jQuery(this)[ state ? "show" : "hide" ](); }); } else { this.animate(genFx("toggle", 3), fn, fn2); } return this; }, fadeTo: function( speed, to, callback ) { /// <summary> /// Fades the opacity of all matched elements to a specified opacity. /// </summary> /// <param name="speed" type="String">A string representing one of three predefined speeds ('slow', 'normal', or 'fast'), or /// the number of milliseconds to run the animation</param> /// <param name="callback" optional="true" type="Function">A function to be executed whenever the animation completes, once for each animated element. It should map function callback() such that this is the DOM element being animated.</param> /// <returns type="jQuery" /> return this.filter(":hidden").css("opacity", 0).show().end() .animate({opacity: to}, speed, callback); }, animate: function( prop, speed, easing, callback ) { /// <summary> /// A function for making custom animations. /// </summary> /// <param name="prop" type="Options">A set of style attributes that you wish to animate and to what end.</param> /// <param name="speed" optional="true" type="String">A string representing one of three predefined speeds ('slow', 'normal', or 'fast'), or /// the number of milliseconds to run the animation</param> /// <param name="easing" optional="true" type="String">The name of the easing effect that you want to use. There are two built-in values, 'linear' and 'swing'.</param> /// <param name="callback" optional="true" type="Function">A function to be executed whenever the animation completes, once for each animated element. It should map function callback() such that this is the DOM element being animated.</param> /// <returns type="jQuery" /> var optall = jQuery.speed(speed, easing, callback); if ( jQuery.isEmptyObject( prop ) ) { return this.each( optall.complete ); } return this[ optall.queue === false ? "each" : "queue" ](function() { var opt = jQuery.extend({}, optall), p, hidden = this.nodeType === 1 && jQuery(this).is(":hidden"), self = this; for ( p in prop ) { var name = p.replace(rdashAlpha, fcamelCase); if ( p !== name ) { prop[ name ] = prop[ p ]; delete prop[ p ]; p = name; } if ( prop[p] === "hide" && hidden || prop[p] === "show" && !hidden ) { return opt.complete.call(this); } if ( ( p === "height" || p === "width" ) && this.style ) { // Store display property opt.display = jQuery.css(this, "display"); // Make sure that nothing sneaks out opt.overflow = this.style.overflow; } if ( jQuery.isArray( prop[p] ) ) { // Create (if needed) and add to specialEasing (opt.specialEasing = opt.specialEasing || {})[p] = prop[p][1]; prop[p] = prop[p][0]; } } if ( opt.overflow != null ) { this.style.overflow = "hidden"; } opt.curAnim = jQuery.extend({}, prop); jQuery.each( prop, function( name, val ) { var e = new jQuery.fx( self, opt, name ); if ( rfxtypes.test(val) ) { e[ val === "toggle" ? hidden ? "show" : "hide" : val ]( prop ); } else { var parts = rfxnum.exec(val), start = e.cur(true) || 0; if ( parts ) { var end = parseFloat( parts[2] ), unit = parts[3] || "px"; // We need to compute starting value if ( unit !== "px" ) { self.style[ name ] = (end || 1) + unit; start = ((end || 1) / e.cur(true)) * start; self.style[ name ] = start + unit; } // If a +=/-= token was provided, we're doing a relative animation if ( parts[1] ) { end = ((parts[1] === "-=" ? -1 : 1) * end) + start; } e.custom( start, end, unit ); } else { e.custom( start, val, "" ); } } }); // For JS strict compliance return true; }); }, stop: function( clearQueue, gotoEnd ) { /// <summary> /// Stops all currently animations on the specified elements. /// </summary> /// <param name="clearQueue" optional="true" type="Boolean">True to clear animations that are queued to run.</param> /// <param name="gotoEnd" optional="true" type="Boolean">True to move the element value to the end of its animation target.</param> /// <returns type="jQuery" /> var timers = jQuery.timers; if ( clearQueue ) { this.queue([]); } this.each(function() { // go in reverse order so anything added to the queue during the loop is ignored for ( var i = timers.length - 1; i >= 0; i-- ) { if ( timers[i].elem === this ) { if (gotoEnd) { // force the next step to be the last timers[i](true); } timers.splice(i, 1); } } }); // start the next in the queue if the last step wasn't forced if ( !gotoEnd ) { this.dequeue(); } return this; } }); // Generate shortcuts for custom animations // jQuery.each({ // slideDown: genFx("show", 1), // slideUp: genFx("hide", 1), // slideToggle: genFx("toggle", 1), // fadeIn: { opacity: "show" }, // fadeOut: { opacity: "hide" } // }, function( name, props ) { // jQuery.fn[ name ] = function( speed, callback ) { // return this.animate( props, speed, callback ); // }; // }); jQuery.fn[ "slideDown" ] = function( speed, callback ) { /// <summary> /// Reveal all matched elements by adjusting their height. /// </summary> /// <param name="speed" type="String">A string representing one of three predefined speeds ('slow', 'normal', or 'fast'), or /// the number of milliseconds to run the animation</param> /// <param name="callback" optional="true" type="Function">A function to be executed whenever the animation completes, once for each animated element. It should map function callback() such that this is the DOM element being animated.</param> /// <returns type="jQuery" /> return this.animate( genFx("show", 1), speed, callback ); }; jQuery.fn[ "slideUp" ] = function( speed, callback ) { /// <summary> /// Hiding all matched elements by adjusting their height. /// </summary> /// <param name="speed" type="String">A string representing one of three predefined speeds ('slow', 'normal', or 'fast'), or /// the number of milliseconds to run the animation</param> /// <param name="callback" optional="true" type="Function">A function to be executed whenever the animation completes, once for each animated element. It should map function callback() such that this is the DOM element being animated.</param> /// <returns type="jQuery" /> return this.animate( genFx("hide", 1), speed, callback ); }; jQuery.fn[ "slideToggle" ] = function( speed, callback ) { /// <summary> /// Toggles the visibility of all matched elements by adjusting their height. /// </summary> /// <param name="speed" type="String">A string representing one of three predefined speeds ('slow', 'normal', or 'fast'), or /// the number of milliseconds to run the animation</param> /// <param name="callback" optional="true" type="Function">A function to be executed whenever the animation completes, once for each animated element. It should map function callback() such that this is the DOM element being animated.</param> /// <returns type="jQuery" /> return this.animate( genFx("toggle", 1), speed, callback ); }; jQuery.fn[ "fadeIn" ] = function( speed, callback ) { /// <summary> /// Fades in all matched elements by adjusting their opacity. /// </summary> /// <param name="speed" type="String">A string representing one of three predefined speeds ('slow', 'normal', or 'fast'), or /// the number of milliseconds to run the animation</param> /// <param name="callback" optional="true" type="Function">A function to be executed whenever the animation completes, once for each animated element. It should map function callback() such that this is the DOM element being animated.</param> /// <returns type="jQuery" /> return this.animate( { opacity: "show" }, speed, callback ); }; jQuery.fn[ "fadeOut" ] = function( speed, callback ) { /// <summary> /// Fades the opacity of all matched elements to a specified opacity. /// </summary> /// <param name="speed" type="String">A string representing one of three predefined speeds ('slow', 'normal', or 'fast'), or /// the number of milliseconds to run the animation</param> /// <param name="callback" optional="true" type="Function">A function to be executed whenever the animation completes, once for each animated element. It should map function callback() such that this is the DOM element being animated.</param> /// <returns type="jQuery" /> return this.animate( { opacity: "hide" }, speed, callback ); }; jQuery.extend({ speed: function( speed, easing, fn ) { /// <summary> /// This member is internal. /// </summary> /// <private /> var opt = speed && typeof speed === "object" ? speed : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction(easing) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : jQuery.fx.speeds[opt.duration] || jQuery.fx.speeds._default; // Queueing opt.old = opt.complete; opt.complete = function() { if ( opt.queue !== false ) { jQuery(this).dequeue(); } if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } }; return opt; }, easing: { linear: function( p, n, firstNum, diff ) { /// <summary> /// This member is internal. /// </summary> /// <private /> return firstNum + diff * p; }, swing: function( p, n, firstNum, diff ) { /// <summary> /// This member is internal. /// </summary> /// <private /> return ((-Math.cos(p*Math.PI)/2) + 0.5) * diff + firstNum; } }, timers: [], fx: function( elem, options, prop ) { /// <summary> /// This member is internal. /// </summary> /// <private /> this.options = options; this.elem = elem; this.prop = prop; if ( !options.orig ) { options.orig = {}; } } }); jQuery.fx.prototype = { // Simple function for setting a style value update: function() { /// <summary> /// This member is internal. /// </summary> /// <private /> if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } (jQuery.fx.step[this.prop] || jQuery.fx.step._default)( this ); // Set display property to block for height/width animations if ( ( this.prop === "height" || this.prop === "width" ) && this.elem.style ) { this.elem.style.display = "block"; } }, // Get the current size cur: function( force ) { /// <summary> /// This member is internal. /// </summary> /// <private /> if ( this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null) ) { return this.elem[ this.prop ]; } var r = parseFloat(jQuery.css(this.elem, this.prop, force)); return r && r > -10000 ? r : parseFloat(jQuery.curCSS(this.elem, this.prop)) || 0; }, // Start an animation from one number to another custom: function( from, to, unit ) { this.startTime = now(); this.start = from; this.end = to; this.unit = unit || this.unit || "px"; this.now = this.start; this.pos = this.state = 0; var self = this; function t( gotoEnd ) { return self.step(gotoEnd); } t.elem = this.elem; if ( t() && jQuery.timers.push(t) && !timerId ) { timerId = setInterval(jQuery.fx.tick, 13); } }, // Simple 'show' function show: function() { /// <summary> /// Displays each of the set of matched elements if they are hidden. /// </summary> // Remember where we started, so that we can go back to it later this.options.orig[this.prop] = jQuery.style( this.elem, this.prop ); this.options.show = true; // Begin the animation // Make sure that we start at a small width/height to avoid any // flash of content this.custom(this.prop === "width" || this.prop === "height" ? 1 : 0, this.cur()); // Start by showing the element jQuery( this.elem ).show(); }, // Simple 'hide' function hide: function() { /// <summary> /// Hides each of the set of matched elements if they are shown. /// </summary> // Remember where we started, so that we can go back to it later this.options.orig[this.prop] = jQuery.style( this.elem, this.prop ); this.options.hide = true; // Begin the animation this.custom(this.cur(), 0); }, // Each step of an animation step: function( gotoEnd ) { /// <summary> /// This method is internal. /// </summary> /// <private /> var t = now(), done = true; if ( gotoEnd || t >= this.options.duration + this.startTime ) { this.now = this.end; this.pos = this.state = 1; this.update(); this.options.curAnim[ this.prop ] = true; for ( var i in this.options.curAnim ) { if ( this.options.curAnim[i] !== true ) { done = false; } } if ( done ) { if ( this.options.display != null ) { // Reset the overflow this.elem.style.overflow = this.options.overflow; // Reset the display var old = jQuery.data(this.elem, "olddisplay"); this.elem.style.display = old ? old : this.options.display; if ( jQuery.css(this.elem, "display") === "none" ) { this.elem.style.display = "block"; } } // Hide the element if the "hide" operation was done if ( this.options.hide ) { jQuery(this.elem).hide(); } // Reset the properties, if the item has been hidden or shown if ( this.options.hide || this.options.show ) { for ( var p in this.options.curAnim ) { jQuery.style(this.elem, p, this.options.orig[p]); } } // Execute the complete function this.options.complete.call( this.elem ); } return false; } else { var n = t - this.startTime; this.state = n / this.options.duration; // Perform the easing function, defaults to swing var specialEasing = this.options.specialEasing && this.options.specialEasing[this.prop]; var defaultEasing = this.options.easing || (jQuery.easing.swing ? "swing" : "linear"); this.pos = jQuery.easing[specialEasing || defaultEasing](this.state, n, 0, 1, this.options.duration); this.now = this.start + ((this.end - this.start) * this.pos); // Perform the next step of the animation this.update(); } return true; } }; jQuery.extend( jQuery.fx, { tick: function() { var timers = jQuery.timers; for ( var i = 0; i < timers.length; i++ ) { if ( !timers[i]() ) { timers.splice(i--, 1); } } if ( !timers.length ) { jQuery.fx.stop(); } }, stop: function() { clearInterval( timerId ); timerId = null; }, speeds: { slow: 600, fast: 200, // Default speed _default: 400 }, step: { opacity: function( fx ) { jQuery.style(fx.elem, "opacity", fx.now); }, _default: function( fx ) { if ( fx.elem.style && fx.elem.style[ fx.prop ] != null ) { fx.elem.style[ fx.prop ] = (fx.prop === "width" || fx.prop === "height" ? Math.max(0, fx.now) : fx.now) + fx.unit; } else { fx.elem[ fx.prop ] = fx.now; } } } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; } function genFx( type, num ) { var obj = {}; jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice(0,num)), function() { obj[ this ] = type; }); return obj; } if ( "getBoundingClientRect" in document.documentElement ) { jQuery.fn.offset = function( options ) { /// <summary> /// Set the current coordinates of every element in the set of matched elements, /// relative to the document. /// </summary> /// <param name="options" type="Object"> /// An object containing the properties top and left, which are integers indicating the /// new top and left coordinates for the elements. /// </param> /// <returns type="jQuery" /> var elem = this[0]; if ( options ) { return this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } if ( !elem || !elem.ownerDocument ) { return null; } if ( elem === elem.ownerDocument.body ) { return jQuery.offset.bodyOffset( elem ); } var box = elem.getBoundingClientRect(), doc = elem.ownerDocument, body = doc.body, docElem = doc.documentElement, clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0, top = box.top + (self.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop ) - clientTop, left = box.left + (self.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft) - clientLeft; return { top: top, left: left }; }; } else { jQuery.fn.offset = function( options ) { /// <summary> /// Set the current coordinates of every element in the set of matched elements, /// relative to the document. /// </summary> /// <param name="options" type="Object"> /// An object containing the properties top and left, which are integers indicating the /// new top and left coordinates for the elements. /// </param> /// <returns type="jQuery" /> var elem = this[0]; if ( options ) { return this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } if ( !elem || !elem.ownerDocument ) { return null; } if ( elem === elem.ownerDocument.body ) { return jQuery.offset.bodyOffset( elem ); } jQuery.offset.initialize(); var offsetParent = elem.offsetParent, prevOffsetParent = elem, doc = elem.ownerDocument, computedStyle, docElem = doc.documentElement, body = doc.body, defaultView = doc.defaultView, prevComputedStyle = defaultView ? defaultView.getComputedStyle( elem, null ) : elem.currentStyle, top = elem.offsetTop, left = elem.offsetLeft; while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) { if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) { break; } computedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle; top -= elem.scrollTop; left -= elem.scrollLeft; if ( elem === offsetParent ) { top += elem.offsetTop; left += elem.offsetLeft; if ( jQuery.offset.doesNotAddBorder && !(jQuery.offset.doesAddBorderForTableAndCells && /^t(able|d|h)$/i.test(elem.nodeName)) ) { top += parseFloat( computedStyle.borderTopWidth ) || 0; left += parseFloat( computedStyle.borderLeftWidth ) || 0; } prevOffsetParent = offsetParent, offsetParent = elem.offsetParent; } if ( jQuery.offset.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" ) { top += parseFloat( computedStyle.borderTopWidth ) || 0; left += parseFloat( computedStyle.borderLeftWidth ) || 0; } prevComputedStyle = computedStyle; } if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" ) { top += body.offsetTop; left += body.offsetLeft; } if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) { top += Math.max( docElem.scrollTop, body.scrollTop ); left += Math.max( docElem.scrollLeft, body.scrollLeft ); } return { top: top, left: left }; }; } jQuery.offset = { initialize: function() { var body = document.body, container = document.createElement("div"), innerDiv, checkDiv, table, td, bodyMarginTop = parseFloat( jQuery.curCSS(body, "marginTop", true) ) || 0, html = "<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>"; jQuery.extend( container.style, { position: "absolute", top: 0, left: 0, margin: 0, border: 0, width: "1px", height: "1px", visibility: "hidden" } ); container.innerHTML = html; body.insertBefore( container, body.firstChild ); innerDiv = container.firstChild; checkDiv = innerDiv.firstChild; td = innerDiv.nextSibling.firstChild.firstChild; this.doesNotAddBorder = (checkDiv.offsetTop !== 5); this.doesAddBorderForTableAndCells = (td.offsetTop === 5); checkDiv.style.position = "fixed", checkDiv.style.top = "20px"; // safari subtracts parent border width here which is 5px this.supportsFixedPosition = (checkDiv.offsetTop === 20 || checkDiv.offsetTop === 15); checkDiv.style.position = checkDiv.style.top = ""; innerDiv.style.overflow = "hidden", innerDiv.style.position = "relative"; this.subtractsBorderForOverflowNotVisible = (checkDiv.offsetTop === -5); this.doesNotIncludeMarginInBodyOffset = (body.offsetTop !== bodyMarginTop); body.removeChild( container ); body = container = innerDiv = checkDiv = table = td = null; jQuery.offset.initialize = jQuery.noop; }, bodyOffset: function( body ) { var top = body.offsetTop, left = body.offsetLeft; jQuery.offset.initialize(); if ( jQuery.offset.doesNotIncludeMarginInBodyOffset ) { top += parseFloat( jQuery.curCSS(body, "marginTop", true) ) || 0; left += parseFloat( jQuery.curCSS(body, "marginLeft", true) ) || 0; } return { top: top, left: left }; }, setOffset: function( elem, options, i ) { // set position first, in-case top/left are set even on static elem if ( /static/.test( jQuery.curCSS( elem, "position" ) ) ) { elem.style.position = "relative"; } var curElem = jQuery( elem ), curOffset = curElem.offset(), curTop = parseInt( jQuery.curCSS( elem, "top", true ), 10 ) || 0, curLeft = parseInt( jQuery.curCSS( elem, "left", true ), 10 ) || 0; if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } var props = { top: (options.top - curOffset.top) + curTop, left: (options.left - curOffset.left) + curLeft }; if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ position: function() { /// <summary> /// Gets the top and left positions of an element relative to its offset parent. /// </summary> /// <returns type="Object">An object with two integer properties, 'top' and 'left'.</returns> if ( !this[0] ) { return null; } var elem = this[0], // Get *real* offsetParent offsetParent = this.offsetParent(), // Get correct offsets offset = this.offset(), parentOffset = /^body|html$/i.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset(); // Subtract element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 offset.top -= parseFloat( jQuery.curCSS(elem, "marginTop", true) ) || 0; offset.left -= parseFloat( jQuery.curCSS(elem, "marginLeft", true) ) || 0; // Add offsetParent borders parentOffset.top += parseFloat( jQuery.curCSS(offsetParent[0], "borderTopWidth", true) ) || 0; parentOffset.left += parseFloat( jQuery.curCSS(offsetParent[0], "borderLeftWidth", true) ) || 0; // Subtract the two offsets return { top: offset.top - parentOffset.top, left: offset.left - parentOffset.left }; }, offsetParent: function() { /// <summary> /// This method is internal. /// </summary> /// <private /> return this.map(function() { var offsetParent = this.offsetParent || document.body; while ( offsetParent && (!/^body|html$/i.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) { offsetParent = offsetParent.offsetParent; } return offsetParent; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( ["Left", "Top"], function( i, name ) { var method = "scroll" + name; jQuery.fn[ method ] = function(val) { /// <summary> /// Gets and optionally sets the scroll left offset of the first matched element. /// </summary> /// <param name="val" type="Number" integer="true" optional="true">A positive number representing the desired scroll left offset.</param> /// <returns type="Number" integer="true">The scroll left offset of the first matched element.</returns> var elem = this[0], win; if ( !elem ) { return null; } if ( val !== undefined ) { // Set the scroll offset return this.each(function() { win = getWindow( this ); if ( win ) { win.scrollTo( !i ? val : jQuery(win).scrollLeft(), i ? val : jQuery(win).scrollTop() ); } else { this[ method ] = val; } }); } else { win = getWindow( elem ); // Return the scroll offset return win ? ("pageXOffset" in win) ? win[ i ? "pageYOffset" : "pageXOffset" ] : jQuery.support.boxModel && win.document.documentElement[ method ] || win.document.body[ method ] : elem[ method ]; } }; }); // Create scrollLeft and scrollTop methods jQuery.each( ["Left", "Top"], function( i, name ) { var method = "scroll" + name; jQuery.fn[ method ] = function(val) { /// <summary> /// Gets and optionally sets the scroll top offset of the first matched element. /// </summary> /// <param name="val" type="Number" integer="true" optional="true">A positive number representing the desired scroll top offset.</param> /// <returns type="Number" integer="true">The scroll top offset of the first matched element.</returns> var elem = this[0], win; if ( !elem ) { return null; } if ( val !== undefined ) { // Set the scroll offset return this.each(function() { win = getWindow( this ); if ( win ) { win.scrollTo( !i ? val : jQuery(win).scrollLeft(), i ? val : jQuery(win).scrollTop() ); } else { this[ method ] = val; } }); } else { win = getWindow( elem ); // Return the scroll offset return win ? ("pageXOffset" in win) ? win[ i ? "pageYOffset" : "pageXOffset" ] : jQuery.support.boxModel && win.document.documentElement[ method ] || win.document.body[ method ] : elem[ method ]; } }; }); function getWindow( elem ) { return ("scrollTo" in elem && elem.document) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // Create innerHeight, innerWidth, outerHeight and outerWidth methods jQuery.each([ "Height" ], function( i, name ) { var type = name.toLowerCase(); // innerHeight and innerWidth jQuery.fn["inner" + name] = function() { /// <summary> /// Gets the inner height of the first matched element, excluding border but including padding. /// </summary> /// <returns type="Number" integer="true">The outer height of the first matched element.</returns> return this[0] ? jQuery.css( this[0], type, false, "padding" ) : null; }; // outerHeight and outerWidth jQuery.fn["outer" + name] = function( margin ) { /// <summary> /// Gets the outer height of the first matched element, including border and padding by default. /// </summary> /// <param name="margins" type="Map">A set of key/value pairs that specify the options for the method.</param> /// <returns type="Number" integer="true">The outer height of the first matched element.</returns> return this[0] ? jQuery.css( this[0], type, false, margin ? "margin" : "border" ) : null; }; jQuery.fn[ type ] = function( size ) { /// <summary> /// Set the CSS height of every matched element. If no explicit unit /// was specified (like 'em' or '%') then &quot;px&quot; is added to the width. If no parameter is specified, it gets /// the current computed pixel height of the first matched element. /// Part of CSS /// </summary> /// <returns type="jQuery" type="jQuery" /> /// <param name="cssProperty" type="String"> /// Set the CSS property to the specified value. Omit to get the value of the first matched element. /// </param> // Get window width or height var elem = this[0]; if ( !elem ) { return size == null ? null : this; } if ( jQuery.isFunction( size ) ) { return this.each(function( i ) { var self = jQuery( this ); self[ type ]( size.call( this, i, self[ type ]() ) ); }); } return ("scrollTo" in elem && elem.document) ? // does it walk and quack like a window? // Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode elem.document.compatMode === "CSS1Compat" && elem.document.documentElement[ "client" + name ] || elem.document.body[ "client" + name ] : // Get document width or height (elem.nodeType === 9) ? // is it a document // Either scroll[Width/Height] or offset[Width/Height], whichever is greater Math.max( elem.documentElement["client" + name], elem.body["scroll" + name], elem.documentElement["scroll" + name], elem.body["offset" + name], elem.documentElement["offset" + name] ) : // Get or set width or height on the element size === undefined ? // Get width or height on the element jQuery.css( elem, type ) : // Set the width or height on the element (default to pixels if value is unitless) this.css( type, typeof size === "string" ? size : size + "px" ); }; }); // Create innerHeight, innerWidth, outerHeight and outerWidth methods jQuery.each([ "Width" ], function( i, name ) { var type = name.toLowerCase(); // innerHeight and innerWidth jQuery.fn["inner" + name] = function() { /// <summary> /// Gets the inner width of the first matched element, excluding border but including padding. /// </summary> /// <returns type="Number" integer="true">The outer width of the first matched element.</returns> return this[0] ? jQuery.css( this[0], type, false, "padding" ) : null; }; // outerHeight and outerWidth jQuery.fn["outer" + name] = function( margin ) { /// <summary> /// Gets the outer width of the first matched element, including border and padding by default. /// </summary> /// <param name="margin" type="Map">A set of key/value pairs that specify the options for the method.</param> /// <returns type="Number" integer="true">The outer width of the first matched element.</returns> return this[0] ? jQuery.css( this[0], type, false, margin ? "margin" : "border" ) : null; }; jQuery.fn[ type ] = function( size ) { /// <summary> /// Set the CSS width of every matched element. If no explicit unit /// was specified (like 'em' or '%') then &quot;px&quot; is added to the width. If no parameter is specified, it gets /// the current computed pixel width of the first matched element. /// Part of CSS /// </summary> /// <returns type="jQuery" type="jQuery" /> /// <param name="cssProperty" type="String"> /// Set the CSS property to the specified value. Omit to get the value of the first matched element. /// </param> // Get window width or height var elem = this[0]; if ( !elem ) { return size == null ? null : this; } if ( jQuery.isFunction( size ) ) { return this.each(function( i ) { var self = jQuery( this ); self[ type ]( size.call( this, i, self[ type ]() ) ); }); } return ("scrollTo" in elem && elem.document) ? // does it walk and quack like a window? // Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode elem.document.compatMode === "CSS1Compat" && elem.document.documentElement[ "client" + name ] || elem.document.body[ "client" + name ] : // Get document width or height (elem.nodeType === 9) ? // is it a document // Either scroll[Width/Height] or offset[Width/Height], whichever is greater Math.max( elem.documentElement["client" + name], elem.body["scroll" + name], elem.documentElement["scroll" + name], elem.body["offset" + name], elem.documentElement["offset" + name] ) : // Get or set width or height on the element size === undefined ? // Get width or height on the element jQuery.css( elem, type ) : // Set the width or height on the element (default to pixels if value is unitless) this.css( type, typeof size === "string" ? size : size + "px" ); }; }); // Expose jQuery to the global object window.jQuery = window.$ = jQuery; })(window);
chester89/nugetApi
test/EndToEnd/ProjectTemplates/WebApplicationProject40.zip/Scripts/jquery-1.4.1-vsdoc.js
JavaScript
apache-2.0
242,990
<?php /* * This file is part of PHPUnit. * * (c) Sebastian Bergmann <sebastian@phpunit.de> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * Logical AND. * * @package PHPUnit * @subpackage Framework_Constraint * @author Sebastian Bergmann <sebastian@phpunit.de> * @author Bernhard Schussek <bschussek@2bepublished.at> * @copyright Sebastian Bergmann <sebastian@phpunit.de> * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://www.phpunit.de/ * @since Class available since Release 3.0.0 */ class PHPUnit_Framework_Constraint_And extends PHPUnit_Framework_Constraint { /** * @var PHPUnit_Framework_Constraint[] */ protected $constraints = array(); /** * @var PHPUnit_Framework_Constraint */ protected $lastConstraint = null; /** * @param PHPUnit_Framework_Constraint[] $constraints * @throws PHPUnit_Framework_Exception */ public function setConstraints(array $constraints) { $this->constraints = array(); foreach ($constraints as $constraint) { if (!($constraint instanceof PHPUnit_Framework_Constraint)) { throw new PHPUnit_Framework_Exception( 'All parameters to ' . __CLASS__ . ' must be a constraint object.' ); } $this->constraints[] = $constraint; } } /** * Evaluates the constraint for parameter $other * * If $returnResult is set to false (the default), an exception is thrown * in case of a failure. null is returned otherwise. * * If $returnResult is true, the result of the evaluation is returned as * a boolean value instead: true in case of success, false in case of a * failure. * * @param mixed $other Value or object to evaluate. * @param string $description Additional information about the test * @param bool $returnResult Whether to return a result or throw an exception * @return mixed * @throws PHPUnit_Framework_ExpectationFailedException */ public function evaluate($other, $description = '', $returnResult = false) { $success = true; $constraint = null; foreach ($this->constraints as $constraint) { if (!$constraint->evaluate($other, $description, true)) { $success = false; break; } } if ($returnResult) { return $success; } if (!$success) { $this->fail($other, $description); } } /** * Returns a string representation of the constraint. * * @return string */ public function toString() { $text = ''; foreach ($this->constraints as $key => $constraint) { if ($key > 0) { $text .= ' and '; } $text .= $constraint->toString(); } return $text; } /** * Counts the number of constraint elements. * * @return integer * @since Method available since Release 3.4.0 */ public function count() { $count = 0; foreach ($this->constraints as $constraint) { $count += count($constraint); } return $count; } }
Bradmau5/DxT-Appliances
Main Website/vendor/phpunit/phpunit/src/Framework/Constraint/And.php
PHP
apache-2.0
3,583
package servers import ( "crypto/rsa" "encoding/base64" "fmt" "net/url" "path" "reflect" "github.com/mitchellh/mapstructure" "github.com/rackspace/gophercloud" "github.com/rackspace/gophercloud/pagination" ) type serverResult struct { gophercloud.Result } // Extract interprets any serverResult as a Server, if possible. func (r serverResult) Extract() (*Server, error) { if r.Err != nil { return nil, r.Err } var response struct { Server Server `mapstructure:"server"` } config := &mapstructure.DecoderConfig{ DecodeHook: toMapFromString, Result: &response, } decoder, err := mapstructure.NewDecoder(config) if err != nil { return nil, err } err = decoder.Decode(r.Body) if err != nil { return nil, err } return &response.Server, nil } // CreateResult temporarily contains the response from a Create call. type CreateResult struct { serverResult } // GetResult temporarily contains the response from a Get call. type GetResult struct { serverResult } // UpdateResult temporarily contains the response from an Update call. type UpdateResult struct { serverResult } // DeleteResult temporarily contains the response from a Delete call. type DeleteResult struct { gophercloud.ErrResult } // RebuildResult temporarily contains the response from a Rebuild call. type RebuildResult struct { serverResult } // ActionResult represents the result of server action operations, like reboot type ActionResult struct { gophercloud.ErrResult } // RescueResult represents the result of a server rescue operation type RescueResult struct { ActionResult } // CreateImageResult represents the result of an image creation operation type CreateImageResult struct { gophercloud.Result } // GetPasswordResult represent the result of a get os-server-password operation. type GetPasswordResult struct { gophercloud.Result } // ExtractPassword gets the encrypted password. // If privateKey != nil the password is decrypted with the private key. // If privateKey == nil the encrypted password is returned and can be decrypted with: // echo '<pwd>' | base64 -D | openssl rsautl -decrypt -inkey <private_key> func (r GetPasswordResult) ExtractPassword(privateKey *rsa.PrivateKey) (string, error) { if r.Err != nil { return "", r.Err } var response struct { Password string `mapstructure:"password"` } err := mapstructure.Decode(r.Body, &response) if err == nil && privateKey != nil && response.Password != "" { return decryptPassword(response.Password, privateKey) } return response.Password, err } func decryptPassword(encryptedPassword string, privateKey *rsa.PrivateKey) (string, error) { b64EncryptedPassword := make([]byte, base64.StdEncoding.DecodedLen(len(encryptedPassword))) n, err := base64.StdEncoding.Decode(b64EncryptedPassword, []byte(encryptedPassword)) if err != nil { return "", fmt.Errorf("Failed to base64 decode encrypted password: %s", err) } password, err := rsa.DecryptPKCS1v15(nil, privateKey, b64EncryptedPassword[0:n]) if err != nil { return "", fmt.Errorf("Failed to decrypt password: %s", err) } return string(password), nil } // ExtractImageID gets the ID of the newly created server image from the header func (res CreateImageResult) ExtractImageID() (string, error) { if res.Err != nil { return "", res.Err } // Get the image id from the header u, err := url.ParseRequestURI(res.Header.Get("Location")) if err != nil { return "", fmt.Errorf("Failed to parse the image id: %s", err.Error()) } imageId := path.Base(u.Path) if imageId == "." || imageId == "/" { return "", fmt.Errorf("Failed to parse the ID of newly created image: %s", u) } return imageId, nil } // Extract interprets any RescueResult as an AdminPass, if possible. func (r RescueResult) Extract() (string, error) { if r.Err != nil { return "", r.Err } var response struct { AdminPass string `mapstructure:"adminPass"` } err := mapstructure.Decode(r.Body, &response) return response.AdminPass, err } // Server exposes only the standard OpenStack fields corresponding to a given server on the user's account. type Server struct { // ID uniquely identifies this server amongst all other servers, including those not accessible to the current tenant. ID string // TenantID identifies the tenant owning this server resource. TenantID string `mapstructure:"tenant_id"` // UserID uniquely identifies the user account owning the tenant. UserID string `mapstructure:"user_id"` // Name contains the human-readable name for the server. Name string // Updated and Created contain ISO-8601 timestamps of when the state of the server last changed, and when it was created. Updated string Created string HostID string // Status contains the current operational status of the server, such as IN_PROGRESS or ACTIVE. Status string // Progress ranges from 0..100. // A request made against the server completes only once Progress reaches 100. Progress int // AccessIPv4 and AccessIPv6 contain the IP addresses of the server, suitable for remote access for administration. AccessIPv4, AccessIPv6 string // Image refers to a JSON object, which itself indicates the OS image used to deploy the server. Image map[string]interface{} // Flavor refers to a JSON object, which itself indicates the hardware configuration of the deployed server. Flavor map[string]interface{} // Addresses includes a list of all IP addresses assigned to the server, keyed by pool. Addresses map[string]interface{} // Metadata includes a list of all user-specified key-value pairs attached to the server. Metadata map[string]interface{} // Links includes HTTP references to the itself, useful for passing along to other APIs that might want a server reference. Links []interface{} // KeyName indicates which public key was injected into the server on launch. KeyName string `json:"key_name" mapstructure:"key_name"` // AdminPass will generally be empty (""). However, it will contain the administrative password chosen when provisioning a new server without a set AdminPass setting in the first place. // Note that this is the ONLY time this field will be valid. AdminPass string `json:"adminPass" mapstructure:"adminPass"` // SecurityGroups includes the security groups that this instance has applied to it SecurityGroups []map[string]interface{} `json:"security_groups" mapstructure:"security_groups"` } // ServerPage abstracts the raw results of making a List() request against the API. // As OpenStack extensions may freely alter the response bodies of structures returned to the client, you may only safely access the // data provided through the ExtractServers call. type ServerPage struct { pagination.LinkedPageBase } // IsEmpty returns true if a page contains no Server results. func (page ServerPage) IsEmpty() (bool, error) { servers, err := ExtractServers(page) if err != nil { return true, err } return len(servers) == 0, nil } // NextPageURL uses the response's embedded link reference to navigate to the next page of results. func (page ServerPage) NextPageURL() (string, error) { type resp struct { Links []gophercloud.Link `mapstructure:"servers_links"` } var r resp err := mapstructure.Decode(page.Body, &r) if err != nil { return "", err } return gophercloud.ExtractNextURL(r.Links) } // ExtractServers interprets the results of a single page from a List() call, producing a slice of Server entities. func ExtractServers(page pagination.Page) ([]Server, error) { casted := page.(ServerPage).Body var response struct { Servers []Server `mapstructure:"servers"` } config := &mapstructure.DecoderConfig{ DecodeHook: toMapFromString, Result: &response, } decoder, err := mapstructure.NewDecoder(config) if err != nil { return nil, err } err = decoder.Decode(casted) return response.Servers, err } // MetadataResult contains the result of a call for (potentially) multiple key-value pairs. type MetadataResult struct { gophercloud.Result } // GetMetadataResult temporarily contains the response from a metadata Get call. type GetMetadataResult struct { MetadataResult } // ResetMetadataResult temporarily contains the response from a metadata Reset call. type ResetMetadataResult struct { MetadataResult } // UpdateMetadataResult temporarily contains the response from a metadata Update call. type UpdateMetadataResult struct { MetadataResult } // MetadatumResult contains the result of a call for individual a single key-value pair. type MetadatumResult struct { gophercloud.Result } // GetMetadatumResult temporarily contains the response from a metadatum Get call. type GetMetadatumResult struct { MetadatumResult } // CreateMetadatumResult temporarily contains the response from a metadatum Create call. type CreateMetadatumResult struct { MetadatumResult } // DeleteMetadatumResult temporarily contains the response from a metadatum Delete call. type DeleteMetadatumResult struct { gophercloud.ErrResult } // Extract interprets any MetadataResult as a Metadata, if possible. func (r MetadataResult) Extract() (map[string]string, error) { if r.Err != nil { return nil, r.Err } var response struct { Metadata map[string]string `mapstructure:"metadata"` } err := mapstructure.Decode(r.Body, &response) return response.Metadata, err } // Extract interprets any MetadatumResult as a Metadatum, if possible. func (r MetadatumResult) Extract() (map[string]string, error) { if r.Err != nil { return nil, r.Err } var response struct { Metadatum map[string]string `mapstructure:"meta"` } err := mapstructure.Decode(r.Body, &response) return response.Metadatum, err } func toMapFromString(from reflect.Kind, to reflect.Kind, data interface{}) (interface{}, error) { if (from == reflect.String) && (to == reflect.Map) { return map[string]interface{}{}, nil } return data, nil } // Address represents an IP address. type Address struct { Version int `mapstructure:"version"` Address string `mapstructure:"addr"` } // AddressPage abstracts the raw results of making a ListAddresses() request against the API. // As OpenStack extensions may freely alter the response bodies of structures returned // to the client, you may only safely access the data provided through the ExtractAddresses call. type AddressPage struct { pagination.SinglePageBase } // IsEmpty returns true if an AddressPage contains no networks. func (r AddressPage) IsEmpty() (bool, error) { addresses, err := ExtractAddresses(r) if err != nil { return true, err } return len(addresses) == 0, nil } // ExtractAddresses interprets the results of a single page from a ListAddresses() call, // producing a map of addresses. func ExtractAddresses(page pagination.Page) (map[string][]Address, error) { casted := page.(AddressPage).Body var response struct { Addresses map[string][]Address `mapstructure:"addresses"` } err := mapstructure.Decode(casted, &response) if err != nil { return nil, err } return response.Addresses, err } // NetworkAddressPage abstracts the raw results of making a ListAddressesByNetwork() request against the API. // As OpenStack extensions may freely alter the response bodies of structures returned // to the client, you may only safely access the data provided through the ExtractAddresses call. type NetworkAddressPage struct { pagination.SinglePageBase } // IsEmpty returns true if a NetworkAddressPage contains no addresses. func (r NetworkAddressPage) IsEmpty() (bool, error) { addresses, err := ExtractNetworkAddresses(r) if err != nil { return true, err } return len(addresses) == 0, nil } // ExtractNetworkAddresses interprets the results of a single page from a ListAddressesByNetwork() call, // producing a slice of addresses. func ExtractNetworkAddresses(page pagination.Page) ([]Address, error) { casted := page.(NetworkAddressPage).Body var response map[string][]Address err := mapstructure.Decode(casted, &response) if err != nil { return nil, err } var key string for k := range response { key = k } return response[key], err }
pmorie/origin
vendor/github.com/rackspace/gophercloud/openstack/compute/v2/servers/results.go
GO
apache-2.0
12,100
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "\u1295\u1309\u1206 \u1230\u12d3\u1270", "\u12f5\u1215\u122d \u1230\u12d3\u1275" ], "DAY": [ "\u1230\u1295\u1260\u1275", "\u1230\u1291\u12ed", "\u1230\u1209\u1235", "\u1228\u1261\u12d5", "\u1213\u1219\u1235", "\u12d3\u122d\u1262", "\u1240\u12f3\u121d" ], "ERANAMES": [ "\u12d3/\u12d3", "\u12d3/\u121d" ], "ERAS": [ "\u12d3/\u12d3", "\u12d3/\u121d" ], "FIRSTDAYOFWEEK": 0, "MONTH": [ "\u1325\u122a", "\u1208\u12ab\u1272\u1275", "\u1218\u130b\u1262\u1275", "\u121a\u12eb\u12dd\u12eb", "\u130d\u1295\u1266\u1275", "\u1230\u1290", "\u1213\u121d\u1208", "\u1290\u1213\u1230", "\u1218\u1235\u12a8\u1228\u121d", "\u1325\u1245\u121d\u1272", "\u1215\u12f3\u122d", "\u1273\u1215\u1233\u1235" ], "SHORTDAY": [ "\u1230\u1295\u1260\u1275", "\u1230\u1291\u12ed", "\u1230\u1209\u1235", "\u1228\u1261\u12d5", "\u1213\u1219\u1235", "\u12d3\u122d\u1262", "\u1240\u12f3\u121d" ], "SHORTMONTH": [ "\u1325\u122a", "\u1208\u12ab\u1272", "\u1218\u130b\u1262", "\u121a\u12eb\u12dd", "\u130d\u1295\u1266", "\u1230\u1290", "\u1213\u121d\u1208", "\u1290\u1213\u1230", "\u1218\u1235\u12a8", "\u1325\u1245\u121d", "\u1215\u12f3\u122d", "\u1273\u1215\u1233" ], "WEEKENDRANGE": [ 5, 6 ], "fullDate": "EEEE\u1361 dd MMMM \u1218\u12d3\u120d\u1272 y G", "longDate": "dd MMMM y", "medium": "dd-MMM-y h:mm:ss a", "mediumDate": "dd-MMM-y", "mediumTime": "h:mm:ss a", "short": "dd/MM/yy h:mm a", "shortDate": "dd/MM/yy", "shortTime": "h:mm a" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "Nfk", "DECIMAL_SEP": ".", "GROUP_SEP": ",", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "\u00a4-", "negSuf": "", "posPre": "\u00a4", "posSuf": "" } ] }, "id": "ti-er", "pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;} }); }]);
timschoch/PnP
Solutions/Governance.TimerJobs/Governance.TimerJobs.RemediationUx/Scripts/i18n/angular-locale_ti-er.js
JavaScript
apache-2.0
3,135
var baseClone = require('./_baseClone'); /** Used to compose bitmasks for cloning. */ var CLONE_SYMBOLS_FLAG = 4; /** * This method is like `_.clone` except that it accepts `customizer` which * is invoked to produce the cloned value. If `customizer` returns `undefined`, * cloning is handled by the method instead. The `customizer` is invoked with * up to four arguments; (value [, index|key, object, stack]). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to clone. * @param {Function} [customizer] The function to customize cloning. * @returns {*} Returns the cloned value. * @see _.cloneDeepWith * @example * * function customizer(value) { * if (_.isElement(value)) { * return value.cloneNode(false); * } * } * * var el = _.cloneWith(document.body, customizer); * * console.log(el === document.body); * // => false * console.log(el.nodeName); * // => 'BODY' * console.log(el.childNodes.length); * // => 0 */ function cloneWith(value, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return baseClone(value, CLONE_SYMBOLS_FLAG, customizer); } module.exports = cloneWith;
ColinLoveLucky/UIApplication
FourStage-Es6/node_modules/babel-preset-es2015/node_modules/babel-plugin-transform-es2015-function-name/node_modules/babel-types/node_modules/lodash/cloneWith.js
JavaScript
apache-2.0
1,194
package test import ( "bytes" "encoding/json" "fmt" "strings" "testing" "github.com/davecgh/go-spew/spew" fuzz "github.com/google/gofuzz" jsoniter "github.com/json-iterator/go" ) func Test_Roundtrip(t *testing.T) { fz := fuzz.New().MaxDepth(10).NilChance(0.3) for i := 0; i < 100; i++ { var before typeForTest fz.Fuzz(&before) jbStd, err := json.Marshal(before) if err != nil { t.Fatalf("failed to marshal with stdlib: %v", err) } if len(strings.TrimSpace(string(jbStd))) == 0 { t.Fatal("stdlib marshal produced empty result and no error") } jbIter, err := jsoniter.ConfigCompatibleWithStandardLibrary.Marshal(before) if err != nil { t.Fatalf("failed to marshal with jsoniter: %v", err) } if len(strings.TrimSpace(string(jbIter))) == 0 { t.Fatal("jsoniter marshal produced empty result and no error") } if string(jbStd) != string(jbIter) { t.Fatalf("marshal expected:\n %s\ngot:\n %s\nobj:\n %s", indent(jbStd, " "), indent(jbIter, " "), dump(before)) } var afterStd typeForTest err = json.Unmarshal(jbIter, &afterStd) if err != nil { t.Fatalf("failed to unmarshal with stdlib: %v\nvia:\n %s", err, indent(jbIter, " ")) } var afterIter typeForTest err = jsoniter.ConfigCompatibleWithStandardLibrary.Unmarshal(jbIter, &afterIter) if err != nil { t.Fatalf("failed to unmarshal with jsoniter: %v\nvia:\n %s", err, indent(jbIter, " ")) } if fingerprint(afterStd) != fingerprint(afterIter) { t.Fatalf("unmarshal expected:\n %s\ngot:\n %s\nvia:\n %s", dump(afterStd), dump(afterIter), indent(jbIter, " ")) } } } const indentStr = "> " func fingerprint(obj interface{}) string { c := spew.ConfigState{ SortKeys: true, SpewKeys: true, } return c.Sprintf("%v", obj) } func dump(obj interface{}) string { cfg := spew.ConfigState{ Indent: indentStr, } return cfg.Sdump(obj) } func indent(src []byte, prefix string) string { var buf bytes.Buffer err := json.Indent(&buf, src, prefix, indentStr) if err != nil { return fmt.Sprintf("!!! %v", err) } return buf.String() } func benchmarkMarshal(t *testing.B, name string, fn func(interface{}) ([]byte, error)) { t.ReportAllocs() t.ResetTimer() var obj typeForTest fz := fuzz.NewWithSeed(0).MaxDepth(10).NilChance(0.3) fz.Fuzz(&obj) for i := 0; i < t.N; i++ { jb, err := fn(obj) if err != nil { t.Fatalf("%s failed to marshal:\n input: %s\n error: %v", name, dump(obj), err) } _ = jb } } func benchmarkUnmarshal(t *testing.B, name string, fn func(data []byte, v interface{}) error) { t.ReportAllocs() t.ResetTimer() var before typeForTest fz := fuzz.NewWithSeed(0).MaxDepth(10).NilChance(0.3) fz.Fuzz(&before) jb, err := json.Marshal(before) if err != nil { t.Fatalf("failed to marshal: %v", err) } for i := 0; i < t.N; i++ { var after typeForTest err = fn(jb, &after) if err != nil { t.Fatalf("%s failed to unmarshal:\n input: %q\n error: %v", name, string(jb), err) } } } func BenchmarkStandardMarshal(t *testing.B) { benchmarkMarshal(t, "stdlib", json.Marshal) } func BenchmarkStandardUnmarshal(t *testing.B) { benchmarkUnmarshal(t, "stdlib", json.Unmarshal) } func BenchmarkJSONIterMarshalFastest(t *testing.B) { benchmarkMarshal(t, "jsoniter-fastest", jsoniter.ConfigFastest.Marshal) } func BenchmarkJSONIterUnmarshalFastest(t *testing.B) { benchmarkUnmarshal(t, "jsoniter-fastest", jsoniter.ConfigFastest.Unmarshal) } func BenchmarkJSONIterMarshalDefault(t *testing.B) { benchmarkMarshal(t, "jsoniter-default", jsoniter.Marshal) } func BenchmarkJSONIterUnmarshalDefault(t *testing.B) { benchmarkUnmarshal(t, "jsoniter-default", jsoniter.Unmarshal) } func BenchmarkJSONIterMarshalCompatible(t *testing.B) { benchmarkMarshal(t, "jsoniter-compat", jsoniter.ConfigCompatibleWithStandardLibrary.Marshal) } func BenchmarkJSONIterUnmarshalCompatible(t *testing.B) { benchmarkUnmarshal(t, "jsoniter-compat", jsoniter.ConfigCompatibleWithStandardLibrary.Unmarshal) }
dgoodwin/online-archivist
vendor/github.com/json-iterator/go/output_tests/array/struct_ptr_string/json_test.go
GO
apache-2.0
4,029
package sockets import ( "net" "net/url" "os" "strings" "golang.org/x/net/proxy" ) // GetProxyEnv allows access to the uppercase and the lowercase forms of // proxy-related variables. See the Go specification for details on these // variables. https://golang.org/pkg/net/http/ func GetProxyEnv(key string) string { proxyValue := os.Getenv(strings.ToUpper(key)) if proxyValue == "" { return os.Getenv(strings.ToLower(key)) } return proxyValue } // DialerFromEnvironment takes in a "direct" *net.Dialer and returns a // proxy.Dialer which will route the connections through the proxy using the // given dialer. func DialerFromEnvironment(direct *net.Dialer) (proxy.Dialer, error) { allProxy := GetProxyEnv("all_proxy") if len(allProxy) == 0 { return direct, nil } proxyURL, err := url.Parse(allProxy) if err != nil { return direct, err } proxyFromURL, err := proxy.FromURL(proxyURL, direct) if err != nil { return direct, err } noProxy := GetProxyEnv("no_proxy") if len(noProxy) == 0 { return proxyFromURL, nil } perHost := proxy.NewPerHost(proxyFromURL, direct) perHost.AddFromString(noProxy) return perHost, nil }
dlorenc/kubernetes
vendor/github.com/docker/go-connections/sockets/proxy.go
GO
apache-2.0
1,158
using System; using UnityEngine; namespace UnityStandardAssets.ImageEffects { [ExecuteInEditMode] [RequireComponent (typeof(Camera))] [AddComponentMenu ("Image Effects/Camera/Depth of Field (deprecated)") ] public class DepthOfFieldDeprecated : PostEffectsBase { public enum Dof34QualitySetting { OnlyBackground = 1, BackgroundAndForeground = 2, } public enum DofResolution { High = 2, Medium = 3, Low = 4, } public enum DofBlurriness { Low = 1, High = 2, VeryHigh = 4, } public enum BokehDestination { Background = 0x1, Foreground = 0x2, BackgroundAndForeground = 0x3, } static private int SMOOTH_DOWNSAMPLE_PASS = 6; static private float BOKEH_EXTRA_BLUR = 2.0f; public Dof34QualitySetting quality = Dof34QualitySetting.OnlyBackground; public DofResolution resolution = DofResolution.Low; public bool simpleTweakMode = true; public float focalPoint = 1.0f; public float smoothness = 0.5f; public float focalZDistance = 0.0f; public float focalZStartCurve = 1.0f; public float focalZEndCurve = 1.0f; private float focalStartCurve = 2.0f; private float focalEndCurve = 2.0f; private float focalDistance01 = 0.1f; public Transform objectFocus = null; public float focalSize = 0.0f; public DofBlurriness bluriness = DofBlurriness.High; public float maxBlurSpread = 1.75f; public float foregroundBlurExtrude = 1.15f; public Shader dofBlurShader; private Material dofBlurMaterial = null; public Shader dofShader; private Material dofMaterial = null; public bool visualize = false; public BokehDestination bokehDestination = BokehDestination.Background; private float widthOverHeight = 1.25f; private float oneOverBaseSize = 1.0f / 512.0f; public bool bokeh = false; public bool bokehSupport = true; public Shader bokehShader; public Texture2D bokehTexture; public float bokehScale = 2.4f; public float bokehIntensity = 0.15f; public float bokehThresholdContrast = 0.1f; public float bokehThresholdLuminance = 0.55f; public int bokehDownsample = 1; private Material bokehMaterial; private Camera _camera; void CreateMaterials () { dofBlurMaterial = CheckShaderAndCreateMaterial (dofBlurShader, dofBlurMaterial); dofMaterial = CheckShaderAndCreateMaterial (dofShader,dofMaterial); bokehSupport = bokehShader.isSupported; if (bokeh && bokehSupport && bokehShader) bokehMaterial = CheckShaderAndCreateMaterial (bokehShader, bokehMaterial); } public override bool CheckResources () { CheckSupport (true); dofBlurMaterial = CheckShaderAndCreateMaterial (dofBlurShader, dofBlurMaterial); dofMaterial = CheckShaderAndCreateMaterial (dofShader,dofMaterial); bokehSupport = bokehShader.isSupported; if (bokeh && bokehSupport && bokehShader) bokehMaterial = CheckShaderAndCreateMaterial (bokehShader, bokehMaterial); if (!isSupported) ReportAutoDisable (); return isSupported; } void OnDisable () { Quads.Cleanup (); } void OnEnable () { _camera = GetComponent<Camera>(); _camera.depthTextureMode |= DepthTextureMode.Depth; } float FocalDistance01 ( float worldDist) { return _camera.WorldToViewportPoint((worldDist-_camera.nearClipPlane) * _camera.transform.forward + _camera.transform.position).z / (_camera.farClipPlane-_camera.nearClipPlane); } int GetDividerBasedOnQuality () { int divider = 1; if (resolution == DofResolution.Medium) divider = 2; else if (resolution == DofResolution.Low) divider = 2; return divider; } int GetLowResolutionDividerBasedOnQuality ( int baseDivider) { int lowTexDivider = baseDivider; if (resolution == DofResolution.High) lowTexDivider *= 2; if (resolution == DofResolution.Low) lowTexDivider *= 2; return lowTexDivider; } private RenderTexture foregroundTexture = null; private RenderTexture mediumRezWorkTexture = null; private RenderTexture finalDefocus = null; private RenderTexture lowRezWorkTexture = null; private RenderTexture bokehSource = null; private RenderTexture bokehSource2 = null; void OnRenderImage (RenderTexture source, RenderTexture destination) { if (CheckResources()==false) { Graphics.Blit (source, destination); return; } if (smoothness < 0.1f) smoothness = 0.1f; // update needed focal & rt size parameter bokeh = bokeh && bokehSupport; float bokehBlurAmplifier = bokeh ? BOKEH_EXTRA_BLUR : 1.0f; bool blurForeground = quality > Dof34QualitySetting.OnlyBackground; float focal01Size = focalSize / (_camera.farClipPlane - _camera.nearClipPlane);; if (simpleTweakMode) { focalDistance01 = objectFocus ? (_camera.WorldToViewportPoint (objectFocus.position)).z / (_camera.farClipPlane) : FocalDistance01 (focalPoint); focalStartCurve = focalDistance01 * smoothness; focalEndCurve = focalStartCurve; blurForeground = blurForeground && (focalPoint > (_camera.nearClipPlane + Mathf.Epsilon)); } else { if (objectFocus) { var vpPoint= _camera.WorldToViewportPoint (objectFocus.position); vpPoint.z = (vpPoint.z) / (_camera.farClipPlane); focalDistance01 = vpPoint.z; } else focalDistance01 = FocalDistance01 (focalZDistance); focalStartCurve = focalZStartCurve; focalEndCurve = focalZEndCurve; blurForeground = blurForeground && (focalPoint > (_camera.nearClipPlane + Mathf.Epsilon)); } widthOverHeight = (1.0f * source.width) / (1.0f * source.height); oneOverBaseSize = 1.0f / 512.0f; dofMaterial.SetFloat ("_ForegroundBlurExtrude", foregroundBlurExtrude); dofMaterial.SetVector ("_CurveParams", new Vector4 (simpleTweakMode ? 1.0f / focalStartCurve : focalStartCurve, simpleTweakMode ? 1.0f / focalEndCurve : focalEndCurve, focal01Size * 0.5f, focalDistance01)); dofMaterial.SetVector ("_InvRenderTargetSize", new Vector4 (1.0f / (1.0f * source.width), 1.0f / (1.0f * source.height),0.0f,0.0f)); int divider = GetDividerBasedOnQuality (); int lowTexDivider = GetLowResolutionDividerBasedOnQuality (divider); AllocateTextures (blurForeground, source, divider, lowTexDivider); // WRITE COC to alpha channel // source is only being bound to detect y texcoord flip Graphics.Blit (source, source, dofMaterial, 3); // better DOWNSAMPLE (could actually be weighted for higher quality) Downsample (source, mediumRezWorkTexture); // BLUR A LITTLE first, which has two purposes // 1.) reduce jitter, noise, aliasing // 2.) produce the little-blur buffer used in composition later Blur (mediumRezWorkTexture, mediumRezWorkTexture, DofBlurriness.Low, 4, maxBlurSpread); if ((bokeh) && ((BokehDestination.Foreground & bokehDestination) != 0)) { dofMaterial.SetVector ("_Threshhold", new Vector4(bokehThresholdContrast, bokehThresholdLuminance, 0.95f, 0.0f)); // add and mark the parts that should end up as bokeh shapes Graphics.Blit (mediumRezWorkTexture, bokehSource2, dofMaterial, 11); // remove those parts (maybe even a little tittle bittle more) from the regurlarly blurred buffer //Graphics.Blit (mediumRezWorkTexture, lowRezWorkTexture, dofMaterial, 10); Graphics.Blit (mediumRezWorkTexture, lowRezWorkTexture);//, dofMaterial, 10); // maybe you want to reblur the small blur ... but not really needed. //Blur (mediumRezWorkTexture, mediumRezWorkTexture, DofBlurriness.Low, 4, maxBlurSpread); // bigger BLUR Blur (lowRezWorkTexture, lowRezWorkTexture, bluriness, 0, maxBlurSpread * bokehBlurAmplifier); } else { // bigger BLUR Downsample (mediumRezWorkTexture, lowRezWorkTexture); Blur (lowRezWorkTexture, lowRezWorkTexture, bluriness, 0, maxBlurSpread); } dofBlurMaterial.SetTexture ("_TapLow", lowRezWorkTexture); dofBlurMaterial.SetTexture ("_TapMedium", mediumRezWorkTexture); Graphics.Blit (null, finalDefocus, dofBlurMaterial, 3); // we are only adding bokeh now if the background is the only part we have to deal with if ((bokeh) && ((BokehDestination.Foreground & bokehDestination) != 0)) AddBokeh (bokehSource2, bokehSource, finalDefocus); dofMaterial.SetTexture ("_TapLowBackground", finalDefocus); dofMaterial.SetTexture ("_TapMedium", mediumRezWorkTexture); // needed for debugging/visualization // FINAL DEFOCUS (background) Graphics.Blit (source, blurForeground ? foregroundTexture : destination, dofMaterial, visualize ? 2 : 0); // FINAL DEFOCUS (foreground) if (blurForeground) { // WRITE COC to alpha channel Graphics.Blit (foregroundTexture, source, dofMaterial, 5); // DOWNSAMPLE (unweighted) Downsample (source, mediumRezWorkTexture); // BLUR A LITTLE first, which has two purposes // 1.) reduce jitter, noise, aliasing // 2.) produce the little-blur buffer used in composition later BlurFg (mediumRezWorkTexture, mediumRezWorkTexture, DofBlurriness.Low, 2, maxBlurSpread); if ((bokeh) && ((BokehDestination.Foreground & bokehDestination) != 0)) { dofMaterial.SetVector ("_Threshhold", new Vector4(bokehThresholdContrast * 0.5f, bokehThresholdLuminance, 0.0f, 0.0f)); // add and mark the parts that should end up as bokeh shapes Graphics.Blit (mediumRezWorkTexture, bokehSource2, dofMaterial, 11); // remove the parts (maybe even a little tittle bittle more) that will end up in bokeh space //Graphics.Blit (mediumRezWorkTexture, lowRezWorkTexture, dofMaterial, 10); Graphics.Blit (mediumRezWorkTexture, lowRezWorkTexture);//, dofMaterial, 10); // big BLUR BlurFg (lowRezWorkTexture, lowRezWorkTexture, bluriness, 1, maxBlurSpread * bokehBlurAmplifier); } else { // big BLUR BlurFg (mediumRezWorkTexture, lowRezWorkTexture, bluriness, 1, maxBlurSpread); } // simple upsample once Graphics.Blit (lowRezWorkTexture, finalDefocus); dofMaterial.SetTexture ("_TapLowForeground", finalDefocus); Graphics.Blit (source, destination, dofMaterial, visualize ? 1 : 4); if ((bokeh) && ((BokehDestination.Foreground & bokehDestination) != 0)) AddBokeh (bokehSource2, bokehSource, destination); } ReleaseTextures (); } void Blur ( RenderTexture from, RenderTexture to, DofBlurriness iterations, int blurPass, float spread) { RenderTexture tmp = RenderTexture.GetTemporary (to.width, to.height); if ((int)iterations > 1) { BlurHex (from, to, blurPass, spread, tmp); if ((int)iterations > 2) { dofBlurMaterial.SetVector ("offsets", new Vector4 (0.0f, spread * oneOverBaseSize, 0.0f, 0.0f)); Graphics.Blit (to, tmp, dofBlurMaterial, blurPass); dofBlurMaterial.SetVector ("offsets", new Vector4 (spread / widthOverHeight * oneOverBaseSize, 0.0f, 0.0f, 0.0f)); Graphics.Blit (tmp, to, dofBlurMaterial, blurPass); } } else { dofBlurMaterial.SetVector ("offsets", new Vector4 (0.0f, spread * oneOverBaseSize, 0.0f, 0.0f)); Graphics.Blit (from, tmp, dofBlurMaterial, blurPass); dofBlurMaterial.SetVector ("offsets", new Vector4 (spread / widthOverHeight * oneOverBaseSize, 0.0f, 0.0f, 0.0f)); Graphics.Blit (tmp, to, dofBlurMaterial, blurPass); } RenderTexture.ReleaseTemporary (tmp); } void BlurFg ( RenderTexture from, RenderTexture to, DofBlurriness iterations, int blurPass, float spread) { // we want a nice, big coc, hence we need to tap once from this (higher resolution) texture dofBlurMaterial.SetTexture ("_TapHigh", from); RenderTexture tmp = RenderTexture.GetTemporary (to.width, to.height); if ((int)iterations > 1) { BlurHex (from, to, blurPass, spread, tmp); if ((int)iterations > 2) { dofBlurMaterial.SetVector ("offsets", new Vector4 (0.0f, spread * oneOverBaseSize, 0.0f, 0.0f)); Graphics.Blit (to, tmp, dofBlurMaterial, blurPass); dofBlurMaterial.SetVector ("offsets", new Vector4 (spread / widthOverHeight * oneOverBaseSize, 0.0f, 0.0f, 0.0f)); Graphics.Blit (tmp, to, dofBlurMaterial, blurPass); } } else { dofBlurMaterial.SetVector ("offsets", new Vector4 (0.0f, spread * oneOverBaseSize, 0.0f, 0.0f)); Graphics.Blit (from, tmp, dofBlurMaterial, blurPass); dofBlurMaterial.SetVector ("offsets", new Vector4 (spread / widthOverHeight * oneOverBaseSize, 0.0f, 0.0f, 0.0f)); Graphics.Blit (tmp, to, dofBlurMaterial, blurPass); } RenderTexture.ReleaseTemporary (tmp); } void BlurHex ( RenderTexture from, RenderTexture to, int blurPass, float spread, RenderTexture tmp) { dofBlurMaterial.SetVector ("offsets", new Vector4 (0.0f, spread * oneOverBaseSize, 0.0f, 0.0f)); Graphics.Blit (from, tmp, dofBlurMaterial, blurPass); dofBlurMaterial.SetVector ("offsets", new Vector4 (spread / widthOverHeight * oneOverBaseSize, 0.0f, 0.0f, 0.0f)); Graphics.Blit (tmp, to, dofBlurMaterial, blurPass); dofBlurMaterial.SetVector ("offsets", new Vector4 (spread / widthOverHeight * oneOverBaseSize, spread * oneOverBaseSize, 0.0f, 0.0f)); Graphics.Blit (to, tmp, dofBlurMaterial, blurPass); dofBlurMaterial.SetVector ("offsets", new Vector4 (spread / widthOverHeight * oneOverBaseSize, -spread * oneOverBaseSize, 0.0f, 0.0f)); Graphics.Blit (tmp, to, dofBlurMaterial, blurPass); } void Downsample ( RenderTexture from, RenderTexture to) { dofMaterial.SetVector ("_InvRenderTargetSize", new Vector4 (1.0f / (1.0f * to.width), 1.0f / (1.0f * to.height), 0.0f, 0.0f)); Graphics.Blit (from, to, dofMaterial, SMOOTH_DOWNSAMPLE_PASS); } void AddBokeh ( RenderTexture bokehInfo, RenderTexture tempTex, RenderTexture finalTarget) { if (bokehMaterial) { var meshes = Quads.GetMeshes (tempTex.width, tempTex.height); // quads: exchanging more triangles with less overdraw RenderTexture.active = tempTex; GL.Clear (false, true, new Color (0.0f, 0.0f, 0.0f, 0.0f)); GL.PushMatrix (); GL.LoadIdentity (); // point filter mode is important, otherwise we get bokeh shape & size artefacts bokehInfo.filterMode = FilterMode.Point; float arW = (bokehInfo.width * 1.0f) / (bokehInfo.height * 1.0f); float sc = 2.0f / (1.0f * bokehInfo.width); sc += bokehScale * maxBlurSpread * BOKEH_EXTRA_BLUR * oneOverBaseSize; bokehMaterial.SetTexture ("_Source", bokehInfo); bokehMaterial.SetTexture ("_MainTex", bokehTexture); bokehMaterial.SetVector ("_ArScale",new Vector4 (sc, sc * arW, 0.5f, 0.5f * arW)); bokehMaterial.SetFloat ("_Intensity", bokehIntensity); bokehMaterial.SetPass (0); foreach(Mesh m in meshes) if (m) Graphics.DrawMeshNow (m, Matrix4x4.identity); GL.PopMatrix (); Graphics.Blit (tempTex, finalTarget, dofMaterial, 8); // important to set back as we sample from this later on bokehInfo.filterMode = FilterMode.Bilinear; } } void ReleaseTextures () { if (foregroundTexture) RenderTexture.ReleaseTemporary (foregroundTexture); if (finalDefocus) RenderTexture.ReleaseTemporary (finalDefocus); if (mediumRezWorkTexture) RenderTexture.ReleaseTemporary (mediumRezWorkTexture); if (lowRezWorkTexture) RenderTexture.ReleaseTemporary (lowRezWorkTexture); if (bokehSource) RenderTexture.ReleaseTemporary (bokehSource); if (bokehSource2) RenderTexture.ReleaseTemporary (bokehSource2); } void AllocateTextures ( bool blurForeground, RenderTexture source, int divider, int lowTexDivider) { foregroundTexture = null; if (blurForeground) foregroundTexture = RenderTexture.GetTemporary (source.width, source.height, 0); mediumRezWorkTexture = RenderTexture.GetTemporary (source.width / divider, source.height / divider, 0); finalDefocus = RenderTexture.GetTemporary (source.width / divider, source.height / divider, 0); lowRezWorkTexture = RenderTexture.GetTemporary (source.width / lowTexDivider, source.height / lowTexDivider, 0); bokehSource = null; bokehSource2 = null; if (bokeh) { bokehSource = RenderTexture.GetTemporary (source.width / (lowTexDivider * bokehDownsample), source.height / (lowTexDivider * bokehDownsample), 0, RenderTextureFormat.ARGBHalf); bokehSource2 = RenderTexture.GetTemporary (source.width / (lowTexDivider * bokehDownsample), source.height / (lowTexDivider * bokehDownsample), 0, RenderTextureFormat.ARGBHalf); bokehSource.filterMode = FilterMode.Bilinear; bokehSource2.filterMode = FilterMode.Bilinear; RenderTexture.active = bokehSource2; GL.Clear (false, true, new Color(0.0f, 0.0f, 0.0f, 0.0f)); } // to make sure: always use bilinear filter setting source.filterMode = FilterMode.Bilinear; finalDefocus.filterMode = FilterMode.Bilinear; mediumRezWorkTexture.filterMode = FilterMode.Bilinear; lowRezWorkTexture.filterMode = FilterMode.Bilinear; if (foregroundTexture) foregroundTexture.filterMode = FilterMode.Bilinear; } } }
Rckdrigo/Emma
Assets/Standard Assets/Effects/ImageEffects/Scripts/DepthOfFieldDeprecated.cs
C#
artistic-2.0
20,008
""" naive ~~~~~ Implements some very "naive" prediction techniques, mainly for baseline comparisons. """ from . import predictors import numpy as _np try: import scipy.stats as _stats except Exception: import sys print("Failed to load scipy.stats", file=sys.stderr) _stats = None class CountingGridKernel(predictors.DataTrainer): """Makes "predictions" by simply laying down a grid, and then counting the number of events in each grid cell to generate a relative risk. This can also be used to produce plots of the actual events which occurred: essentially a two-dimensional histogram. :param grid_width: The width of each grid cell. :param grid_height: The height of each grid cell, if None, then the same as `width`. :param region: Optionally, the :class:`RectangularRegion` to base the grid on. If not specified, this will be the bounding box of the data. """ def __init__(self, grid_width, grid_height = None, region = None): self.grid_width = grid_width self.grid_height = grid_height self.region = region def predict(self): """Produces an instance of :class:`GridPredictionArray` based upon the set :attrib:`region` (defaulting to the bounding box of the input data). Each entry of the "risk intensity matrix" will simply be the count of events in that grid cell. Changing the "region" may be important, as it will affect exactly which grid cell an event falls into. Events are always clipped to the region before being assigned to cells. (This is potentially important if the region is not an exact multiple of the grid size.) """ if self.region is None: region = self.data.bounding_box else: region = self.region xsize, ysize = region.grid_size(self.grid_width, self.grid_height) height = self.grid_width if self.grid_height is None else self.grid_height matrix = _np.zeros((ysize, xsize)) mask = ( (self.data.xcoords >= region.xmin) & (self.data.xcoords <= region.xmax) & (self.data.ycoords >= region.ymin) & (self.data.ycoords <= region.ymax) ) xc, yc = self.data.xcoords[mask], self.data.ycoords[mask] xg = _np.floor((xc - region.xmin) / self.grid_width).astype(_np.int) yg = _np.floor((yc - region.ymin) / height).astype(_np.int) for x, y in zip(xg, yg): matrix[y][x] += 1 return predictors.GridPredictionArray(self.grid_width, height, matrix, region.xmin, region.ymin) class ScipyKDE(predictors.DataTrainer): """A light wrapper around the `scipy` Gaussian KDE. Uses just the space coordinates of the events to estimate a risk density. """ def __init__(self): pass def predict(self, bw_method = None): """Produces an instance of :class:`KernelRiskPredictor` wrapping the result of the call to `scipy.stats.kde.gaussian_kde()`. :param bw_method: The bandwidth estimation method, to be passed to `scipy`. Defaults to None (currently the "scott" method). """ kernel = _stats.kde.gaussian_kde(self.data.coords, bw_method) return predictors.KernelRiskPredictor(kernel) def grid_predict(self, grid_size, bw_method = None): """Produces an instance of :class:`GridPredictionArray` wrapping the result of the call to `scipy.stats.kde.gaussian_kde()`. The region used is the bounding box of the input data. For more control, use the :method:`predict` and set the offset and grid size to sample down to a custom grid. :param grid_size: The width and height of each grid cell. :param bw_method: The bandwidth estimation method, to be passed to `scipy`. Defaults to None (currently the "scott" method). """ kernel = _stats.kde.gaussian_kde(self.data.coords, bw_method) region = self.data.bounding_box return predictors.grid_prediction_from_kernel(kernel, region, grid_size)
QuantCrimAtLeeds/PredictCode
open_cp/naive.py
Python
artistic-2.0
4,114
package com.server; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; import java.text.SimpleDateFormat; import java.util.Date; public class ClientThread extends Thread { public Socket clientSocket; public ServerThread serverThread; public DataInputStream dis; public DataOutputStream dos; public String client_userID; private boolean flag_exit = false; public ClientThread(Socket socket, ServerThread serverThread){ clientSocket = socket; this.serverThread = serverThread; try { dis = new DataInputStream(clientSocket.getInputStream()); dos = new DataOutputStream(clientSocket.getOutputStream()); } catch (IOException e) { e.printStackTrace(); } } @Override public void run() { while(flag_exit){ try { String Message = dis.readUTF(); if(Message.contains("@login")){ String [] userInfo = Message.split("@login"); int userID = Integer.parseInt(userInfo[1]); serverThread.users.remove(userID); if(serverThread.users.containsValue(userInfo[0])){ for(int i = 0; i < serverThread.clients.size(); i++){ int id = (int)serverThread.clients.get(i).getId(); if(serverThread.users.get(id).equals(userInfo[0])){ serverThread.users.remove(id); serverThread.users.put(id, userInfo[0] + "_" + id); break; } } serverThread.users.put(Integer.parseInt(userInfo[1]), userInfo[0] + "_" + userInfo[1]); }else{ serverThread.users.put(userID, userInfo[0]); } Message = null; StringBuffer sb = new StringBuffer(); synchronized (serverThread.clients) { for(int i = 0; i < serverThread.clients.size(); i++){ int threadID = (int) serverThread.clients.elementAt(i).getId(); sb.append((String)serverThread.users.get(new Integer(threadID)) + "@userlist"); sb.append(threadID + "@userlist"); } } String userNames = new String(sb); serverThread.serverFrame.setDisUsers(userNames); Message = userNames; }else{ if(Message.contains("@exit")){ String [] userInfo = Message.split("@exit"); int userID = Integer.parseInt(userInfo[1]); serverThread.users.remove(userID); Message = null; StringBuffer sb = new StringBuffer(); synchronized (serverThread.clients) { for(int i = 0; i < serverThread.clients.size(); i++){ int threadID = (int) serverThread.clients.elementAt(i).getId(); if(userID == threadID){ serverThread.clients.removeElementAt(i); i--; }else{ sb.append((String)serverThread.users.get(new Integer(threadID)) + "@userlist"); sb.append(threadID + "@userlist"); } } } String userNames = new String(sb); if(userNames.equals("")){ serverThread.serverFrame.setDisUsers("@userlist"); }else{ serverThread.serverFrame.setDisUsers(userNames); } Message = userNames; }else{ if(Message.contains("@chat")){ String[] chat = Message.split("@chat"); StringBuffer sb = new StringBuffer(); SimpleDateFormat form = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String date = form.format(new Date()); sb.append(chat[0] + " " + date + "\n"); sb.append(chat[2] + "@chat"); String str = new String(sb); Message = str; serverThread.serverFrame.setDisMess(Message); }else{ if(Message.contains("@single")){ } } } } synchronized (serverThread.messages) { if(Message != null){ serverThread.messages.addElement(Message); } } if(Message.contains("@exit")){ this.clientSocket.close(); flag_exit = false; } } catch (IOException e) {} } } public void closeClienthread(ClientThread clientThread) { if(clientThread.clientSocket != null){ try { clientThread.clientSocket.close(); } catch (IOException e) { System.out.println("server's clientSocket is null"); } } try { setFlag_exit(false); } catch (Throwable e) { e.printStackTrace(); } } public void setFlag_exit(boolean b) { flag_exit = b; } }
DuGuQiuBai/Java
day26/resource/chat_socket_server/src/com/server/ClientThread.java
Java
artistic-2.0
4,211
var test = require("tap").test , LRU = require("../") test("basic", function (t) { var cache = new LRU({max: 10}) cache.set("key", "value") t.equal(cache.get("key"), "value") t.equal(cache.get("nada"), undefined) t.equal(cache.length, 1) t.equal(cache.max, 10) t.end() }) test("least recently set", function (t) { var cache = new LRU(2) cache.set("a", "A") cache.set("b", "B") cache.set("c", "C") t.equal(cache.get("c"), "C") t.equal(cache.get("b"), "B") t.equal(cache.get("a"), undefined) t.end() }) test("lru recently gotten", function (t) { var cache = new LRU(2) cache.set("a", "A") cache.set("b", "B") cache.get("a") cache.set("c", "C") t.equal(cache.get("c"), "C") t.equal(cache.get("b"), undefined) t.equal(cache.get("a"), "A") t.end() }) test("del", function (t) { var cache = new LRU(2) cache.set("a", "A") cache.del("a") t.equal(cache.get("a"), undefined) t.end() }) test("max", function (t) { var cache = new LRU(3) // test changing the max, verify that the LRU items get dropped. cache.max = 100 for (var i = 0; i < 100; i ++) cache.set(i, i) t.equal(cache.length, 100) for (var i = 0; i < 100; i ++) { t.equal(cache.get(i), i) } cache.max = 3 t.equal(cache.length, 3) for (var i = 0; i < 97; i ++) { t.equal(cache.get(i), undefined) } for (var i = 98; i < 100; i ++) { t.equal(cache.get(i), i) } // now remove the max restriction, and try again. cache.max = "hello" for (var i = 0; i < 100; i ++) cache.set(i, i) t.equal(cache.length, 100) for (var i = 0; i < 100; i ++) { t.equal(cache.get(i), i) } // should trigger an immediate resize cache.max = 3 t.equal(cache.length, 3) for (var i = 0; i < 97; i ++) { t.equal(cache.get(i), undefined) } for (var i = 98; i < 100; i ++) { t.equal(cache.get(i), i) } t.end() }) test("reset", function (t) { var cache = new LRU(10) cache.set("a", "A") cache.set("b", "B") cache.reset() t.equal(cache.length, 0) t.equal(cache.max, 10) t.equal(cache.get("a"), undefined) t.equal(cache.get("b"), undefined) t.end() }) // Note: `<cache>.dump()` is a debugging tool only. No guarantees are made // about the format/layout of the response. test("dump", function (t) { var cache = new LRU(10) var d = cache.dump(); t.equal(Object.keys(d).length, 0, "nothing in dump for empty cache") cache.set("a", "A") var d = cache.dump() // { a: { key: "a", value: "A", lu: 0 } } t.ok(d.a) t.equal(d.a.key, "a") t.equal(d.a.value, "A") t.equal(d.a.lu, 0) cache.set("b", "B") cache.get("b") d = cache.dump() t.ok(d.b) t.equal(d.b.key, "b") t.equal(d.b.value, "B") t.equal(d.b.lu, 2) t.end() }) test("basic with weighed length", function (t) { var cache = new LRU({ max: 100, length: function (item) { return item.size } }) cache.set("key", {val: "value", size: 50}) t.equal(cache.get("key").val, "value") t.equal(cache.get("nada"), undefined) t.equal(cache.lengthCalculator(cache.get("key")), 50) t.equal(cache.length, 50) t.equal(cache.max, 100) t.end() }) test("weighed length item too large", function (t) { var cache = new LRU({ max: 10, length: function (item) { return item.size } }) t.equal(cache.max, 10) // should fall out immediately cache.set("key", {val: "value", size: 50}) t.equal(cache.length, 0) t.equal(cache.get("key"), undefined) t.end() }) test("least recently set with weighed length", function (t) { var cache = new LRU({ max:8, length: function (item) { return item.length } }) cache.set("a", "A") cache.set("b", "BB") cache.set("c", "CCC") cache.set("d", "DDDD") t.equal(cache.get("d"), "DDDD") t.equal(cache.get("c"), "CCC") t.equal(cache.get("b"), undefined) t.equal(cache.get("a"), undefined) t.end() }) test("lru recently gotten with weighed length", function (t) { var cache = new LRU({ max: 8, length: function (item) { return item.length } }) cache.set("a", "A") cache.set("b", "BB") cache.set("c", "CCC") cache.get("a") cache.get("b") cache.set("d", "DDDD") t.equal(cache.get("c"), undefined) t.equal(cache.get("d"), "DDDD") t.equal(cache.get("b"), "BB") t.equal(cache.get("a"), "A") t.end() }) test("set returns proper booleans", function(t) { var cache = new LRU({ max: 5, length: function (item) { return item.length } }) t.equal(cache.set("a", "A"), true) // should return false for max exceeded t.equal(cache.set("b", "donuts"), false) t.equal(cache.set("b", "B"), true) t.equal(cache.set("c", "CCCC"), true) t.end() }) test("drop the old items", function(t) { var cache = new LRU({ max: 5, maxAge: 50 }) cache.set("a", "A") setTimeout(function () { cache.set("b", "b") t.equal(cache.get("a"), "A") }, 25) setTimeout(function () { cache.set("c", "C") // timed out t.notOk(cache.get("a")) }, 60) setTimeout(function () { t.notOk(cache.get("b")) t.equal(cache.get("c"), "C") }, 90) setTimeout(function () { t.notOk(cache.get("c")) t.end() }, 155) }) test("disposal function", function(t) { var disposed = false var cache = new LRU({ max: 1, dispose: function (k, n) { disposed = n } }) cache.set(1, 1) cache.set(2, 2) t.equal(disposed, 1) cache.set(3, 3) t.equal(disposed, 2) cache.reset() t.equal(disposed, 3) t.end() }) test("disposal function on too big of item", function(t) { var disposed = false var cache = new LRU({ max: 1, length: function (k) { return k.length }, dispose: function (k, n) { disposed = n } }) var obj = [ 1, 2 ] t.equal(disposed, false) cache.set("obj", obj) t.equal(disposed, obj) t.end() }) test("has()", function(t) { var cache = new LRU({ max: 1, maxAge: 10 }) cache.set('foo', 'bar') t.equal(cache.has('foo'), true) cache.set('blu', 'baz') t.equal(cache.has('foo'), false) t.equal(cache.has('blu'), true) setTimeout(function() { t.equal(cache.has('blu'), false) t.end() }, 15) }) test("stale", function(t) { var cache = new LRU({ maxAge: 10, stale: true }) cache.set('foo', 'bar') t.equal(cache.get('foo'), 'bar') t.equal(cache.has('foo'), true) setTimeout(function() { t.equal(cache.has('foo'), false) t.equal(cache.get('foo'), 'bar') t.equal(cache.get('foo'), undefined) t.end() }, 15) }) test("lru update via set", function(t) { var cache = LRU({ max: 2 }); cache.set('foo', 1); cache.set('bar', 2); cache.del('bar'); cache.set('baz', 3); cache.set('qux', 4); t.equal(cache.get('foo'), undefined) t.equal(cache.get('bar'), undefined) t.equal(cache.get('baz'), 3) t.equal(cache.get('qux'), 4) t.end() }) test("least recently set w/ peek", function (t) { var cache = new LRU(2) cache.set("a", "A") cache.set("b", "B") t.equal(cache.peek("a"), "A") cache.set("c", "C") t.equal(cache.get("c"), "C") t.equal(cache.get("b"), "B") t.equal(cache.get("a"), undefined) t.end() })
metazool/herenow
node_modules/bower/node_modules/lru-cache/test/basic.js
JavaScript
artistic-2.0
7,105
class GstPluginsGood < Formula desc "GStreamer plugins (well-supported, under the LGPL)" homepage "http://gstreamer.freedesktop.org/" stable do url "http://gstreamer.freedesktop.org/src/gst-plugins-good/gst-plugins-good-1.4.5.tar.xz" mirror "http://ftp.osuosl.org/pub/blfs/svn/g/gst-plugins-good-1.4.5.tar.xz" sha256 "79b1b5f3f7bcaa8a615202eb5e176121eeb8336960f70687e536ad78dbc7e641" depends_on "check" => :optional end bottle do sha1 "184f6be9e300566f37e7b014cca49f78018c36d4" => :yosemite sha1 "a05a8f0dc08ea2626623f30dcb2cc458bd973b7e" => :mavericks sha1 "7ce582ddab67b58d87469d112745144a0cf0edd2" => :mountain_lion end head do url "git://anongit.freedesktop.org/gstreamer/gst-plugins-good" depends_on "autoconf" => :build depends_on "automake" => :build depends_on "libtool" => :build depends_on "check" end depends_on "pkg-config" => :build depends_on "gettext" depends_on "gst-plugins-base" depends_on "libsoup" depends_on :x11 => :optional # The set of optional dependencies is based on the intersection of # gst-plugins-good-0.10.30/REQUIREMENTS and Homebrew formulae depends_on "orc" => :optional depends_on "gtk+" => :optional depends_on "aalib" => :optional depends_on "libcdio" => :optional depends_on "esound" => :optional depends_on "flac" => [:optional, "with-libogg"] depends_on "jpeg" => :optional depends_on "libcaca" => :optional depends_on "libdv" => :optional depends_on "libshout" => :optional depends_on "speex" => :optional depends_on "taglib" => :optional depends_on "libpng" => :optional depends_on "libvpx" => :optional depends_on "libogg" if build.with? "flac" def install args = %W[ --prefix=#{prefix} --disable-gtk-doc --disable-goom --with-default-videosink=ximagesink --disable-debug --disable-dependency-tracking --disable-silent-rules ] if build.with? "x11" args << "--with-x" else args << "--disable-x" end if build.head? ENV["NOCONFIGURE"] = "yes" system "./autogen.sh" end system "./configure", *args system "make" system "make", "install" end end
pedromaltez-forks/homebrew
Library/Formula/gst-plugins-good.rb
Ruby
bsd-2-clause
2,216
/* * Copyright (c) 2014. Real Time Genomics Limited. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.rtg.usage; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.net.URI; import java.net.URISyntaxException; import com.rtg.launcher.AbstractCli; import com.rtg.launcher.CommonFlags; import com.rtg.util.StringUtils; import com.rtg.util.cli.CommonFlagCategories; import com.rtg.util.diagnostic.Diagnostic; import com.rtg.util.diagnostic.NoTalkbackSlimException; /** * module entrance for usage server */ public class UsageServerCli extends AbstractCli { private static final String PORT = "port"; private static final String THREADS = "threads"; // these can be used to check if the server has been started if we're called programmatically protected final Object mSync; private boolean mStarted = false; /** * Constructor */ public UsageServerCli() { mSync = new Object(); mSuppressUsage = true; } @Override public String moduleName() { return "usageserver"; } @Override public String description() { return "run a local server for collecting RTG command usage information"; } boolean getStarted() { synchronized (mSync) { return mStarted; } } @Override protected void initFlags() { final String host = mUsageLogger.getUsageConfiguration().getUsageHost(); int defaultPort = 8080; if (host != null) { try { final URI uri = new URI(host); if (uri.getScheme() != null && "http".equalsIgnoreCase(uri.getScheme())) { final int hostPort = uri.getPort(); defaultPort = hostPort == -1 ? 80 : hostPort; } } catch (URISyntaxException e) { throw new NoTalkbackSlimException("Malformed usage host specified in usage configuration: " + host); } } CommonFlagCategories.setCategories(mFlags); mFlags.setDescription("Start usage tracking server."); mFlags.registerOptional('p', PORT, Integer.class, CommonFlags.INT, "port on which to listen for usage logging connections.", defaultPort).setCategory(CommonFlagCategories.UTILITY); mFlags.registerOptional('T', THREADS, Integer.class, CommonFlags.INT, "number of worker threads to handle incoming connections.", 4).setCategory(CommonFlagCategories.UTILITY); } @Override protected int mainExec(OutputStream out, PrintStream err) throws IOException { Diagnostic.info("Checking usage configuration."); if (!mUsageLogger.getUsageConfiguration().isEnabled()) { throw new NoTalkbackSlimException("Cannot start usage server without RTG_USAGE configuration option set. " + UsageLogging.SEE_MANUAL); } else if (mUsageLogger.getUsageConfiguration().getUsageDir() == null) { throw new NoTalkbackSlimException("Cannot start usage server without RTG_USAGE_DIR configuration option set. " + UsageLogging.SEE_MANUAL); } final Integer port = (Integer) mFlags.getValue(PORT); final String configHost = mUsageLogger.getUsageConfiguration().getUsageHost(); // Output some warnings if the port doesn't correspond with where the clients will be pointing if (configHost != null) { try { final URI uri = new URI(configHost); if (uri.getScheme() != null && "http".equalsIgnoreCase(uri.getScheme())) { final int configPort = uri.getPort() == -1 ? 80 : uri.getPort(); if (configPort != port) { Diagnostic.warning("Specified port " + port + " does not correspond with port from usage configuration: " + configPort); } } else { Diagnostic.warning("This server (HTTP on port " + port + ") does not correspond to current usage configuration: " + configHost); } } catch (URISyntaxException e) { throw new NoTalkbackSlimException("Malformed usage host URI specified in usage configuration: " + configHost); } } else { Diagnostic.warning("Clients will not be able to connect until RTG_USAGE_HOST has been set. " + UsageLogging.SEE_MANUAL); } final UsageServer us = new UsageServer(port, new File(mUsageLogger.getUsageConfiguration().getUsageDir()), (Integer) mFlags.getValue(THREADS)); synchronized (mSync) { us.start(); out.write(("Usage server listening on port " + us.getPort() + StringUtils.LS).getBytes()); mStarted = true; try { boolean cont = true; while (cont) { try { mSync.wait(1000); } catch (InterruptedException e) { cont = false; } } } finally { us.end(); } } return 0; } }
RealTimeGenomics/rtg-tools
src/com/rtg/usage/UsageServerCli.java
Java
bsd-2-clause
5,967
INSERT INTO `listvalues` (`ListID`,`instance`,`scope`,`ValueKey`,`ValueDesc`,`OrderID`,`modified`) SELECT `ListID`,'lava','crms-nacc','udssubjectdemo','3',3,NOW() FROM `list` where `ListName`='InstrumentVersions'; INSERT INTO `listvalues` (`ListID`,`instance`,`scope`,`ValueKey`,`ValueDesc`,`OrderID`,`modified`) SELECT `ListID`,'lava','crms-nacc','udsinformantdemo','3',3,NOW() FROM `list` where `ListName`='InstrumentVersions'; INSERT INTO `listvalues` (`ListID`,`instance`,`scope`,`ValueKey`,`ValueDesc`,`OrderID`,`modified`) SELECT `ListID`,'lava','crms-nacc','udsfamilyhistory','3',3,NOW() FROM `list` where `ListName`='InstrumentVersions'; INSERT INTO `listvalues` (`ListID`,`instance`,`scope`,`ValueKey`,`ValueDesc`,`OrderID`,`modified`) SELECT `ListID`,'lava','crms-nacc','udsmedications','3',3,NOW() FROM `list` where `ListName`='InstrumentVersions'; INSERT INTO `listvalues` (`ListID`,`instance`,`scope`,`ValueKey`,`ValueDesc`,`OrderID`,`modified`) SELECT `ListID`,'lava','crms-nacc','udshealthhistory','3',3,NOW() FROM `list` where `ListName`='InstrumentVersions'; INSERT INTO `listvalues` (`ListID`,`instance`,`scope`,`ValueKey`,`ValueDesc`,`OrderID`,`modified`) SELECT `ListID`,'lava','crms-nacc','udsphysical','3',3,NOW() FROM `list` where `ListName`='InstrumentVersions'; INSERT INTO `listvalues` (`ListID`,`instance`,`scope`,`ValueKey`,`ValueDesc`,`OrderID`,`modified`) SELECT `ListID`,'lava','crms-nacc','udscdr','3',3,NOW() FROM `list` where `ListName`='InstrumentVersions'; INSERT INTO `listvalues` (`ListID`,`instance`,`scope`,`ValueKey`,`ValueDesc`,`OrderID`,`modified`) SELECT `ListID`,'lava','crms-nacc','udsnpi','3',3,NOW() FROM `list` where `ListName`='InstrumentVersions'; INSERT INTO `listvalues` (`ListID`,`instance`,`scope`,`ValueKey`,`ValueDesc`,`OrderID`,`modified`) SELECT `ListID`,'lava','crms-nacc','udsgds','3',3,NOW() FROM `list` where `ListName`='InstrumentVersions'; INSERT INTO `listvalues` (`ListID`,`instance`,`scope`,`ValueKey`,`ValueDesc`,`OrderID`,`modified`) SELECT `ListID`,'lava','crms-nacc','udsfaq','3',3,NOW() FROM `list` where `ListName`='InstrumentVersions'; INSERT INTO `listvalues` (`ListID`,`instance`,`scope`,`ValueKey`,`ValueDesc`,`OrderID`,`modified`) SELECT `ListID`,'lava','crms-nacc','udsappraisal','3',3,NOW() FROM `list` where `ListName`='InstrumentVersions'; INSERT INTO `listvalues` (`ListID`,`instance`,`scope`,`ValueKey`,`ValueDesc`,`OrderID`,`modified`) SELECT `ListID`,'lava','crms-nacc','udssymptomsonset','3',3,NOW() FROM `list` where `ListName`='InstrumentVersions'; INSERT INTO `listvalues` (`ListID`,`instance`,`scope`,`ValueKey`,`ValueDesc`,`OrderID`,`modified`) SELECT `ListID`,'lava','crms-nacc','udsdiagnosis','3',3,NOW() FROM `list` where `ListName`='InstrumentVersions'; INSERT INTO `listvalues` (`ListID`,`instance`,`scope`,`ValueKey`,`ValueDesc`,`OrderID`,`modified`) SELECT `ListID`,'lava','crms-nacc','udsformchecklist','3',3,NOW() FROM `list` where `ListName`='InstrumentVersions'; INSERT INTO `listvalues` (`ListID`,`instance`,`scope`,`ValueKey`,`ValueDesc`,`OrderID`,`modified`) SELECT `ListID`,'lava','crms-nacc','udsmedicalconditions','3',3,NOW() FROM `list` where `ListName`='InstrumentVersions'; INSERT INTO `listvalues` (`ListID`,`instance`,`scope`,`ValueKey`,`ValueDesc`,`OrderID`,`modified`) SELECT `ListID`,'lava','crms-nacc','udsmilestone','3',3,NOW() FROM `list` where `ListName`='InstrumentVersions'; INSERT INTO `listvalues` (`ListID`,`instance`,`scope`,`ValueKey`,`ValueDesc`,`OrderID`,`modified`) SELECT `ListID`,'lava','crms-nacc','udsneuropsychmoca','3',3,NOW() FROM `list` where `ListName`='InstrumentVersions'; INSERT INTO `listvalues` (`ListID`,`instance`,`scope`,`ValueKey`,`ValueDesc`,`OrderID`,`modified`) SELECT `ListID`,'lava','crms-nacc','udsphoneinclusion','3',3,NOW() FROM `list` where `ListName`='InstrumentVersions'; INSERT INTO `listvalues` (`ListID`,`instance`,`scope`,`ValueKey`,`ValueDesc`,`OrderID`,`modified`) SELECT `ListID`,'lava','crms-nacc','udsftldspecimenconsent','2',2,NOW() FROM `list` where `ListName`='InstrumentVersions'; INSERT INTO `listvalues` (`ListID`,`instance`,`scope`,`ValueKey`,`ValueDesc`,`OrderID`,`modified`) SELECT `ListID`,'lava','crms-nacc','udsftldspecimenconsent','3',3,NOW() FROM `list` where `ListName`='InstrumentVersions'; INSERT INTO `listvalues` (`ListID`,`instance`,`scope`,`ValueKey`,`ValueDesc`,`OrderID`,`modified`) SELECT `ListID`,'lava','crms-nacc','udsftldupdrs','2',2,NOW() FROM `list` where `ListName`='InstrumentVersions'; INSERT INTO `listvalues` (`ListID`,`instance`,`scope`,`ValueKey`,`ValueDesc`,`OrderID`,`modified`) SELECT `ListID`,'lava','crms-nacc','udsftldupdrs','3',3,NOW() FROM `list` where `ListName`='InstrumentVersions'; INSERT INTO `listvalues` (`ListID`,`instance`,`scope`,`ValueKey`,`ValueDesc`,`OrderID`,`modified`) SELECT `ListID`,'lava','crms-nacc','udsftldclinfeatures','2',2,NOW() FROM `list` where `ListName`='InstrumentVersions'; INSERT INTO `listvalues` (`ListID`,`instance`,`scope`,`ValueKey`,`ValueDesc`,`OrderID`,`modified`) SELECT `ListID`,'lava','crms-nacc','udsftldclinfeatures','3',3,NOW() FROM `list` where `ListName`='InstrumentVersions'; INSERT INTO `listvalues` (`ListID`,`instance`,`scope`,`ValueKey`,`ValueDesc`,`OrderID`,`modified`) SELECT `ListID`,'lava','crms-nacc','udsftldneuropsych','2',2,NOW() FROM `list` where `ListName`='InstrumentVersions'; INSERT INTO `listvalues` (`ListID`,`instance`,`scope`,`ValueKey`,`ValueDesc`,`OrderID`,`modified`) SELECT `ListID`,'lava','crms-nacc','udsftldneuropsych','3',3,NOW() FROM `list` where `ListName`='InstrumentVersions'; INSERT INTO `listvalues` (`ListID`,`instance`,`scope`,`ValueKey`,`ValueDesc`,`OrderID`,`modified`) SELECT `ListID`,'lava','crms-nacc','udsftldsnq','2',2,NOW() FROM `list` where `ListName`='InstrumentVersions'; INSERT INTO `listvalues` (`ListID`,`instance`,`scope`,`ValueKey`,`ValueDesc`,`OrderID`,`modified`) SELECT `ListID`,'lava','crms-nacc','udsftldsnq','3',3,NOW() FROM `list` where `ListName`='InstrumentVersions'; INSERT INTO `listvalues` (`ListID`,`instance`,`scope`,`ValueKey`,`ValueDesc`,`OrderID`,`modified`) SELECT `ListID`,'lava','crms-nacc','udsftldsboc','2',2,NOW() FROM `list` where `ListName`='InstrumentVersions'; INSERT INTO `listvalues` (`ListID`,`instance`,`scope`,`ValueKey`,`ValueDesc`,`OrderID`,`modified`) SELECT `ListID`,'lava','crms-nacc','udsftldsboc','3',3,NOW() FROM `list` where `ListName`='InstrumentVersions'; INSERT INTO `listvalues` (`ListID`,`instance`,`scope`,`ValueKey`,`ValueDesc`,`OrderID`,`modified`) SELECT `ListID`,'lava','crms-nacc','udsftldbis','2',2,NOW() FROM `list` where `ListName`='InstrumentVersions'; INSERT INTO `listvalues` (`ListID`,`instance`,`scope`,`ValueKey`,`ValueDesc`,`OrderID`,`modified`) SELECT `ListID`,'lava','crms-nacc','udsftldbis','3',3,NOW() FROM `list` where `ListName`='InstrumentVersions'; INSERT INTO `listvalues` (`ListID`,`instance`,`scope`,`ValueKey`,`ValueDesc`,`OrderID`,`modified`) SELECT `ListID`,'lava','crms-nacc','udsftldiri','2',2,NOW() FROM `list` where `ListName`='InstrumentVersions'; INSERT INTO `listvalues` (`ListID`,`instance`,`scope`,`ValueKey`,`ValueDesc`,`OrderID`,`modified`) SELECT `ListID`,'lava','crms-nacc','udsftldiri','3',3,NOW() FROM `list` where `ListName`='InstrumentVersions'; INSERT INTO `listvalues` (`ListID`,`instance`,`scope`,`ValueKey`,`ValueDesc`,`OrderID`,`modified`) SELECT `ListID`,'lava','crms-nacc','udsftldrsms','2',2,NOW() FROM `list` where `ListName`='InstrumentVersions'; INSERT INTO `listvalues` (`ListID`,`instance`,`scope`,`ValueKey`,`ValueDesc`,`OrderID`,`modified`) SELECT `ListID`,'lava','crms-nacc','udsftldrsms','3',3,NOW() FROM `list` where `ListName`='InstrumentVersions'; INSERT INTO `listvalues` (`ListID`,`instance`,`scope`,`ValueKey`,`ValueDesc`,`OrderID`,`modified`) SELECT `ListID`,'lava','crms-nacc','udsftldimagingavail','2',2,NOW() FROM `list` where `ListName`='InstrumentVersions'; INSERT INTO `listvalues` (`ListID`,`instance`,`scope`,`ValueKey`,`ValueDesc`,`OrderID`,`modified`) SELECT `ListID`,'lava','crms-nacc','udsftldimagingavail','3',3,NOW() FROM `list` where `ListName`='InstrumentVersions'; INSERT INTO `listvalues` (`ListID`,`instance`,`scope`,`ValueKey`,`ValueDesc`,`OrderID`,`modified`) SELECT `ListID`,'lava','crms-nacc','udsftldimagingdiag','2',2,NOW() FROM `list` where `ListName`='InstrumentVersions'; INSERT INTO `listvalues` (`ListID`,`instance`,`scope`,`ValueKey`,`ValueDesc`,`OrderID`,`modified`) SELECT `ListID`,'lava','crms-nacc','udsftldimagingdiag','3',3,NOW() FROM `list` where `ListName`='InstrumentVersions'; INSERT INTO `listvalues` (`ListID`,`instance`,`scope`,`ValueKey`,`ValueDesc`,`OrderID`,`modified`) SELECT `ListID`,'lava','crms-nacc','udsftldformchecklist','2',2,NOW() FROM `list` where `ListName`='InstrumentVersions'; INSERT INTO `listvalues` (`ListID`,`instance`,`scope`,`ValueKey`,`ValueDesc`,`OrderID`,`modified`) SELECT `ListID`,'lava','crms-nacc','udsftldformchecklist','3',3,NOW() FROM `list` where `ListName`='InstrumentVersions'; ALTER TABLE udssubjectdemo ADD REFERSC SMALLINT AFTER REFER, ADD LEARNED SMALLINT AFTER REFERX, ADD SOURCENW SMALLINT AFTER SOURCE, ADD LIVSITUA SMALLINT AFTER LIVSIT; -- in UDS 3.0 the form name changes from A2: Information Demographics to A2: Co-Participant Demographics, but still using the same underlying table ALTER TABLE udsinformantdemo ADD INKNOWN SMALLINT AFTER INRELTOX; ALTER TABLE udshealthhistory MODIFY COLUMN TOBAC30 SMALLINT AFTER INSTRID, MODIFY COLUMN TOBAC100 SMALLINT AFTER TOBAC30, MODIFY COLUMN SMOKYRS SMALLINT AFTER TOBAC100, MODIFY COLUMN PACKSPER SMALLINT AFTER SMOKYRS, MODIFY COLUMN QUITSMOK SMALLINT AFTER PACKSPER, ADD ALCOCCAS SMALLINT AFTER QUITSMOK, ADD ALCFREQ SMALLINT AFTER ALCOCCAS, ADD HATTMULT SMALLINT AFTER CVHATT, ADD HATTYEAR SMALLINT AFTER HATTMULT, ADD CVPACDEF SMALLINT AFTER CVPACE, ADD CVANGINA SMALLINT AFTER CVCHF, ADD CVHVALVE SMALLINT AFTER CVANGINA, ADD STROKMUL SMALLINT AFTER STROK6YR, ADD STROKYR SMALLINT AFTER STROKMUL, ADD TIAMULT SMALLINT AFTER TIA6YR, ADD TIAYEAR SMALLINT AFTER TIAMULT, ADD TBI SMALLINT AFTER TRAUMCHR, ADD TBIBRIEF SMALLINT AFTER TBI, ADD TBIEXTEN SMALLINT AFTER TBIBRIEF, ADD TBIWOLOS SMALLINT AFTER TBIEXTEN, ADD TBIYEAR SMALLINT AFTER TBIWOLOS, ADD DIABTYPE SMALLINT AFTER DIABETES, ADD ARTHRIT SMALLINT AFTER THYROID, ADD ARTHTYPE SMALLINT AFTER ARTHRIT, ADD ARTHTYPX VARCHAR(60) AFTER ARTHTYPE, ADD ARTHUPEX SMALLINT AFTER ARTHTYPX, ADD ARTHLOEX SMALLINT AFTER ARTHUPEX, ADD ARTHSPIN SMALLINT AFTER ARTHLOEX, ADD ARTHUNK SMALLINT AFTER ARTHSPIN, ADD APNEA SMALLINT AFTER INCONTF, ADD RBD SMALLINT AFTER APNEA, ADD INSOMN SMALLINT AFTER RBD, ADD OTHSLEEP SMALLINT AFTER INSOMN, ADD OTHSLEEX VARCHAR(60) AFTER OTHSLEEP, MODIFY COLUMN ALCOHOL SMALLINT AFTER OTHSLEEX, MODIFY COLUMN ABUSOTHR SMALLINT AFTER ALCOHOL, MODIFY COLUMN ABUSX VARCHAR(60) AFTER ABUSOTHR, ADD PTSD SMALLINT AFTER ABUSX, ADD BIPOLAR SMALLINT AFTER PTSD, ADD SCHIZ SMALLINT AFTER BIPOLAR, ADD ANXIETY SMALLINT AFTER DEPOTHR, ADD OCD SMALLINT AFTER ANXIETY, ADD NPSYDEV SMALLINT AFTER OCD; ALTER TABLE udsappraisal ADD `NORMEXAM` SMALLINT, ADD `PARKSIGN` SMALLINT, ADD `RESTTRL` SMALLINT, ADD `RESTTRR` SMALLINT, ADD `SLOWINGL` SMALLINT, ADD `SLOWINGR` SMALLINT, ADD `RIGIDL` SMALLINT, ADD `RIGIDR` SMALLINT, ADD `BRADY` SMALLINT, ADD `PARKGAIT` SMALLINT, ADD `POSTINST` SMALLINT, ADD `CVDSIGNS` SMALLINT, ADD `CORTDEF` SMALLINT, ADD `SIVDFIND` SMALLINT, ADD `CVDMOTL` SMALLINT, ADD `CVDMOTR` SMALLINT, ADD `CORTVISL` SMALLINT, ADD `CORTVISR` SMALLINT, ADD `SOMATL` SMALLINT, ADD `SOMATR` SMALLINT, ADD `POSTCORT` SMALLINT, ADD `PSPCBS` SMALLINT, ADD `EYEPSP` SMALLINT, ADD `DYSPSP` SMALLINT, ADD `AXIALPSP` SMALLINT, ADD `GAITPSP` SMALLINT, ADD `APRAXSP` SMALLINT, ADD `APRAXL` SMALLINT, ADD `APRAXR` SMALLINT, ADD `CORTSENL` SMALLINT, ADD `CORTSENR` SMALLINT, ADD `ATAXL` SMALLINT, ADD `ATAXR` SMALLINT, ADD `ALIENLML` SMALLINT, ADD `ALIENLMR` SMALLINT, ADD `DYSTONL` SMALLINT, ADD `DYSTONR` SMALLINT, ADD `MYOCLLT` SMALLINT, ADD `MYOCLRT` SMALLINT, ADD `ALSFIND` SMALLINT, ADD `GAITNPH` SMALLINT, ADD `OTHNEUR` SMALLINT, ADD `OTHNEURX` VARCHAR(60) DEFAULT NULL; ALTER TABLE udssymptomsonset ADD DECCLCOG SMALLINT AFTER DECCLIN, ADD COGORI SMALLINT AFTER COGMEM, ADD COGFLAGO SMALLINT AFTER COGFLUC, ADD COGFPRED SMALLINT AFTER COGFRSTX, ADD COGFPREX VARCHAR(60) AFTER COGFPRED, ADD DECCLBE SMALLINT AFTER COGMODEX, ADD BEVHAGO SMALLINT AFTER BEVWELL, ADD BEREMAGO SMALLINT AFTER BEREM, ADD BEANX SMALLINT AFTER BEREMAGO, ADD BEFPRED SMALLINT AFTER BEFRSTX, ADD BEFPREDX VARCHAR(60) AFTER BEFPRED, ADD BEAGE SMALLINT AFTER BEMODEX, ADD DECCLMOT SMALLINT AFTER BEAGE, ADD PARKAGE SMALLINT AFTER MOMOPARK, ADD MOMOALS SMALLINT AFTER PARKAGE, ADD ALSAGE SMALLINT AFTER MOMOALS, ADD MOAGE SMALLINT AFTER ALSAGE, ADD LBDEVAL SMALLINT AFTER FRSTCHG, ADD FTLDEVAL SMALLINT AFTER LBDEVAL; ALTER TABLE udsdiagnosis ADD COLUMN `DXMETHOD` smallint NULL DEFAULT null , ADD COLUMN `AMNDEM` smallint NULL DEFAULT null , ADD COLUMN `PCA` smallint NULL DEFAULT null , ADD COLUMN `PPASYN` smallint NULL DEFAULT null , ADD COLUMN `PPASYNT` smallint NULL DEFAULT null , ADD COLUMN `FTDSYN` smallint NULL DEFAULT null , ADD COLUMN `LBDSYN` smallint NULL DEFAULT null , ADD COLUMN `NAMNDEM` smallint NULL DEFAULT null , ADD COLUMN `AMYLPET` smallint NULL DEFAULT null , ADD COLUMN `AMYLCSF` smallint NULL DEFAULT null , ADD COLUMN `FDGAD` smallint NULL DEFAULT null , ADD COLUMN `HIPPATR` smallint NULL DEFAULT null , ADD COLUMN `TAUPETAD` smallint NULL DEFAULT null , ADD COLUMN `CSFTAU` smallint NULL DEFAULT null , ADD COLUMN `FDGFTLD` smallint NULL DEFAULT null , ADD COLUMN `TPETFTLD` smallint NULL DEFAULT null , ADD COLUMN `MRFTLD` smallint NULL DEFAULT null , ADD COLUMN `DATSCAN` smallint NULL DEFAULT null , ADD COLUMN `OTHBIOM` smallint NULL DEFAULT null , ADD COLUMN `OTHBIOMX` varchar(60) NULL DEFAULT null , ADD COLUMN `IMAGLINF` smallint NULL DEFAULT null , ADD COLUMN `IMAGLAC` smallint NULL DEFAULT null , ADD COLUMN `IMAGMACH` smallint NULL DEFAULT null , ADD COLUMN `IMAGMICH` smallint NULL DEFAULT null , ADD COLUMN `IMAGMWMH` smallint NULL DEFAULT null , ADD COLUMN `IMAGEWMH` smallint NULL DEFAULT null , ADD COLUMN `ADMUT` smallint NULL DEFAULT null , ADD COLUMN `FTLDMUT` smallint NULL DEFAULT null , ADD COLUMN `OTHMUT` smallint NULL DEFAULT null , ADD COLUMN `OTHMUTX` varchar(60) NULL DEFAULT null , ADD COLUMN `ALZDIS` smallint NULL DEFAULT null , ADD COLUMN `ALZDISIF` smallint NULL DEFAULT null , ADD COLUMN `LBDIS` smallint NULL DEFAULT null , ADD COLUMN `LBDIF` smallint NULL DEFAULT null , ADD COLUMN `MSA` smallint NULL DEFAULT null , ADD COLUMN `MSAIF` smallint NULL DEFAULT null , ADD COLUMN `FTLDMO` smallint NULL DEFAULT null , ADD COLUMN `FTLDMOIF` smallint NULL DEFAULT null , ADD COLUMN `FTLDNOS` smallint NULL DEFAULT null , ADD COLUMN `FTLDNOIF` smallint NULL DEFAULT null , ADD COLUMN `FTLDSUBT` smallint NULL DEFAULT null , ADD COLUMN `FTLDSUBX` varchar(60) NULL DEFAULT null , ADD COLUMN `CVD` smallint NULL DEFAULT null , ADD COLUMN `CVDIF` smallint NULL DEFAULT null , ADD COLUMN `PREVSTK` smallint NULL DEFAULT null , ADD COLUMN `STROKDEC` smallint NULL DEFAULT null , ADD COLUMN `STKIMAG` smallint NULL DEFAULT null , ADD COLUMN `INFNETW` smallint NULL DEFAULT null , ADD COLUMN `INFWMH` smallint NULL DEFAULT null , ADD COLUMN `ESSTREM` smallint NULL DEFAULT null , ADD COLUMN `ESSTREIF` smallint NULL DEFAULT null , ADD COLUMN `BRNINCTE` smallint NULL DEFAULT null , ADD COLUMN `EPILEP` smallint NULL DEFAULT null , ADD COLUMN `EPILEPIF` smallint NULL DEFAULT null , ADD COLUMN `NEOPSTAT` smallint NULL DEFAULT null , ADD COLUMN `HIV` smallint NULL DEFAULT null , ADD COLUMN `HIVIF` smallint NULL DEFAULT null , ADD COLUMN `OTHCOG` smallint NULL DEFAULT null , ADD COLUMN `OTHCOGIF` smallint NULL DEFAULT null , ADD COLUMN `OTHCOGX` varchar(60) NULL DEFAULT null , ADD COLUMN `DEPTREAT` smallint NULL DEFAULT null , ADD COLUMN `BIPOLDX` smallint NULL DEFAULT null , ADD COLUMN `BIPOLDIF` smallint NULL DEFAULT null , ADD COLUMN `SCHIZOP` smallint NULL DEFAULT null , ADD COLUMN `SCHIZOIF` smallint NULL DEFAULT null , ADD COLUMN `ANXIET` smallint NULL DEFAULT null , ADD COLUMN `ANXIETIF` smallint NULL DEFAULT null , ADD COLUMN `DELIR` smallint NULL DEFAULT null , ADD COLUMN `DELIRIF` smallint NULL DEFAULT null , ADD COLUMN `PTSDDX` smallint NULL DEFAULT null , ADD COLUMN `PTSDDXIF` smallint NULL DEFAULT null , ADD COLUMN `OTHPSYX` varchar(60) NULL DEFAULT null , ADD COLUMN `ALCABUSE` smallint NULL DEFAULT null , ADD COLUMN `IMPSUB` smallint NULL DEFAULT null , ADD COLUMN `IMPSUBIF` smallint NULL DEFAULT null; ALTER TABLE udsmilestone ADD COLUMN `CHANGEMO` smallint NULL DEFAULT null , ADD COLUMN `CHANGEDY` smallint NULL DEFAULT null , ADD COLUMN `CHANGEYR` smallint NULL DEFAULT null , ADD COLUMN `ACONSENT` smallint NULL DEFAULT null , ADD COLUMN `RECOGIM` smallint NULL DEFAULT null , ADD COLUMN `REPHYILL` smallint NULL DEFAULT null , ADD COLUMN `REREFUSE` smallint NULL DEFAULT null , ADD COLUMN `RENAVAIL` smallint NULL DEFAULT null , ADD COLUMN `RENURSE` smallint NULL DEFAULT null , ADD COLUMN `REJOIN` smallint NULL DEFAULT null , ADD COLUMN `FTLDDISC` smallint NULL DEFAULT null , ADD COLUMN `FTLDREAS` smallint NULL DEFAULT null , ADD COLUMN `FTLDREAX` varchar(60) NULL DEFAULT null , ADD COLUMN `DROPREAS` smallint NULL DEFAULT null;
UCSFMemoryAndAging/lava-uds
lava-crms-nacc/database/crms-nacc/versions/V3.6/V3.6.0/uds3_run_once.sql
SQL
bsd-2-clause
17,561
from ndlib.models.DiffusionModel import DiffusionModel import future.utils import numpy as np import random from sklearn.metrics import jaccard_score __author__ = ['Letizia Milli'] __license__ = "BSD-2-Clause" class HKModel(DiffusionModel): """ Model Parameters to be specified via ModelConfig :param epsilon: bounded confidence threshold from the HK model (float in [0,1]) """ def __init__(self, graph): """ Model Constructor :param graph: A networkx graph object """ super(self.__class__, self).__init__(graph) self.discrete_state = False self.available_statuses = { "Infected": 0 } self.parameters = { "model": { "epsilon": { "descr": "Bounded confidence threshold", "range": [0, 1], "optional": False, } }, "edges": {}, "nodes": {}, } self.name = "Hegselmann-Krause" def set_initial_status(self, configuration=None): """ Override behaviour of methods in class DiffusionModel. Overwrites initial status using random real values. """ super(HKModel, self).set_initial_status(configuration) # set node status for node in self.status: self.status[node] = random.uniform(-1, 1) self.initial_status = self.status.copy() def clean_initial_status(self, valid_status=None): for n, s in future.utils.iteritems(self.status): if s > 1 or s < -1: self.status[n] = 0.0 def iteration(self, node_status=True): ''' Execute a single model iteration :return: Iteration_id, Incremental node status (dictionary code -> status) ''' # An iteration changes the opinion of the selected agent 'i' . self.clean_initial_status(None) actual_status = {node: nstatus for node, nstatus in future.utils.iteritems(self.status)} if self.actual_iteration == 0: self.actual_iteration += 1 delta, node_count, status_delta = self.status_delta(self.status) if node_status: return {"iteration": 0, "status": self.status.copy(), "node_count": node_count.copy(), "status_delta": status_delta.copy()} else: return {"iteration": 0, "status": {}, "node_count": node_count.copy(), "status_delta": status_delta.copy()} for i in range(0, self.graph.number_of_nodes()): # select a random node n1 = list(self.graph.nodes)[np.random.randint(0, self.graph.number_of_nodes())] # select neighbors of n1 neighbours = list(self.graph.neighbors(n1)) sum_op = 0 count_in_eps = 0 if len(neighbours) == 0: continue for neigh in neighbours: # compute the difference between opinions diff_opinion = np.abs((actual_status[n1]) - (actual_status[neigh])) if diff_opinion < self.params['model']['epsilon']: sum_op += actual_status[neigh] # count_in_eps is the number of neighbors in epsilon count_in_eps += 1 if (count_in_eps > 0): new_op = sum_op / float(count_in_eps) else: # if there aren't neighbors in epsilon, the status of n1 doesn't change new_op = actual_status[n1] actual_status[n1] = new_op delta, node_count, status_delta = self.status_delta(actual_status) self.status = actual_status self.actual_iteration += 1 if node_status: return {"iteration": self.actual_iteration - 1, "status": delta.copy(), "node_count": node_count.copy(), "status_delta": status_delta.copy()} else: return {"iteration": self.actual_iteration - 1, "status": {}, "node_count": node_count.copy(), "status_delta": status_delta.copy()}
GiulioRossetti/ndlib
ndlib/models/opinions/HKModel.py
Python
bsd-2-clause
4,167
/* * Copyright (c) 2016, Bart Hanssens <bart.hanssens@fedict.be> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package be.fedict.lodtools.web.auth; import io.dropwizard.auth.AuthenticationException; import io.dropwizard.auth.Authenticator; import io.dropwizard.auth.basic.BasicCredentials; import java.util.Optional; /** * * @author Bart.Hanssens */ public class UpdateAuth implements Authenticator<BasicCredentials, DummyUser> { private final String username; private final String password; @Override public Optional<DummyUser> authenticate(BasicCredentials c) throws AuthenticationException { if (c.getUsername().equals(username) && c.getPassword().equals(password)) { return Optional.of(new DummyUser()); } return Optional.empty(); } /** * Constructor * * @param username * @param password */ public UpdateAuth(String username, String password) { this.username = username; this.password = password; } }
Fedict/lod-triplepages
src/main/java/be/fedict/lodtools/web/auth/UpdateAuth.java
Java
bsd-2-clause
2,297
/** * */ package sim.workload.sigcomm; import java.util.Iterator; import sim.events.Event; import sim.events.Events; import sim.main.Global; import sim.net.Host; import sim.net.HostSet; import sim.net.overlay.dht.NodeAddressPair; import sim.net.overlay.dht.NodeAddressPairs; import sim.net.overlay.dht.stealth.StealthPeer; import sim.stats.StatsObject; /** * This event looks at every StealthPeer's routing table and compares the proximity * metric they know to the real proximity metric. This allows us to judge how * well the metric works over time * * @author Andrew Brampton * */ public class RoutingTableStalenessEvent extends Event { public static RoutingTableStalenessEvent newEvent() { RoutingTableStalenessEvent e = (RoutingTableStalenessEvent) Event.newEvent(RoutingTableStalenessEvent.class); return e; } /* (non-Javadoc) * @see sim.events.Event#getEstimatedRunTime() */ @Override public long getEstimatedRunTime() { return 0; } /* (non-Javadoc) * @see sim.events.Event#run() */ @Override public void run() throws Exception { HostSet hosts = Global.hosts.getType(StealthPeer.class); final String stat = "RTStale(" + Events.getTime() + ")"; final String stat2 = "RTValid(" + Events.getTime() + ")"; final String stat3 = "RTFrac(" + Events.getTime() + ")"; Iterator<Host> i = hosts.iterator(); while (i.hasNext()) { StealthPeer p = (StealthPeer)i.next(); int stale = 0; int valid = 0; for (int x = 0; x < p.routingTable.getRows(); x++) { NodeAddressPairs[] row = p.routingTable.getRow(x); if (row != null) { for (int y = 0; y < row.length; y++) { NodeAddressPairs cell = row[y]; if (cell != null) { Iterator<NodeAddressPair> c = cell.iterator(); while (c.hasNext()) { NodeAddressPair pair = c.next(); if ( Global.hosts.get(pair.address).hasFailed() ) { Global.stats.logCount(stat); stale++; } else { Global.stats.logCount(stat2); valid++; } } } } } } if ((valid + stale) > 0) Global.stats.logAverage(stat3, (double)stale / (double)(valid + stale)); } Global.stats.logAverage("RTStale_Total", Global.stats.getValue(stat + StatsObject.COUNT) ); Global.stats.logAverage("RTValid_Total", Global.stats.getValue(stat2 + StatsObject.COUNT) ); Global.stats.logAverage("RTFrac_Total", Global.stats.getValue(stat3 + StatsObject.AVERAGE) ); } }
bramp/p2psim
src/sim/workload/sigcomm/RoutingTableStalenessEvent.java
Java
bsd-2-clause
2,552
// // ZennyLinearSearchViewController.m // CPU Dasher // // Created by zenny_chen on 13-4-13. // // #import "ZennyLinearSearchViewController.h" #import "ZennyPickerView.h" #import "LavenderDeviceInfo.h" #import "ZennyUITag.h" @interface ZennyLinearSearchViewController () @end @implementation ZennyLinearSearchViewController - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } - (void)loadView { CGRect screenBounds = [UIScreen mainScreen].bounds; CGFloat totalHeight = screenBounds.size.height - 20.0f; UIView *aView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, screenBounds.size.width, totalHeight)]; aView.backgroundColor = [UIColor whiteColor]; self.view = aView; [aView release]; } static NSString* const arrayLengthList[] = { @"1 mega bytes", @"2 mega bytes", @"4 mega bytes", @"8 mega bytes" }; static NSString* const targetPositionList[] = { @"1/4 of total length", @"1/2 of total length", @"3/4 of total length", @"The last element" }; static NSString* const calcForms[] = { @"Naive", @"ARMv6 based", @"NEON", @"Duo-core" }; static const size_t arrayTotalLengths[] = { 1 * 1024 * 1024UL, 2 * 1024 * 1024UL, 4 * 1024 * 1024UL, 8 * 1024 * 1024 }; static const float targetPositionOffset[] = { 0.25f, 0.5f, 0.75f, 1.0f }; - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. CGRect screenBounds = [UIScreen mainScreen].bounds; UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, screenBounds.size.width, 35.0f)]; title.backgroundColor = [UIColor colorWithRed:0.5098f green:0.8627f blue:0.7539f alpha:1.0f]; title.textAlignment = UITextAlignmentCenter; title.textColor = [UIColor colorWithRed:0.7961f green:0.1922f blue:0.4588f alpha:1.0f]; title.font = [UIFont fontWithName:@"Helvetica-Bold" size:18.0f]; title.text = @"Linear Search"; [self.view addSubview:title]; [title release]; UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(10.0f, 7.0f, 30.0f, 21.0f)]; button.contentScaleFactor = [[UIScreen mainScreen] scale]; [button setImage:[UIImage imageNamed:@"baritem_back.png"] forState:UIControlStateNormal]; [button addTarget:self action:@selector(backButtonTouched:) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:button]; [button release]; CGFloat width = screenBounds.size.width * 0.40625f; CGFloat edgeMargin = (screenBounds.size.width - width * 2.0f - 40.0f) * 0.5f; CGFloat rightX = edgeMargin + width + 40.0f; UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(edgeMargin, 50.0f, width, 30.0f)]; label.backgroundColor = [UIColor clearColor]; label.textAlignment = UITextAlignmentRight; label.font = [UIFont fontWithName:@"Helvetica" size:16.0f]; label.text = @"Array length:"; [self.view addSubview:label]; [label release]; const UIControlContentHorizontalAlignment buttonAlignment = [UIViewController instancesRespondToSelector:@selector(prefersStatusBarHidden)]? UIControlContentHorizontalAlignmentLeft : UIControlContentHorizontalAlignmentCenter; button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; button.frame = CGRectMake(rightX, 50.0f, width, 30.0f); button.contentHorizontalAlignment = buttonAlignment; [button setTitle:arrayLengthList[0] forState:UIControlStateNormal]; [button addTarget:self action:@selector(arrayLengthTouched:) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:button]; label = [[UILabel alloc] initWithFrame:CGRectMake(edgeMargin, 100.0f, width, 30.0f)]; label.backgroundColor = [UIColor clearColor]; label.textAlignment = UITextAlignmentRight; label.font = [UIFont fontWithName:@"Helvetica" size:16.0f]; label.text = @"Target position:"; [self.view addSubview:label]; [label release]; button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; button.frame = CGRectMake(rightX, 100.0f, width, 30.0f); button.contentHorizontalAlignment = buttonAlignment; [button setTitle:targetPositionList[0] forState:UIControlStateNormal]; [button addTarget:self action:@selector(targetPositionTouched:) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:button]; label = [[UILabel alloc] initWithFrame:CGRectMake(edgeMargin, 150.0f, width, 30.0f)]; label.backgroundColor = [UIColor clearColor]; label.textAlignment = UITextAlignmentRight; label.font = [UIFont fontWithName:@"Helvetica" size:16.0f]; label.text = @"Calculation form:"; [self.view addSubview:label]; [label release]; button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; button.frame = CGRectMake(rightX, 150.0f, width, 30.0f); button.contentHorizontalAlignment = buttonAlignment; [button setTitle:calcForms[0] forState:UIControlStateNormal]; [button addTarget:self action:@selector(formTouched:) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:button]; button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; button.frame = CGRectMake(rightX, 200.0f, width, 30.0f); button.contentHorizontalAlignment = buttonAlignment; [button setTitle:@"Calculate" forState:UIControlStateNormal]; [button addTarget:self action:@selector(calculateTouched:) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:button]; width = 0.875 * screenBounds.size.width; edgeMargin = (screenBounds.size.width - width) * 0.5f; label = [[UILabel alloc] initWithFrame:CGRectMake(edgeMargin, 260.0f, width, 80.0f)]; label.tag = CALC_AVERAGE_LABEL_TAG; label.backgroundColor = [UIColor clearColor]; label.textAlignment = UITextAlignmentLeft; label.font = [UIFont fontWithName:@"Helvetica" size:16.0f]; label.text = @""; label.numberOfLines = 4; label.hidden = YES; [self.view addSubview:label]; [label release]; mCanBeTouched = YES; } #pragma mark - button-event handlers - (void)backButtonTouched:(id)sender { [self.navigationController popViewControllerAnimated:YES]; } - (void)arrayLengthTouched:(UIButton*)sender { if(!mCanBeTouched) return; mCanBeTouched = NO; CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height - 20.0f; ZennyPickerView *pickerView = [[ZennyPickerView alloc] initWithFrame:CGRectMake(0.0f, screenHeight, 0.0f, 0.0f)]; pickerView->inputButton = sender; pickerView->pOutputIndex = &mArrayLengthIndex; pickerView->pIsFinished = &mCanBeTouched; [pickerView initPickerView:arrayLengthList count:sizeof(arrayLengthList) / sizeof(arrayLengthList[0])]; [self.view addSubview:pickerView]; [pickerView release]; UILabel *label = (UILabel*)[self.view viewWithTag:CALC_AVERAGE_LABEL_TAG]; label.text = @""; [UIView animateWithDuration:0.6 animations:^void(void){ pickerView.frame = CGRectMake(0.0f, screenHeight - 45.0f - pickerView.frame.size.height, pickerView.frame.size.width, pickerView.frame.size.height); }completion:^void(BOOL finished){ }]; } - (void)targetPositionTouched:(UIButton*)sender { if(!mCanBeTouched) return; mCanBeTouched = NO; CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height - 20.0f; ZennyPickerView *pickerView = [[ZennyPickerView alloc] initWithFrame:CGRectMake(0.0f, screenHeight, 0.0f, 0.0f)]; pickerView->inputButton = sender; pickerView->pOutputIndex = &mTargetPositionIndex; pickerView->pIsFinished = &mCanBeTouched; [pickerView initPickerView:targetPositionList count:sizeof(targetPositionList) / sizeof(targetPositionList[0])]; [self.view addSubview:pickerView]; [pickerView release]; UILabel *label = (UILabel*)[self.view viewWithTag:CALC_AVERAGE_LABEL_TAG]; label.text = @""; [UIView animateWithDuration:0.6 animations:^void(void){ pickerView.frame = CGRectMake(0.0f, screenHeight - 45.0f - pickerView.frame.size.height, pickerView.frame.size.width, pickerView.frame.size.height); }completion:^void(BOOL finished){ }]; } - (void)formTouched:(UIButton*)sender { if(!mCanBeTouched) return; mCanBeTouched = NO; CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height - 20.0f; ZennyPickerView *pickerView = [[ZennyPickerView alloc] initWithFrame:CGRectMake(0.0f, screenHeight, 0.0f, 0.0f)]; pickerView->inputButton = sender; pickerView->pOutputIndex = &mCalcFormIndex; pickerView->pIsFinished = &mCanBeTouched; NSUInteger forms = sizeof(calcForms) / sizeof(calcForms[0]); if([LavenderDeviceInfo getInstance]->nCores < 2) forms--; [pickerView initPickerView:calcForms count:forms]; [self.view addSubview:pickerView]; [pickerView release]; UILabel *label = (UILabel*)[self.view viewWithTag:CALC_AVERAGE_LABEL_TAG]; label.text = @""; [UIView animateWithDuration:0.6 animations:^void(void){ pickerView.frame = CGRectMake(0.0f, screenHeight - 45.0f - pickerView.frame.size.height, pickerView.frame.size.width, pickerView.frame.size.height); }completion:^void(BOOL finished){ }]; } - (void)calculateTouched:(UIButton*)sender { if(!mCanBeTouched) return; mCanBeTouched = NO; UILabel *label = (UILabel*)[self.view viewWithTag:CALC_AVERAGE_LABEL_TAG]; label.hidden = NO; label.text = @"This may take several seconds. Please wait..."; [self performSelector:@selector(doCalculate:) withObject:label afterDelay:0.1]; } #pragma mark - Calculation static int LinearSearchProc(const int *pSrc, size_t length, size_t targetValue); static int LinearSearchProcDuoCore(const int *pSrc, size_t length, size_t targetValue); extern int LinearSearchProcARMv6(const int *pSrc, size_t length, size_t targetValue); extern int LinearSearchProcNEON(const int *pSrc, size_t length, size_t targetValue); static int (* const linearSearchProcList[])(const int*, size_t, size_t) = { &LinearSearchProc, &LinearSearchProcARMv6, &LinearSearchProcNEON, &LinearSearchProcDuoCore }; - (void)doCalculate:(UILabel*)label { size_t initAddress = (size_t)mCalcBuffer; // 32 bytes aligned int *pAlignedMem = (int*)((initAddress + 31) & ~31); size_t length = arrayTotalLengths[mArrayLengthIndex]; // Initialize with zero memset(pAlignedMem, 0, length); // Get the number of total elements length /= 4; // Get the target index size_t targetIndex = (size_t)((float)length * targetPositionOffset[mTargetPositionIndex]) - 1UL; pAlignedMem[targetIndex] = 1; // Do calculation NSTimeInterval beginTimes[10]; NSTimeInterval endTimes[10]; NSTimeInterval deltaResults[10]; NSProcessInfo *processor = [NSProcessInfo processInfo]; int result = -1; int (*pCalcProc)(const int*, size_t, size_t) = linearSearchProcList[mCalcFormIndex]; for(int i = 0; i < 10; i++) { beginTimes[i] = [processor systemUptime]; result = (*pCalcProc)(pAlignedMem, length, 1); endTimes[i] = [processor systemUptime]; } // Statistics for(int i = 0; i < 10; i++) deltaResults[i] = endTimes[i] - beginTimes[i]; NSTimeInterval minTime = deltaResults[0]; NSTimeInterval maxTime = deltaResults[0]; NSTimeInterval sumTime = deltaResults[0]; for(int i = 1; i < 10; i++) { if(minTime > deltaResults[i]) minTime = deltaResults[i]; if(maxTime < deltaResults[i]) maxTime = deltaResults[i]; sumTime += deltaResults[i]; } minTime *= 1000.0; maxTime *= 1000.0; sumTime *= 1000.0; label.text = [NSString stringWithFormat:@"Target element index: %d\nMaximum time spent: %.3f ms\nAverage time spent: %.3f ms\nMinimum time spent: %.3f ms", result, maxTime, sumTime / 10.0, minTime]; mCanBeTouched = YES; } static int LinearSearchProc(const int *pSrc, size_t length, size_t targetValue) { int resultIndex = -1; for(size_t i = 0; i < length; i++) { if(pSrc[i] == targetValue) { resultIndex = i; break; } } return resultIndex; } static int LinearSearchProcDuoCore(const int *pSrc, size_t length, size_t targetValue) { __block BOOL isFinished = NO; __block int innerResult = -1; dispatch_queue_t queue = dispatch_queue_create("Zenny_Queue", NULL); dispatch_async(queue, ^void(void) { innerResult = LinearSearchProcNEON(&pSrc[length / 2], length / 2, 1); isFinished = YES; }); int outerResult = LinearSearchProcNEON(pSrc, length / 2, 1); while(!isFinished) __asm__("yield"); if(innerResult > -1) outerResult = innerResult + (length / 2); dispatch_release(queue); return outerResult; } #pragma mark - - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
zenny-chen/CPU-Dasher-for-iOS
ZennyLinearSearchViewController.m
Matlab
bsd-2-clause
13,418
''' WebIDL binder https://github.com/kripken/emscripten/wiki/WebIDL-Binder ''' import os, sys import shared sys.path.append(shared.path_from_root('third_party')) sys.path.append(shared.path_from_root('third_party', 'ply')) import WebIDL class Dummy: def __init__(self, init): for k, v in init.iteritems(): self.__dict__[k] = v def getExtendedAttribute(self, name): return None input_file = sys.argv[1] output_base = sys.argv[2] shared.try_delete(output_base + '.cpp') shared.try_delete(output_base + '.js') p = WebIDL.Parser() p.parse(r''' interface VoidPtr { }; ''' + open(input_file).read()) data = p.finish() interfaces = {} implements = {} enums = {} for thing in data: if isinstance(thing, WebIDL.IDLInterface): interfaces[thing.identifier.name] = thing elif isinstance(thing, WebIDL.IDLImplementsStatement): implements.setdefault(thing.implementor.identifier.name, []).append(thing.implementee.identifier.name) elif isinstance(thing, WebIDL.IDLEnum): enums[thing.identifier.name] = thing #print interfaces #print implements pre_c = [] mid_c = [] mid_js = [] pre_c += [r''' #include <emscripten.h> '''] mid_c += [r''' extern "C" { '''] def emit_constructor(name): global mid_js mid_js += [r'''%s.prototype = %s; %s.prototype.constructor = %s; %s.prototype.__class__ = %s; %s.__cache__ = {}; Module['%s'] = %s; ''' % (name, 'Object.create(%s.prototype)' % (implements[name][0] if implements.get(name) else 'WrapperObject'), name, name, name, name, name, name, name)] mid_js += [''' // Bindings utilities function WrapperObject() { } '''] emit_constructor('WrapperObject') mid_js += [''' function getCache(__class__) { return (__class__ || WrapperObject).__cache__; } Module['getCache'] = getCache; function wrapPointer(ptr, __class__) { var cache = getCache(__class__); var ret = cache[ptr]; if (ret) return ret; ret = Object.create((__class__ || WrapperObject).prototype); ret.ptr = ptr; return cache[ptr] = ret; } Module['wrapPointer'] = wrapPointer; function castObject(obj, __class__) { return wrapPointer(obj.ptr, __class__); } Module['castObject'] = castObject; Module['NULL'] = wrapPointer(0); function destroy(obj) { if (!obj['__destroy__']) throw 'Error: Cannot destroy object. (Did you create it yourself?)'; obj['__destroy__'](); // Remove from cache, so the object can be GC'd and refs added onto it released delete getCache(obj.__class__)[obj.ptr]; } Module['destroy'] = destroy; function compare(obj1, obj2) { return obj1.ptr === obj2.ptr; } Module['compare'] = compare; function getPointer(obj) { return obj.ptr; } Module['getPointer'] = getPointer; function getClass(obj) { return obj.__class__; } Module['getClass'] = getClass; // Converts a value into a C-style string. var ensureString = (function() { var stringCache = {}; function ensureString(value) { if (typeof value == 'string') { var cachedVal = stringCache[value]; if (cachedVal) return cachedVal; var ret = allocate(intArrayFromString(value), 'i8', ALLOC_STACK); stringCache[value] = ret; return ret; } return value; } return ensureString; })(); '''] mid_c += [''' // Not using size_t for array indices as the values used by the javascript code are signed. void array_bounds_check(const int array_size, const int array_idx) { if (array_idx < 0 || array_idx >= array_size) { EM_ASM_INT({ throw 'Array index ' + $0 + ' out of bounds: [0,' + $1 + ')'; }, array_idx, array_size); } } '''] C_FLOATS = ['float', 'double'] def type_to_c(t, non_pointing=False): #print 'to c ', t t = t.replace(' (Wrapper)', '') if t == 'Long': return 'int' elif t == 'UnsignedLong': return 'unsigned int' elif t == 'Short': return 'short' elif t == 'UnsignedShort': return 'unsigned short' elif t == 'Byte': return 'char' elif t == 'Octet': return 'unsigned char' elif t == 'Void': return 'void' elif t == 'String': return 'char*' elif t == 'Float': return 'float' elif t == 'Double': return 'double' elif t == 'Boolean': return 'bool' elif t == 'Any' or t == 'VoidPtr': return 'void*' elif t in interfaces: return (interfaces[t].getExtendedAttribute('Prefix') or [''])[0] + t + ('' if non_pointing else '*') else: return t def take_addr_if_nonpointer(m): if m.getExtendedAttribute('Ref') or m.getExtendedAttribute('Value'): return '&' return '' def deref_if_nonpointer(m): if m.getExtendedAttribute('Ref') or m.getExtendedAttribute('Value'): return '*' return '' def type_to_cdec(raw): name = ret = type_to_c(raw.type.name, non_pointing=True) if raw.getExtendedAttribute('Const'): ret = 'const ' + ret if name not in interfaces: return ret if raw.getExtendedAttribute('Ref'): return ret + '&' if raw.getExtendedAttribute('Value'): return ret return ret + '*' def render_function(class_name, func_name, sigs, return_type, non_pointer, copy, operator, constructor, func_scope, call_content=None, const=False): global mid_c, mid_js, js_impl_methods #print 'renderfunc', class_name, func_name, sigs, return_type, constructor bindings_name = class_name + '_' + func_name min_args = min(sigs.keys()) max_args = max(sigs.keys()) c_names = {} # JS cache = ('getCache(%s)[this.ptr] = this;' % class_name) if constructor else '' call_prefix = '' if not constructor else 'this.ptr = ' call_postfix = '' if return_type != 'Void' and not constructor: call_prefix = 'return ' if not constructor: if return_type in interfaces: call_prefix += 'wrapPointer(' call_postfix += ', ' + return_type + ')' elif return_type == 'String': call_prefix += 'Pointer_stringify(' call_postfix += ')' args = ['arg%d' % i for i in range(max_args)] if not constructor: body = ' var self = this.ptr;\n' pre_arg = ['self'] else: body = '' pre_arg = [] for i in range(max_args): # note: null has typeof object, but is ok to leave as is, since we are calling into asm code where null|0 = 0 body += " if (arg%d && typeof arg%d === 'object') arg%d = arg%d.ptr;\n" % (i, i, i, i) body += " else arg%d = ensureString(arg%d);\n" % (i, i) for i in range(min_args, max_args): c_names[i] = 'emscripten_bind_%s_%d' % (bindings_name, i) body += ' if (arg%d === undefined) { %s%s(%s)%s%s }\n' % (i, call_prefix, '_' + c_names[i], ', '.join(pre_arg + args[:i]), call_postfix, '' if 'return ' in call_prefix else '; ' + (cache or ' ') + 'return') c_names[max_args] = 'emscripten_bind_%s_%d' % (bindings_name, max_args) body += ' %s%s(%s)%s;\n' % (call_prefix, '_' + c_names[max_args], ', '.join(pre_arg + args), call_postfix) if cache: body += ' ' + cache + '\n' mid_js += [r'''function%s(%s) { %s };''' % ((' ' + func_name) if constructor else '', ', '.join(args), body[:-1])] # C for i in range(min_args, max_args+1): raw = sigs.get(i) if raw is None: continue sig = [arg.type.name for arg in raw] c_arg_types = map(type_to_c, sig) normal_args = ', '.join(['%s arg%d' % (c_arg_types[j], j) for j in range(i)]) if constructor: full_args = normal_args else: full_args = type_to_c(class_name, non_pointing=True) + '* self' + ('' if not normal_args else ', ' + normal_args) call_args = ', '.join(['%sarg%d' % ('*' if raw[j].getExtendedAttribute('Ref') else '', j) for j in range(i)]) if constructor: call = 'new ' + type_to_c(class_name, non_pointing=True) call += '(' + call_args + ')' elif call_content is not None: call = call_content else: call = 'self->' + func_name call += '(' + call_args + ')' if operator: assert '=' in operator, 'can only do += *= etc. for now, all with "="' cast_self = 'self' if class_name != func_scope: # this function comes from an ancestor class; for operators, we must cast it cast_self = 'dynamic_cast<' + type_to_c(func_scope) + '>(' + cast_self + ')' call = '(*%s %s %sarg0)' % (cast_self, operator, '*' if sig[0] in interfaces else '') pre = '' basic_return = 'return ' if constructor or return_type is not 'Void' else '' return_prefix = basic_return return_postfix = '' if non_pointer: return_prefix += '&'; if copy: pre += ' static %s temp;\n' % type_to_c(return_type, non_pointing=True) return_prefix += '(temp = ' return_postfix += ', &temp)' c_return_type = type_to_c(return_type) mid_c += [r''' %s%s EMSCRIPTEN_KEEPALIVE %s(%s) { %s %s%s%s; } ''' % ('const ' if const else '', type_to_c(class_name) if constructor else c_return_type, c_names[i], full_args, pre, return_prefix, call, return_postfix)] if not constructor: if i == max_args: dec_args = ', '.join(map(lambda j: type_to_cdec(raw[j]) + ' arg' + str(j), range(i))) js_call_args = ', '.join(['%sarg%d' % (('(int)' if sig[j] in interfaces else '') + ('&' if raw[j].getExtendedAttribute('Ref') or raw[j].getExtendedAttribute('Value') else ''), j) for j in range(i)]) js_impl_methods += [r''' %s %s(%s) { %sEM_ASM_%s({ var self = Module['getCache'](Module['%s'])[$0]; if (!self.hasOwnProperty('%s')) throw 'a JSImplementation must implement all functions, you forgot %s::%s.'; %sself.%s(%s)%s; }, (int)this%s); }''' % (c_return_type, func_name, dec_args, basic_return, 'INT' if c_return_type not in C_FLOATS else 'DOUBLE', class_name, func_name, class_name, func_name, return_prefix, func_name, ','.join(['$%d' % i for i in range(1, max_args + 1)]), return_postfix, (', ' if js_call_args else '') + js_call_args)] for name, interface in interfaces.iteritems(): js_impl = interface.getExtendedAttribute('JSImplementation') if not js_impl: continue implements[name] = [js_impl[0]] names = interfaces.keys() names.sort(lambda x, y: 1 if implements.get(x) and implements[x][0] == y else (-1 if implements.get(y) and implements[y][0] == x else 0)) for name in names: interface = interfaces[name] mid_js += ['\n// ' + name + '\n'] mid_c += ['\n// ' + name + '\n'] global js_impl_methods js_impl_methods = [] cons = interface.getExtendedAttribute('Constructor') if type(cons) == list: raise Exception('do not use "Constructor", instead create methods with the name of the interface') js_impl = interface.getExtendedAttribute('JSImplementation') if js_impl: js_impl = js_impl[0] # Methods seen_constructor = False # ensure a constructor, even for abstract base classes for m in interface.members: if m.identifier.name == name: seen_constructor = True break if not seen_constructor: mid_js += ['function %s() { throw "cannot construct a %s, no constructor in IDL" }\n' % (name, name)] emit_constructor(name) for m in interface.members: if not m.isMethod(): continue constructor = m.identifier.name == name if not constructor: parent_constructor = False temp = m.parentScope while temp.parentScope: if temp.identifier.name == m.identifier.name: parent_constructor = True temp = temp.parentScope if parent_constructor: continue if not constructor: mid_js += [r''' %s.prototype['%s'] = ''' % (name, m.identifier.name)] sigs = {} return_type = None for ret, args in m.signatures(): if return_type is None: return_type = ret.name else: assert return_type == ret.name, 'overloads must have the same return type' for i in range(len(args)+1): if i == len(args) or args[i].optional: assert i not in sigs, 'overloading must differentiate by # of arguments (cannot have two signatures that differ by types but not by length)' sigs[i] = args[:i] render_function(name, m.identifier.name, sigs, return_type, m.getExtendedAttribute('Ref'), m.getExtendedAttribute('Value'), (m.getExtendedAttribute('Operator') or [None])[0], constructor, func_scope=m.parentScope.identifier.name, const=m.getExtendedAttribute('Const')) mid_js += [';\n'] if constructor: emit_constructor(name) for m in interface.members: if not m.isAttr(): continue attr = m.identifier.name if m.type.isArray(): get_sigs = { 1: [Dummy({ 'type': WebIDL.BuiltinTypes[WebIDL.IDLBuiltinType.Types.long] })] } set_sigs = { 2: [Dummy({ 'type': WebIDL.BuiltinTypes[WebIDL.IDLBuiltinType.Types.long] }), Dummy({ 'type': m.type })] } get_call_content = take_addr_if_nonpointer(m) + 'self->' + attr + '[arg0]' set_call_content = 'self->' + attr + '[arg0] = ' + deref_if_nonpointer(m) + 'arg1' if m.getExtendedAttribute('BoundsChecked'): bounds_check = "array_bounds_check(sizeof(self->%s) / sizeof(self->%s[0]), arg0)" % (attr, attr) get_call_content = "(%s, %s)" % (bounds_check, get_call_content) set_call_content = "(%s, %s)" % (bounds_check, set_call_content) else: get_sigs = { 0: [] } set_sigs = { 1: [Dummy({ 'type': m.type })] } get_call_content = take_addr_if_nonpointer(m) + 'self->' + attr set_call_content = 'self->' + attr + ' = ' + deref_if_nonpointer(m) + 'arg0' get_name = 'get_' + attr mid_js += [r''' %s.prototype['%s']= ''' % (name, get_name)] render_function(name, get_name, get_sigs, m.type.name, None, None, None, False, func_scope=interface, call_content=get_call_content, const=m.getExtendedAttribute('Const')) if not m.readonly: set_name = 'set_' + attr mid_js += [r''' %s.prototype['%s']= ''' % (name, set_name)] render_function(name, set_name, set_sigs, 'Void', None, None, None, False, func_scope=interface, call_content=set_call_content, const=m.getExtendedAttribute('Const')) if not interface.getExtendedAttribute('NoDelete'): mid_js += [r''' %s.prototype['__destroy__'] = ''' % name] render_function(name, '__destroy__', { 0: [] }, 'Void', None, None, None, False, func_scope=interface, call_content='delete self') # Emit C++ class implementation that calls into JS implementation if js_impl: pre_c += [r''' class %s : public %s { public: %s }; ''' % (name, type_to_c(js_impl, non_pointing=True), '\n'.join(js_impl_methods))] deferred_js = [] for name, enum in enums.iteritems(): mid_c += ['\n// ' + name + '\n'] deferred_js += ['\n', '// ' + name + '\n'] for value in enum.values(): function_id = "%s_%s" % (name, value.split('::')[-1]) mid_c += [r'''%s EMSCRIPTEN_KEEPALIVE emscripten_enum_%s() { return %s; } ''' % (name, function_id, value)] symbols = value.split('::') if len(symbols) == 1: identifier = symbols[0] deferred_js += ["Module['%s'] = _emscripten_enum_%s();\n" % (identifier, function_id)] elif len(symbols) == 2: [namespace, identifier] = symbols if namespace in interfaces: # namespace is a class deferred_js += ["Module['%s']['%s'] = _emscripten_enum_%s();\n" % \ (namespace, identifier, function_id)] else: # namespace is a namespace, so the enums get collapsed into the top level namespace. deferred_js += ["Module['%s'] = _emscripten_enum_%s();\n" % (identifier, function_id)] else: throw ("Illegal enum value %s" % value) mid_c += ['\n}\n\n'] mid_js += [''' (function() { function setupEnums() { %s } if (Module['calledRun']) setupEnums(); else addOnPreMain(setupEnums); })(); ''' % '\n '.join(deferred_js)] # Write c = open(output_base + '.cpp', 'w') for x in pre_c: c.write(x) for x in mid_c: c.write(x) c.close() js = open(output_base + '.js', 'w') for x in mid_js: js.write(x) js.close()
PopCap/GameIdea
Engine/Source/ThirdParty/HTML5/emsdk/emscripten/1.30.0/tools/webidl_binder.py
Python
bsd-2-clause
16,445
/****************************************************************************** * * Module Name: dtio.c - File I/O support for data table compiler * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2014, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * *****************************************************************************/ #include "aslcompiler.h" #include "dtcompiler.h" #include "acapps.h" #define _COMPONENT DT_COMPILER ACPI_MODULE_NAME ("dtio") /* Local prototypes */ static char * DtTrim ( char *String); static void DtLinkField ( DT_FIELD *Field); static ACPI_STATUS DtParseLine ( char *LineBuffer, UINT32 Line, UINT32 Offset); static void DtWriteBinary ( DT_SUBTABLE *Subtable, void *Context, void *ReturnValue); static void DtDumpBuffer ( UINT32 FileId, UINT8 *Buffer, UINT32 Offset, UINT32 Length); static void DtDumpSubtableInfo ( DT_SUBTABLE *Subtable, void *Context, void *ReturnValue); static void DtDumpSubtableTree ( DT_SUBTABLE *Subtable, void *Context, void *ReturnValue); /* States for DtGetNextLine */ #define DT_NORMAL_TEXT 0 #define DT_START_QUOTED_STRING 1 #define DT_START_COMMENT 2 #define DT_SLASH_ASTERISK_COMMENT 3 #define DT_SLASH_SLASH_COMMENT 4 #define DT_END_COMMENT 5 #define DT_MERGE_LINES 6 #define DT_ESCAPE_SEQUENCE 7 static UINT32 Gbl_NextLineOffset; /****************************************************************************** * * FUNCTION: DtTrim * * PARAMETERS: String - Current source code line to trim * * RETURN: Trimmed line. Must be freed by caller. * * DESCRIPTION: Trim left and right spaces * *****************************************************************************/ static char * DtTrim ( char *String) { char *Start; char *End; char *ReturnString; ACPI_SIZE Length; /* Skip lines that start with a space */ if (!ACPI_STRCMP (String, " ")) { ReturnString = UtStringCacheCalloc (1); return (ReturnString); } /* Setup pointers to start and end of input string */ Start = String; End = String + ACPI_STRLEN (String) - 1; /* Find first non-whitespace character */ while ((Start <= End) && ((*Start == ' ') || (*Start == '\t'))) { Start++; } /* Find last non-space character */ while (End >= Start) { if (*End == '\r' || *End == '\n') { End--; continue; } if (*End != ' ') { break; } End--; } /* Remove any quotes around the string */ if (*Start == '\"') { Start++; } if (*End == '\"') { End--; } /* Create the trimmed return string */ Length = ACPI_PTR_DIFF (End, Start) + 1; ReturnString = UtStringCacheCalloc (Length + 1); if (ACPI_STRLEN (Start)) { ACPI_STRNCPY (ReturnString, Start, Length); } ReturnString[Length] = 0; return (ReturnString); } /****************************************************************************** * * FUNCTION: DtLinkField * * PARAMETERS: Field - New field object to link * * RETURN: None * * DESCRIPTION: Link one field name and value to the list * *****************************************************************************/ static void DtLinkField ( DT_FIELD *Field) { DT_FIELD *Prev; DT_FIELD *Next; Prev = Next = Gbl_FieldList; while (Next) { Prev = Next; Next = Next->Next; } if (Prev) { Prev->Next = Field; } else { Gbl_FieldList = Field; } } /****************************************************************************** * * FUNCTION: DtParseLine * * PARAMETERS: LineBuffer - Current source code line * Line - Current line number in the source * Offset - Current byte offset of the line * * RETURN: Status * * DESCRIPTION: Parse one source line * *****************************************************************************/ static ACPI_STATUS DtParseLine ( char *LineBuffer, UINT32 Line, UINT32 Offset) { char *Start; char *End; char *TmpName; char *TmpValue; char *Name; char *Value; char *Colon; UINT32 Length; DT_FIELD *Field; UINT32 Column; UINT32 NameColumn; BOOLEAN IsNullString = FALSE; if (!LineBuffer) { return (AE_OK); } /* All lines after "Raw Table Data" are ingored */ if (strstr (LineBuffer, ACPI_RAW_TABLE_DATA_HEADER)) { return (AE_NOT_FOUND); } Colon = strchr (LineBuffer, ':'); if (!Colon) { return (AE_OK); } Start = LineBuffer; End = Colon; while (Start < Colon) { if (*Start == '[') { /* Found left bracket, go to the right bracket */ while (Start < Colon && *Start != ']') { Start++; } } else if (*Start != ' ') { break; } Start++; } /* * There are two column values. One for the field name, * and one for the field value. */ Column = ACPI_PTR_DIFF (Colon, LineBuffer) + 3; NameColumn = ACPI_PTR_DIFF (Start, LineBuffer) + 1; Length = ACPI_PTR_DIFF (End, Start); TmpName = UtLocalCalloc (Length + 1); ACPI_STRNCPY (TmpName, Start, Length); Name = DtTrim (TmpName); ACPI_FREE (TmpName); Start = End = (Colon + 1); while (*End) { /* Found left quotation, go to the right quotation and break */ if (*End == '"') { End++; /* Check for an explicit null string */ if (*End == '"') { IsNullString = TRUE; } while (*End && (*End != '"')) { End++; } End++; break; } /* * Special "comment" fields at line end, ignore them. * Note: normal slash-slash and slash-asterisk comments are * stripped already by the DtGetNextLine parser. * * TBD: Perhaps DtGetNextLine should parse the following type * of comments also. */ if (*End == '[') { End--; break; } End++; } Length = ACPI_PTR_DIFF (End, Start); TmpValue = UtLocalCalloc (Length + 1); ACPI_STRNCPY (TmpValue, Start, Length); Value = DtTrim (TmpValue); ACPI_FREE (TmpValue); /* Create a new field object only if we have a valid value field */ if ((Value && *Value) || IsNullString) { Field = UtFieldCacheCalloc (); Field->Name = Name; Field->Value = Value; Field->Line = Line; Field->ByteOffset = Offset; Field->NameColumn = NameColumn; Field->Column = Column; DtLinkField (Field); } /* Else -- Ignore this field, it has no valid data */ return (AE_OK); } /****************************************************************************** * * FUNCTION: DtGetNextLine * * PARAMETERS: Handle - Open file handle for the source file * * RETURN: Filled line buffer and offset of start-of-line (ASL_EOF on EOF) * * DESCRIPTION: Get the next valid source line. Removes all comments. * Ignores empty lines. * * Handles both slash-asterisk and slash-slash comments. * Also, quoted strings, but no escapes within. * * Line is returned in Gbl_CurrentLineBuffer. * Line number in original file is returned in Gbl_CurrentLineNumber. * *****************************************************************************/ UINT32 DtGetNextLine ( FILE *Handle) { BOOLEAN LineNotAllBlanks = FALSE; UINT32 State = DT_NORMAL_TEXT; UINT32 CurrentLineOffset; UINT32 i; int c; for (i = 0; ;) { /* * If line is too long, expand the line buffers. Also increases * Gbl_LineBufferSize. */ if (i >= Gbl_LineBufferSize) { UtExpandLineBuffers (); } c = getc (Handle); if (c == EOF) { switch (State) { case DT_START_QUOTED_STRING: case DT_SLASH_ASTERISK_COMMENT: AcpiOsPrintf ("**** EOF within comment/string %u\n", State); break; default: break; } /* Standalone EOF is OK */ if (i == 0) { return (ASL_EOF); } /* * Received an EOF in the middle of a line. Terminate the * line with a newline. The next call to this function will * return a standalone EOF. Thus, the upper parsing software * never has to deal with an EOF within a valid line (or * the last line does not get tossed on the floor.) */ c = '\n'; State = DT_NORMAL_TEXT; } switch (State) { case DT_NORMAL_TEXT: /* Normal text, insert char into line buffer */ Gbl_CurrentLineBuffer[i] = (char) c; switch (c) { case '/': State = DT_START_COMMENT; break; case '"': State = DT_START_QUOTED_STRING; LineNotAllBlanks = TRUE; i++; break; case '\\': /* * The continuation char MUST be last char on this line. * Otherwise, it will be assumed to be a valid ASL char. */ State = DT_MERGE_LINES; break; case '\n': CurrentLineOffset = Gbl_NextLineOffset; Gbl_NextLineOffset = (UINT32) ftell (Handle); Gbl_CurrentLineNumber++; /* * Exit if line is complete. Ignore empty lines (only \n) * or lines that contain nothing but blanks. */ if ((i != 0) && LineNotAllBlanks) { if ((i + 1) >= Gbl_LineBufferSize) { UtExpandLineBuffers (); } Gbl_CurrentLineBuffer[i+1] = 0; /* Terminate string */ return (CurrentLineOffset); } /* Toss this line and start a new one */ i = 0; LineNotAllBlanks = FALSE; break; default: if (c != ' ') { LineNotAllBlanks = TRUE; } i++; break; } break; case DT_START_QUOTED_STRING: /* Insert raw chars until end of quoted string */ Gbl_CurrentLineBuffer[i] = (char) c; i++; switch (c) { case '"': State = DT_NORMAL_TEXT; break; case '\\': State = DT_ESCAPE_SEQUENCE; break; case '\n': AcpiOsPrintf ("ERROR at line %u: Unterminated quoted string\n", Gbl_CurrentLineNumber++); State = DT_NORMAL_TEXT; break; default: /* Get next character */ break; } break; case DT_ESCAPE_SEQUENCE: /* Just copy the escaped character. TBD: sufficient for table compiler? */ Gbl_CurrentLineBuffer[i] = (char) c; i++; State = DT_START_QUOTED_STRING; break; case DT_START_COMMENT: /* Open comment if this character is an asterisk or slash */ switch (c) { case '*': State = DT_SLASH_ASTERISK_COMMENT; break; case '/': State = DT_SLASH_SLASH_COMMENT; break; default: /* Not a comment */ i++; /* Save the preceding slash */ if (i >= Gbl_LineBufferSize) { UtExpandLineBuffers (); } Gbl_CurrentLineBuffer[i] = (char) c; i++; State = DT_NORMAL_TEXT; break; } break; case DT_SLASH_ASTERISK_COMMENT: /* Ignore chars until an asterisk-slash is found */ switch (c) { case '\n': Gbl_NextLineOffset = (UINT32) ftell (Handle); Gbl_CurrentLineNumber++; break; case '*': State = DT_END_COMMENT; break; default: break; } break; case DT_SLASH_SLASH_COMMENT: /* Ignore chars until end-of-line */ if (c == '\n') { /* We will exit via the NORMAL_TEXT path */ ungetc (c, Handle); State = DT_NORMAL_TEXT; } break; case DT_END_COMMENT: /* End comment if this char is a slash */ switch (c) { case '/': State = DT_NORMAL_TEXT; break; case '\n': CurrentLineOffset = Gbl_NextLineOffset; Gbl_NextLineOffset = (UINT32) ftell (Handle); Gbl_CurrentLineNumber++; break; case '*': /* Consume all adjacent asterisks */ break; default: State = DT_SLASH_ASTERISK_COMMENT; break; } break; case DT_MERGE_LINES: if (c != '\n') { /* * This is not a continuation backslash, it is a normal * normal ASL backslash - for example: Scope(\_SB_) */ i++; /* Keep the backslash that is already in the buffer */ ungetc (c, Handle); State = DT_NORMAL_TEXT; } else { /* * This is a continuation line -- a backlash followed * immediately by a newline. Insert a space between the * lines (overwrite the backslash) */ Gbl_CurrentLineBuffer[i] = ' '; i++; /* Ignore newline, this will merge the lines */ CurrentLineOffset = Gbl_NextLineOffset; Gbl_NextLineOffset = (UINT32) ftell (Handle); Gbl_CurrentLineNumber++; State = DT_NORMAL_TEXT; } break; default: DtFatal (ASL_MSG_COMPILER_INTERNAL, NULL, "Unknown input state"); return (ASL_EOF); } } } /****************************************************************************** * * FUNCTION: DtScanFile * * PARAMETERS: Handle - Open file handle for the source file * * RETURN: Pointer to start of the constructed parse tree. * * DESCRIPTION: Scan source file, link all field names and values * to the global parse tree: Gbl_FieldList * *****************************************************************************/ DT_FIELD * DtScanFile ( FILE *Handle) { ACPI_STATUS Status; UINT32 Offset; ACPI_FUNCTION_NAME (DtScanFile); /* Get the file size */ Gbl_InputByteCount = CmGetFileSize (Handle); if (Gbl_InputByteCount == ACPI_UINT32_MAX) { AslAbort (); } Gbl_CurrentLineNumber = 0; Gbl_CurrentLineOffset = 0; Gbl_NextLineOffset = 0; /* Scan line-by-line */ while ((Offset = DtGetNextLine (Handle)) != ASL_EOF) { ACPI_DEBUG_PRINT ((ACPI_DB_PARSE, "Line %2.2u/%4.4X - %s", Gbl_CurrentLineNumber, Offset, Gbl_CurrentLineBuffer)); Status = DtParseLine (Gbl_CurrentLineBuffer, Gbl_CurrentLineNumber, Offset); if (Status == AE_NOT_FOUND) { break; } } /* Dump the parse tree if debug enabled */ DtDumpFieldList (Gbl_FieldList); return (Gbl_FieldList); } /* * Output functions */ /****************************************************************************** * * FUNCTION: DtWriteBinary * * PARAMETERS: DT_WALK_CALLBACK * * RETURN: Status * * DESCRIPTION: Write one subtable of a binary ACPI table * *****************************************************************************/ static void DtWriteBinary ( DT_SUBTABLE *Subtable, void *Context, void *ReturnValue) { FlWriteFile (ASL_FILE_AML_OUTPUT, Subtable->Buffer, Subtable->Length); } /****************************************************************************** * * FUNCTION: DtOutputBinary * * PARAMETERS: * * RETURN: Status * * DESCRIPTION: Write entire binary ACPI table (result of compilation) * *****************************************************************************/ void DtOutputBinary ( DT_SUBTABLE *RootTable) { if (!RootTable) { return; } /* Walk the entire parse tree, emitting the binary data */ DtWalkTableTree (RootTable, DtWriteBinary, NULL, NULL); Gbl_TableLength = CmGetFileSize (Gbl_Files[ASL_FILE_AML_OUTPUT].Handle); if (Gbl_TableLength == ACPI_UINT32_MAX) { AslAbort (); } } /* * Listing support */ /****************************************************************************** * * FUNCTION: DtDumpBuffer * * PARAMETERS: FileID - Where to write buffer data * Buffer - Buffer to dump * Offset - Offset in current table * Length - Buffer Length * * RETURN: None * * DESCRIPTION: Another copy of DumpBuffer routine (unfortunately). * * TBD: merge dump buffer routines * *****************************************************************************/ static void DtDumpBuffer ( UINT32 FileId, UINT8 *Buffer, UINT32 Offset, UINT32 Length) { UINT32 i; UINT32 j; UINT8 BufChar; FlPrintFile (FileId, "Output: [%3.3Xh %4.4d %3d] ", Offset, Offset, Length); i = 0; while (i < Length) { if (i >= 16) { FlPrintFile (FileId, "%24s", ""); } /* Print 16 hex chars */ for (j = 0; j < 16;) { if (i + j >= Length) { /* Dump fill spaces */ FlPrintFile (FileId, " "); j++; continue; } FlPrintFile (FileId, "%02X ", Buffer[i+j]); j++; } FlPrintFile (FileId, " "); for (j = 0; j < 16; j++) { if (i + j >= Length) { FlPrintFile (FileId, "\n\n"); return; } BufChar = Buffer[(ACPI_SIZE) i + j]; if (ACPI_IS_PRINT (BufChar)) { FlPrintFile (FileId, "%c", BufChar); } else { FlPrintFile (FileId, "."); } } /* Done with that line. */ FlPrintFile (FileId, "\n"); i += 16; } FlPrintFile (FileId, "\n\n"); } /****************************************************************************** * * FUNCTION: DtDumpFieldList * * PARAMETERS: Field - Root field * * RETURN: None * * DESCRIPTION: Dump the entire field list * *****************************************************************************/ void DtDumpFieldList ( DT_FIELD *Field) { if (!Gbl_DebugFlag || !Field) { return; } DbgPrint (ASL_DEBUG_OUTPUT, "\nField List:\n" "LineNo ByteOff NameCol Column TableOff " "Flags %32s : %s\n\n", "Name", "Value"); while (Field) { DbgPrint (ASL_DEBUG_OUTPUT, "%.08X %.08X %.08X %.08X %.08X %.08X %32s : %s\n", Field->Line, Field->ByteOffset, Field->NameColumn, Field->Column, Field->TableOffset, Field->Flags, Field->Name, Field->Value); Field = Field->Next; } DbgPrint (ASL_DEBUG_OUTPUT, "\n\n"); } /****************************************************************************** * * FUNCTION: DtDumpSubtableInfo, DtDumpSubtableTree * * PARAMETERS: DT_WALK_CALLBACK * * RETURN: None * * DESCRIPTION: Info - dump a subtable tree entry with extra information. * Tree - dump a subtable tree formatted by depth indentation. * *****************************************************************************/ static void DtDumpSubtableInfo ( DT_SUBTABLE *Subtable, void *Context, void *ReturnValue) { DbgPrint (ASL_DEBUG_OUTPUT, "[%.04X] %.08X %.08X %.08X %.08X %.08X %p %p %p\n", Subtable->Depth, Subtable->Length, Subtable->TotalLength, Subtable->SizeOfLengthField, Subtable->Flags, Subtable, Subtable->Parent, Subtable->Child, Subtable->Peer); } static void DtDumpSubtableTree ( DT_SUBTABLE *Subtable, void *Context, void *ReturnValue) { DbgPrint (ASL_DEBUG_OUTPUT, "[%.04X] %*s%08X (%.02X) - (%.02X)\n", Subtable->Depth, (4 * Subtable->Depth), " ", Subtable, Subtable->Length, Subtable->TotalLength); } /****************************************************************************** * * FUNCTION: DtDumpSubtableList * * PARAMETERS: None * * RETURN: None * * DESCRIPTION: Dump the raw list of subtables with information, and also * dump the subtable list in formatted tree format. Assists with * the development of new table code. * *****************************************************************************/ void DtDumpSubtableList ( void) { if (!Gbl_DebugFlag || !Gbl_RootTable) { return; } DbgPrint (ASL_DEBUG_OUTPUT, "Subtable Info:\n" "Depth Length TotalLen LenSize Flags " "This Parent Child Peer\n\n"); DtWalkTableTree (Gbl_RootTable, DtDumpSubtableInfo, NULL, NULL); DbgPrint (ASL_DEBUG_OUTPUT, "\nSubtable Tree: (Depth, Subtable, Length, TotalLength)\n\n"); DtWalkTableTree (Gbl_RootTable, DtDumpSubtableTree, NULL, NULL); DbgPrint (ASL_DEBUG_OUTPUT, "\n"); } /****************************************************************************** * * FUNCTION: DtWriteFieldToListing * * PARAMETERS: Buffer - Contains the compiled data * Field - Field node for the input line * Length - Length of the output data * * RETURN: None * * DESCRIPTION: Write one field to the listing file (if listing is enabled). * *****************************************************************************/ void DtWriteFieldToListing ( UINT8 *Buffer, DT_FIELD *Field, UINT32 Length) { UINT8 FileByte; if (!Gbl_ListingFlag || !Field) { return; } /* Dump the original source line */ FlPrintFile (ASL_FILE_LISTING_OUTPUT, "Input: "); FlSeekFile (ASL_FILE_INPUT, Field->ByteOffset); while (FlReadFile (ASL_FILE_INPUT, &FileByte, 1) == AE_OK) { FlWriteFile (ASL_FILE_LISTING_OUTPUT, &FileByte, 1); if (FileByte == '\n') { break; } } /* Dump the line as parsed and represented internally */ FlPrintFile (ASL_FILE_LISTING_OUTPUT, "Parsed: %*s : %.64s", Field->Column-4, Field->Name, Field->Value); if (strlen (Field->Value) > 64) { FlPrintFile (ASL_FILE_LISTING_OUTPUT, "...Additional data, length 0x%X\n", strlen (Field->Value)); } FlPrintFile (ASL_FILE_LISTING_OUTPUT, "\n"); /* Dump the hex data that will be output for this field */ DtDumpBuffer (ASL_FILE_LISTING_OUTPUT, Buffer, Field->TableOffset, Length); } /****************************************************************************** * * FUNCTION: DtWriteTableToListing * * PARAMETERS: None * * RETURN: None * * DESCRIPTION: Write the entire compiled table to the listing file * in hex format * *****************************************************************************/ void DtWriteTableToListing ( void) { UINT8 *Buffer; if (!Gbl_ListingFlag) { return; } /* Read the entire table from the output file */ Buffer = UtLocalCalloc (Gbl_TableLength); FlSeekFile (ASL_FILE_AML_OUTPUT, 0); FlReadFile (ASL_FILE_AML_OUTPUT, Buffer, Gbl_TableLength); /* Dump the raw table data */ AcpiOsRedirectOutput (Gbl_Files[ASL_FILE_LISTING_OUTPUT].Handle); AcpiOsPrintf ("\n%s: Length %d (0x%X)\n\n", ACPI_RAW_TABLE_DATA_HEADER, Gbl_TableLength, Gbl_TableLength); AcpiUtDumpBuffer (Buffer, Gbl_TableLength, DB_BYTE_DISPLAY, 0); AcpiOsRedirectOutput (stdout); ACPI_FREE (Buffer); }
cmsd2/ChrisOS
libs/acpica/source/compiler/dtio.c
C
bsd-2-clause
32,862
/* * Copyright (C) 2008, 2009, 2010 Apple Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "ApplicationCacheGroup.h" #include "ApplicationCache.h" #include "ApplicationCacheHost.h" #include "ApplicationCacheResource.h" #include "ApplicationCacheStorage.h" #include "Chrome.h" #include "ChromeClient.h" #include "DOMApplicationCache.h" #include "DocumentLoader.h" #include "Frame.h" #include "FrameLoader.h" #include "FrameLoaderClient.h" #include "HTTPHeaderNames.h" #include "InspectorInstrumentation.h" #include "ManifestParser.h" #include "Page.h" #include "ProgressTracker.h" #include "ResourceHandle.h" #include "SecurityOrigin.h" #include "Settings.h" #include <wtf/HashMap.h> #include <wtf/MainThread.h> namespace WebCore { ApplicationCacheGroup::ApplicationCacheGroup(Ref<ApplicationCacheStorage>&& storage, const URL& manifestURL) : m_storage(WTFMove(storage)) , m_manifestURL(manifestURL) , m_origin(SecurityOrigin::create(manifestURL)) , m_updateStatus(Idle) , m_downloadingPendingMasterResourceLoadersCount(0) , m_progressTotal(0) , m_progressDone(0) , m_frame(nullptr) , m_storageID(0) , m_isObsolete(false) , m_completionType(None) , m_calledReachedMaxAppCacheSize(false) , m_availableSpaceInQuota(ApplicationCacheStorage::unknownQuota()) , m_originQuotaExceededPreviously(false) { } ApplicationCacheGroup::~ApplicationCacheGroup() { ASSERT(!m_newestCache); ASSERT(m_caches.isEmpty()); stopLoading(); m_storage->cacheGroupDestroyed(this); } ApplicationCache* ApplicationCacheGroup::cacheForMainRequest(const ResourceRequest& request, DocumentLoader* documentLoader) { if (!ApplicationCache::requestIsHTTPOrHTTPSGet(request)) return nullptr; URL url(request.url()); if (url.hasFragmentIdentifier()) url.removeFragmentIdentifier(); auto* page = documentLoader->frame() ? documentLoader->frame()->page() : nullptr; if (!page || page->usesEphemeralSession()) return nullptr; if (ApplicationCacheGroup* group = page->applicationCacheStorage().cacheGroupForURL(url)) { ASSERT(group->newestCache()); ASSERT(!group->isObsolete()); return group->newestCache(); } return nullptr; } ApplicationCache* ApplicationCacheGroup::fallbackCacheForMainRequest(const ResourceRequest& request, DocumentLoader* documentLoader) { if (!ApplicationCache::requestIsHTTPOrHTTPSGet(request)) return nullptr; URL url(request.url()); if (url.hasFragmentIdentifier()) url.removeFragmentIdentifier(); auto* page = documentLoader->frame() ? documentLoader->frame()->page() : nullptr; if (!page) return nullptr; if (ApplicationCacheGroup* group = page->applicationCacheStorage().fallbackCacheGroupForURL(url)) { ASSERT(group->newestCache()); ASSERT(!group->isObsolete()); return group->newestCache(); } return nullptr; } void ApplicationCacheGroup::selectCache(Frame* frame, const URL& passedManifestURL) { ASSERT(frame && frame->page()); if (!frame->settings().offlineWebApplicationCacheEnabled()) return; DocumentLoader* documentLoader = frame->loader().documentLoader(); ASSERT(!documentLoader->applicationCacheHost()->applicationCache()); if (passedManifestURL.isNull()) { selectCacheWithoutManifestURL(frame); return; } // Don't access anything on disk if private browsing is enabled. if (frame->page()->usesEphemeralSession() || !frame->document()->securityOrigin()->canAccessApplicationCache(frame->tree().top().document()->securityOrigin())) { postListenerTask(ApplicationCacheHost::CHECKING_EVENT, documentLoader); postListenerTask(ApplicationCacheHost::ERROR_EVENT, documentLoader); return; } URL manifestURL(passedManifestURL); if (manifestURL.hasFragmentIdentifier()) manifestURL.removeFragmentIdentifier(); ApplicationCache* mainResourceCache = documentLoader->applicationCacheHost()->mainResourceApplicationCache(); if (mainResourceCache) { if (manifestURL == mainResourceCache->group()->m_manifestURL) { // The cache may have gotten obsoleted after we've loaded from it, but before we parsed the document and saw cache manifest. if (mainResourceCache->group()->isObsolete()) return; mainResourceCache->group()->associateDocumentLoaderWithCache(documentLoader, mainResourceCache); mainResourceCache->group()->update(frame, ApplicationCacheUpdateWithBrowsingContext); } else { // The main resource was loaded from cache, so the cache must have an entry for it. Mark it as foreign. URL resourceURL(documentLoader->responseURL()); if (resourceURL.hasFragmentIdentifier()) resourceURL.removeFragmentIdentifier(); ApplicationCacheResource* resource = mainResourceCache->resourceForURL(resourceURL); bool inStorage = resource->storageID(); resource->addType(ApplicationCacheResource::Foreign); if (inStorage) frame->page()->applicationCacheStorage().storeUpdatedType(resource, mainResourceCache); // Restart the current navigation from the top of the navigation algorithm, undoing any changes that were made // as part of the initial load. // The navigation will not result in the same resource being loaded, because "foreign" entries are never picked during navigation. frame->navigationScheduler().scheduleLocationChange(frame->document(), frame->document()->securityOrigin(), documentLoader->url(), frame->loader().referrer()); } return; } // The resource was loaded from the network, check if it is a HTTP/HTTPS GET. const ResourceRequest& request = frame->loader().activeDocumentLoader()->request(); if (!ApplicationCache::requestIsHTTPOrHTTPSGet(request)) return; // Check that the resource URL has the same scheme/host/port as the manifest URL. if (!protocolHostAndPortAreEqual(manifestURL, request.url())) return; ApplicationCacheGroup* group = frame->page()->applicationCacheStorage().findOrCreateCacheGroup(manifestURL); documentLoader->applicationCacheHost()->setCandidateApplicationCacheGroup(group); group->m_pendingMasterResourceLoaders.add(documentLoader); group->m_downloadingPendingMasterResourceLoadersCount++; ASSERT(!group->m_cacheBeingUpdated || group->m_updateStatus != Idle); group->update(frame, ApplicationCacheUpdateWithBrowsingContext); } void ApplicationCacheGroup::selectCacheWithoutManifestURL(Frame* frame) { if (!frame->settings().offlineWebApplicationCacheEnabled()) return; DocumentLoader* documentLoader = frame->loader().documentLoader(); ASSERT(!documentLoader->applicationCacheHost()->applicationCache()); // Don't access anything on disk if private browsing is enabled. if (frame->page()->usesEphemeralSession() || !frame->document()->securityOrigin()->canAccessApplicationCache(frame->tree().top().document()->securityOrigin())) { postListenerTask(ApplicationCacheHost::CHECKING_EVENT, documentLoader); postListenerTask(ApplicationCacheHost::ERROR_EVENT, documentLoader); return; } ApplicationCache* mainResourceCache = documentLoader->applicationCacheHost()->mainResourceApplicationCache(); if (mainResourceCache) { mainResourceCache->group()->associateDocumentLoaderWithCache(documentLoader, mainResourceCache); mainResourceCache->group()->update(frame, ApplicationCacheUpdateWithBrowsingContext); } } void ApplicationCacheGroup::finishedLoadingMainResource(DocumentLoader* loader) { ASSERT(m_pendingMasterResourceLoaders.contains(loader)); ASSERT(m_completionType == None || m_pendingEntries.isEmpty()); URL url = loader->url(); if (url.hasFragmentIdentifier()) url.removeFragmentIdentifier(); switch (m_completionType) { case None: // The main resource finished loading before the manifest was ready. It will be handled via dispatchMainResources() later. return; case NoUpdate: ASSERT(!m_cacheBeingUpdated); associateDocumentLoaderWithCache(loader, m_newestCache.get()); if (ApplicationCacheResource* resource = m_newestCache->resourceForURL(url)) { if (!(resource->type() & ApplicationCacheResource::Master)) { resource->addType(ApplicationCacheResource::Master); ASSERT(!resource->storageID()); } } else m_newestCache->addResource(ApplicationCacheResource::create(url, loader->response(), ApplicationCacheResource::Master, loader->mainResourceData())); break; case Failure: // Cache update has been a failure, so there is no reason to keep the document associated with the incomplete cache // (its main resource was not cached yet, so it is likely that the application changed significantly server-side). ASSERT(!m_cacheBeingUpdated); // Already cleared out by stopLoading(). loader->applicationCacheHost()->setApplicationCache(nullptr); // Will unset candidate, too. m_associatedDocumentLoaders.remove(loader); postListenerTask(ApplicationCacheHost::ERROR_EVENT, loader); break; case Completed: ASSERT(m_associatedDocumentLoaders.contains(loader)); if (ApplicationCacheResource* resource = m_cacheBeingUpdated->resourceForURL(url)) { if (!(resource->type() & ApplicationCacheResource::Master)) { resource->addType(ApplicationCacheResource::Master); ASSERT(!resource->storageID()); } } else m_cacheBeingUpdated->addResource(ApplicationCacheResource::create(url, loader->response(), ApplicationCacheResource::Master, loader->mainResourceData())); // The "cached" event will be posted to all associated documents once update is complete. break; } ASSERT(m_downloadingPendingMasterResourceLoadersCount > 0); m_downloadingPendingMasterResourceLoadersCount--; checkIfLoadIsComplete(); } void ApplicationCacheGroup::failedLoadingMainResource(DocumentLoader* loader) { ASSERT(m_pendingMasterResourceLoaders.contains(loader)); ASSERT(m_completionType == None || m_pendingEntries.isEmpty()); switch (m_completionType) { case None: // The main resource finished loading before the manifest was ready. It will be handled via dispatchMainResources() later. return; case NoUpdate: ASSERT(!m_cacheBeingUpdated); // The manifest didn't change, and we have a relevant cache - but the main resource download failed mid-way, so it cannot be stored to the cache, // and the loader does not get associated to it. If there are other main resources being downloaded for this cache group, they may still succeed. postListenerTask(ApplicationCacheHost::ERROR_EVENT, loader); break; case Failure: // Cache update failed, too. ASSERT(!m_cacheBeingUpdated); // Already cleared out by stopLoading(). ASSERT(!loader->applicationCacheHost()->applicationCache() || loader->applicationCacheHost()->applicationCache()->group() == this); loader->applicationCacheHost()->setApplicationCache(nullptr); // Will unset candidate, too. m_associatedDocumentLoaders.remove(loader); postListenerTask(ApplicationCacheHost::ERROR_EVENT, loader); break; case Completed: // The cache manifest didn't list this main resource, and all cache entries were already updated successfully - but the main resource failed to load, // so it cannot be stored to the cache. If there are other main resources being downloaded for this cache group, they may still succeed. ASSERT(m_associatedDocumentLoaders.contains(loader)); ASSERT(loader->applicationCacheHost()->applicationCache() == m_cacheBeingUpdated); ASSERT(!loader->applicationCacheHost()->candidateApplicationCacheGroup()); m_associatedDocumentLoaders.remove(loader); loader->applicationCacheHost()->setApplicationCache(nullptr); postListenerTask(ApplicationCacheHost::ERROR_EVENT, loader); break; } ASSERT(m_downloadingPendingMasterResourceLoadersCount > 0); m_downloadingPendingMasterResourceLoadersCount--; checkIfLoadIsComplete(); } void ApplicationCacheGroup::stopLoading() { if (m_manifestHandle) { ASSERT(!m_currentHandle); ASSERT(m_manifestHandle->client() == this); m_manifestHandle->clearClient(); m_manifestHandle->cancel(); m_manifestHandle = nullptr; } if (m_currentHandle) { ASSERT(!m_manifestHandle); ASSERT(m_cacheBeingUpdated); ASSERT(m_currentHandle->client() == this); m_currentHandle->clearClient(); m_currentHandle->cancel(); m_currentHandle = nullptr; } // FIXME: Resetting just a tiny part of the state in this function is confusing. Callers have to take care of a lot more. m_cacheBeingUpdated = nullptr; m_pendingEntries.clear(); } void ApplicationCacheGroup::disassociateDocumentLoader(DocumentLoader* loader) { m_associatedDocumentLoaders.remove(loader); m_pendingMasterResourceLoaders.remove(loader); if (auto* host = loader->applicationCacheHost()) host->setApplicationCache(nullptr); // Will set candidate group to null, too. if (!m_associatedDocumentLoaders.isEmpty() || !m_pendingMasterResourceLoaders.isEmpty()) return; if (m_caches.isEmpty()) { // There is an initial cache attempt in progress. ASSERT(!m_newestCache); // Delete ourselves, causing the cache attempt to be stopped. delete this; return; } ASSERT(m_caches.contains(m_newestCache.get())); // Release our reference to the newest cache. This could cause us to be deleted. // Any ongoing updates will be stopped from destructor. m_newestCache = nullptr; } void ApplicationCacheGroup::cacheDestroyed(ApplicationCache* cache) { if (m_caches.remove(cache) && m_caches.isEmpty()) { ASSERT(m_associatedDocumentLoaders.isEmpty()); ASSERT(m_pendingMasterResourceLoaders.isEmpty()); delete this; } } void ApplicationCacheGroup::stopLoadingInFrame(Frame* frame) { if (frame != m_frame) return; cacheUpdateFailed(); } void ApplicationCacheGroup::setNewestCache(PassRefPtr<ApplicationCache> newestCache) { m_newestCache = newestCache; m_caches.add(m_newestCache.get()); m_newestCache->setGroup(this); } void ApplicationCacheGroup::makeObsolete() { if (isObsolete()) return; m_isObsolete = true; m_storage->cacheGroupMadeObsolete(this); ASSERT(!m_storageID); } void ApplicationCacheGroup::update(Frame* frame, ApplicationCacheUpdateOption updateOption) { if (m_updateStatus == Checking || m_updateStatus == Downloading) { if (updateOption == ApplicationCacheUpdateWithBrowsingContext) { postListenerTask(ApplicationCacheHost::CHECKING_EVENT, frame->loader().documentLoader()); if (m_updateStatus == Downloading) postListenerTask(ApplicationCacheHost::DOWNLOADING_EVENT, frame->loader().documentLoader()); } return; } // Don't access anything on disk if private browsing is enabled. if (frame->page()->usesEphemeralSession() || !frame->document()->securityOrigin()->canAccessApplicationCache(frame->tree().top().document()->securityOrigin())) { ASSERT(m_pendingMasterResourceLoaders.isEmpty()); ASSERT(m_pendingEntries.isEmpty()); ASSERT(!m_cacheBeingUpdated); postListenerTask(ApplicationCacheHost::CHECKING_EVENT, frame->loader().documentLoader()); postListenerTask(ApplicationCacheHost::ERROR_EVENT, frame->loader().documentLoader()); return; } ASSERT(!m_frame); m_frame = frame; setUpdateStatus(Checking); postListenerTask(ApplicationCacheHost::CHECKING_EVENT, m_associatedDocumentLoaders); if (!m_newestCache) { ASSERT(updateOption == ApplicationCacheUpdateWithBrowsingContext); postListenerTask(ApplicationCacheHost::CHECKING_EVENT, frame->loader().documentLoader()); } ASSERT(!m_manifestHandle); ASSERT(!m_manifestResource); ASSERT(!m_currentHandle); ASSERT(!m_currentResource); ASSERT(m_completionType == None); // FIXME: Handle defer loading m_manifestHandle = createResourceHandle(m_manifestURL, m_newestCache ? m_newestCache->manifestResource() : 0); } void ApplicationCacheGroup::abort(Frame* frame) { if (m_updateStatus == Idle) return; ASSERT(m_updateStatus == Checking || (m_updateStatus == Downloading && m_cacheBeingUpdated)); if (m_completionType != None) return; frame->document()->addConsoleMessage(MessageSource::AppCache, MessageLevel::Debug, ASCIILiteral("Application Cache download process was aborted.")); cacheUpdateFailed(); } RefPtr<ResourceHandle> ApplicationCacheGroup::createResourceHandle(const URL& url, ApplicationCacheResource* newestCachedResource) { ResourceRequest request(url); m_frame->loader().applyUserAgent(request); request.setHTTPHeaderField(HTTPHeaderName::CacheControl, "max-age=0"); if (newestCachedResource) { const String& lastModified = newestCachedResource->response().httpHeaderField(HTTPHeaderName::LastModified); const String& eTag = newestCachedResource->response().httpHeaderField(HTTPHeaderName::ETag); if (!lastModified.isEmpty() || !eTag.isEmpty()) { if (!lastModified.isEmpty()) request.setHTTPHeaderField(HTTPHeaderName::IfModifiedSince, lastModified); if (!eTag.isEmpty()) request.setHTTPHeaderField(HTTPHeaderName::IfNoneMatch, eTag); } } RefPtr<ResourceHandle> handle = ResourceHandle::create(m_frame->loader().networkingContext(), request, this, false, true); // Because willSendRequest only gets called during redirects, we initialize // the identifier and the first willSendRequest here. m_currentResourceIdentifier = m_frame->page()->progress().createUniqueIdentifier(); ResourceResponse redirectResponse = ResourceResponse(); InspectorInstrumentation::willSendRequest(m_frame, m_currentResourceIdentifier, m_frame->loader().documentLoader(), request, redirectResponse); return handle; } void ApplicationCacheGroup::didReceiveResponse(ResourceHandle* handle, ResourceResponse&& response) { ASSERT(m_frame); InspectorInstrumentationCookie cookie = InspectorInstrumentation::willReceiveResourceResponse(m_frame); InspectorInstrumentation::didReceiveResourceResponse(cookie, m_currentResourceIdentifier, m_frame->loader().documentLoader(), response, 0); if (handle == m_manifestHandle) { didReceiveManifestResponse(response); return; } ASSERT(handle == m_currentHandle); URL url(handle->firstRequest().url()); if (url.hasFragmentIdentifier()) url.removeFragmentIdentifier(); ASSERT(!m_currentResource); ASSERT(m_pendingEntries.contains(url)); unsigned type = m_pendingEntries.get(url); // If this is an initial cache attempt, we should not get master resources delivered here. if (!m_newestCache) ASSERT(!(type & ApplicationCacheResource::Master)); if (m_newestCache && response.httpStatusCode() == 304) { // Not modified. ApplicationCacheResource* newestCachedResource = m_newestCache->resourceForURL(url); if (newestCachedResource) { m_cacheBeingUpdated->addResource(ApplicationCacheResource::create(url, newestCachedResource->response(), type, &newestCachedResource->data(), newestCachedResource->path())); m_pendingEntries.remove(m_currentHandle->firstRequest().url()); m_currentHandle->cancel(); m_currentHandle = nullptr; // Load the next resource, if any. startLoadingEntry(); return; } // The server could return 304 for an unconditional request - in this case, we handle the response as a normal error. } if (response.httpStatusCode() / 100 != 2 || response.url() != m_currentHandle->firstRequest().url()) { if ((type & ApplicationCacheResource::Explicit) || (type & ApplicationCacheResource::Fallback)) { m_frame->document()->addConsoleMessage(MessageSource::AppCache, MessageLevel::Error, "Application Cache update failed, because " + m_currentHandle->firstRequest().url().stringCenterEllipsizedToLength() + ((response.httpStatusCode() / 100 != 2) ? " could not be fetched." : " was redirected.")); // Note that cacheUpdateFailed() can cause the cache group to be deleted. cacheUpdateFailed(); } else if (response.httpStatusCode() == 404 || response.httpStatusCode() == 410) { // Skip this resource. It is dropped from the cache. m_currentHandle->cancel(); m_currentHandle = nullptr; m_pendingEntries.remove(url); // Load the next resource, if any. startLoadingEntry(); } else { // Copy the resource and its metadata from the newest application cache in cache group whose completeness flag is complete, and act // as if that was the fetched resource, ignoring the resource obtained from the network. ASSERT(m_newestCache); ApplicationCacheResource* newestCachedResource = m_newestCache->resourceForURL(handle->firstRequest().url()); ASSERT(newestCachedResource); m_cacheBeingUpdated->addResource(ApplicationCacheResource::create(url, newestCachedResource->response(), type, &newestCachedResource->data(), newestCachedResource->path())); m_pendingEntries.remove(m_currentHandle->firstRequest().url()); m_currentHandle->cancel(); m_currentHandle = nullptr; // Load the next resource, if any. startLoadingEntry(); } return; } m_currentResource = ApplicationCacheResource::create(url, response, type); } void ApplicationCacheGroup::didReceiveData(ResourceHandle* handle, const char* data, unsigned length, int encodedDataLength) { UNUSED_PARAM(encodedDataLength); InspectorInstrumentation::didReceiveData(m_frame, m_currentResourceIdentifier, 0, length, 0); if (handle == m_manifestHandle) { didReceiveManifestData(data, length); return; } ASSERT(handle == m_currentHandle); ASSERT(m_currentResource); m_currentResource->data().append(data, length); } void ApplicationCacheGroup::didFinishLoading(ResourceHandle* handle, double finishTime) { InspectorInstrumentation::didFinishLoading(m_frame, m_frame->loader().documentLoader(), m_currentResourceIdentifier, finishTime); if (handle == m_manifestHandle) { didFinishLoadingManifest(); return; } ASSERT(m_currentHandle == handle); ASSERT(m_pendingEntries.contains(handle->firstRequest().url())); m_pendingEntries.remove(handle->firstRequest().url()); ASSERT(m_cacheBeingUpdated); m_cacheBeingUpdated->addResource(WTFMove(m_currentResource)); m_currentHandle = nullptr; // While downloading check to see if we have exceeded the available quota. // We can stop immediately if we have already previously failed // due to an earlier quota restriction. The client was already notified // of the quota being reached and decided not to increase it then. // FIXME: Should we break earlier and prevent redownloading on later page loads? if (m_originQuotaExceededPreviously && m_availableSpaceInQuota < m_cacheBeingUpdated->estimatedSizeInStorage()) { m_currentResource = nullptr; m_frame->document()->addConsoleMessage(MessageSource::AppCache, MessageLevel::Error, ASCIILiteral("Application Cache update failed, because size quota was exceeded.")); cacheUpdateFailed(); return; } // Load the next resource, if any. startLoadingEntry(); } void ApplicationCacheGroup::didFail(ResourceHandle* handle, const ResourceError& error) { InspectorInstrumentation::didFailLoading(m_frame, m_frame->loader().documentLoader(), m_currentResourceIdentifier, error); if (handle == m_manifestHandle) { // A network error is logged elsewhere, no need to log again. Also, it's normal for manifest fetching to fail when working offline. cacheUpdateFailed(); return; } ASSERT(handle == m_currentHandle); unsigned type = m_currentResource ? m_currentResource->type() : m_pendingEntries.get(handle->firstRequest().url()); URL url(handle->firstRequest().url()); if (url.hasFragmentIdentifier()) url.removeFragmentIdentifier(); ASSERT(!m_currentResource || !m_pendingEntries.contains(url)); m_currentResource = nullptr; m_pendingEntries.remove(url); if ((type & ApplicationCacheResource::Explicit) || (type & ApplicationCacheResource::Fallback)) { m_frame->document()->addConsoleMessage(MessageSource::AppCache, MessageLevel::Error, "Application Cache update failed, because " + url.stringCenterEllipsizedToLength() + " could not be fetched."); // Note that cacheUpdateFailed() can cause the cache group to be deleted. cacheUpdateFailed(); } else { // Copy the resource and its metadata from the newest application cache in cache group whose completeness flag is complete, and act // as if that was the fetched resource, ignoring the resource obtained from the network. ASSERT(m_newestCache); ApplicationCacheResource* newestCachedResource = m_newestCache->resourceForURL(url); ASSERT(newestCachedResource); m_cacheBeingUpdated->addResource(ApplicationCacheResource::create(url, newestCachedResource->response(), type, &newestCachedResource->data(), newestCachedResource->path())); // Load the next resource, if any. startLoadingEntry(); } } void ApplicationCacheGroup::didReceiveManifestResponse(const ResourceResponse& response) { ASSERT(!m_manifestResource); ASSERT(m_manifestHandle); if (response.httpStatusCode() == 404 || response.httpStatusCode() == 410) { InspectorInstrumentation::didFailLoading(m_frame, m_frame->loader().documentLoader(), m_currentResourceIdentifier, m_frame->loader().cancelledError(m_manifestHandle->firstRequest())); m_frame->document()->addConsoleMessage(MessageSource::AppCache, MessageLevel::Error, makeString("Application Cache manifest could not be fetched, because the manifest had a ", String::number(response.httpStatusCode()), " response.")); manifestNotFound(); return; } if (response.httpStatusCode() == 304) return; if (response.httpStatusCode() / 100 != 2) { InspectorInstrumentation::didFailLoading(m_frame, m_frame->loader().documentLoader(), m_currentResourceIdentifier, m_frame->loader().cancelledError(m_manifestHandle->firstRequest())); m_frame->document()->addConsoleMessage(MessageSource::AppCache, MessageLevel::Error, makeString("Application Cache manifest could not be fetched, because the manifest had a ", String::number(response.httpStatusCode()), " response.")); cacheUpdateFailed(); return; } if (response.url() != m_manifestHandle->firstRequest().url()) { InspectorInstrumentation::didFailLoading(m_frame, m_frame->loader().documentLoader(), m_currentResourceIdentifier, m_frame->loader().cancelledError(m_manifestHandle->firstRequest())); m_frame->document()->addConsoleMessage(MessageSource::AppCache, MessageLevel::Error, ASCIILiteral("Application Cache manifest could not be fetched, because a redirection was attempted.")); cacheUpdateFailed(); return; } m_manifestResource = ApplicationCacheResource::create(m_manifestHandle->firstRequest().url(), response, ApplicationCacheResource::Manifest); } void ApplicationCacheGroup::didReceiveManifestData(const char* data, int length) { if (m_manifestResource) m_manifestResource->data().append(data, length); } void ApplicationCacheGroup::didFinishLoadingManifest() { bool isUpgradeAttempt = m_newestCache; if (!isUpgradeAttempt && !m_manifestResource) { // The server returned 304 Not Modified even though we didn't send a conditional request. m_frame->document()->addConsoleMessage(MessageSource::AppCache, MessageLevel::Error, ASCIILiteral("Application Cache manifest could not be fetched because of an unexpected 304 Not Modified server response.")); cacheUpdateFailed(); return; } m_manifestHandle = nullptr; // Check if the manifest was not modified. if (isUpgradeAttempt) { ApplicationCacheResource* newestManifest = m_newestCache->manifestResource(); ASSERT(newestManifest); if (!m_manifestResource || // The resource will be null if HTTP response was 304 Not Modified. (newestManifest->data().size() == m_manifestResource->data().size() && !memcmp(newestManifest->data().data(), m_manifestResource->data().data(), newestManifest->data().size()))) { m_completionType = NoUpdate; m_manifestResource = nullptr; deliverDelayedMainResources(); return; } } Manifest manifest; if (!parseManifest(m_manifestURL, m_manifestResource->data().data(), m_manifestResource->data().size(), manifest)) { // At the time of this writing, lack of "CACHE MANIFEST" signature is the only reason for parseManifest to fail. m_frame->document()->addConsoleMessage(MessageSource::AppCache, MessageLevel::Error, ASCIILiteral("Application Cache manifest could not be parsed. Does it start with CACHE MANIFEST?")); cacheUpdateFailed(); return; } ASSERT(!m_cacheBeingUpdated); m_cacheBeingUpdated = ApplicationCache::create(); m_cacheBeingUpdated->setGroup(this); for (auto& loader : m_pendingMasterResourceLoaders) associateDocumentLoaderWithCache(loader, m_cacheBeingUpdated.get()); // We have the manifest, now download the resources. setUpdateStatus(Downloading); postListenerTask(ApplicationCacheHost::DOWNLOADING_EVENT, m_associatedDocumentLoaders); ASSERT(m_pendingEntries.isEmpty()); if (isUpgradeAttempt) { for (const auto& urlAndResource : m_newestCache->resources()) { unsigned type = urlAndResource.value->type(); if (type & ApplicationCacheResource::Master) addEntry(urlAndResource.key, type); } } for (const auto& explicitURL : manifest.explicitURLs) addEntry(explicitURL, ApplicationCacheResource::Explicit); for (auto& fallbackURL : manifest.fallbackURLs) addEntry(fallbackURL.second, ApplicationCacheResource::Fallback); m_cacheBeingUpdated->setOnlineWhitelist(manifest.onlineWhitelistedURLs); m_cacheBeingUpdated->setFallbackURLs(manifest.fallbackURLs); m_cacheBeingUpdated->setAllowsAllNetworkRequests(manifest.allowAllNetworkRequests); m_progressTotal = m_pendingEntries.size(); m_progressDone = 0; recalculateAvailableSpaceInQuota(); startLoadingEntry(); } void ApplicationCacheGroup::didReachMaxAppCacheSize() { ASSERT(m_frame); ASSERT(m_cacheBeingUpdated); m_frame->page()->chrome().client().reachedMaxAppCacheSize(m_frame->page()->applicationCacheStorage().spaceNeeded(m_cacheBeingUpdated->estimatedSizeInStorage())); m_calledReachedMaxAppCacheSize = true; checkIfLoadIsComplete(); } void ApplicationCacheGroup::didReachOriginQuota(int64_t totalSpaceNeeded) { // Inform the client the origin quota has been reached, they may decide to increase the quota. // We expect quota to be increased synchronously while waiting for the call to return. m_frame->page()->chrome().client().reachedApplicationCacheOriginQuota(m_origin.get(), totalSpaceNeeded); } void ApplicationCacheGroup::cacheUpdateFailed() { stopLoading(); m_manifestResource = nullptr; // Wait for master resource loads to finish. m_completionType = Failure; deliverDelayedMainResources(); } void ApplicationCacheGroup::recalculateAvailableSpaceInQuota() { if (!m_frame->page()->applicationCacheStorage().calculateRemainingSizeForOriginExcludingCache(m_origin.get(), m_newestCache.get(), m_availableSpaceInQuota)) { // Failed to determine what is left in the quota. Fallback to allowing anything. m_availableSpaceInQuota = ApplicationCacheStorage::noQuota(); } } void ApplicationCacheGroup::manifestNotFound() { makeObsolete(); postListenerTask(ApplicationCacheHost::OBSOLETE_EVENT, m_associatedDocumentLoaders); postListenerTask(ApplicationCacheHost::ERROR_EVENT, m_pendingMasterResourceLoaders); stopLoading(); ASSERT(m_pendingEntries.isEmpty()); m_manifestResource = nullptr; while (!m_pendingMasterResourceLoaders.isEmpty()) { HashSet<DocumentLoader*>::iterator it = m_pendingMasterResourceLoaders.begin(); ASSERT((*it)->applicationCacheHost()->candidateApplicationCacheGroup() == this); ASSERT(!(*it)->applicationCacheHost()->applicationCache()); (*it)->applicationCacheHost()->setCandidateApplicationCacheGroup(nullptr); m_pendingMasterResourceLoaders.remove(it); } m_downloadingPendingMasterResourceLoadersCount = 0; setUpdateStatus(Idle); m_frame = nullptr; if (m_caches.isEmpty()) { ASSERT(m_associatedDocumentLoaders.isEmpty()); ASSERT(!m_cacheBeingUpdated); delete this; } } void ApplicationCacheGroup::checkIfLoadIsComplete() { if (m_manifestHandle || !m_pendingEntries.isEmpty() || m_downloadingPendingMasterResourceLoadersCount) return; // We're done, all resources have finished downloading (successfully or not). bool isUpgradeAttempt = m_newestCache; switch (m_completionType) { case None: ASSERT_NOT_REACHED(); return; case NoUpdate: ASSERT(isUpgradeAttempt); ASSERT(!m_cacheBeingUpdated); // The storage could have been manually emptied by the user. if (!m_storageID) m_storage->storeNewestCache(this); postListenerTask(ApplicationCacheHost::NOUPDATE_EVENT, m_associatedDocumentLoaders); break; case Failure: ASSERT(!m_cacheBeingUpdated); postListenerTask(ApplicationCacheHost::ERROR_EVENT, m_associatedDocumentLoaders); if (m_caches.isEmpty()) { ASSERT(m_associatedDocumentLoaders.isEmpty()); delete this; return; } break; case Completed: { // FIXME: Fetch the resource from manifest URL again, and check whether it is identical to the one used for update (in case the application was upgraded server-side in the meanwhile). (<rdar://problem/6467625>) ASSERT(m_cacheBeingUpdated); if (m_manifestResource) m_cacheBeingUpdated->setManifestResource(WTFMove(m_manifestResource)); else { // We can get here as a result of retrying the Complete step, following // a failure of the cache storage to save the newest cache due to hitting // the maximum size. In such a case, m_manifestResource may be 0, as // the manifest was already set on the newest cache object. ASSERT(m_cacheBeingUpdated->manifestResource()); ASSERT(m_storage->isMaximumSizeReached()); ASSERT(m_calledReachedMaxAppCacheSize); } RefPtr<ApplicationCache> oldNewestCache = (m_newestCache == m_cacheBeingUpdated) ? RefPtr<ApplicationCache>() : m_newestCache; // If we exceeded the origin quota while downloading we can request a quota // increase now, before we attempt to store the cache. int64_t totalSpaceNeeded; if (!m_storage->checkOriginQuota(this, oldNewestCache.get(), m_cacheBeingUpdated.get(), totalSpaceNeeded)) didReachOriginQuota(totalSpaceNeeded); ApplicationCacheStorage::FailureReason failureReason; setNewestCache(WTFMove(m_cacheBeingUpdated)); if (m_storage->storeNewestCache(this, oldNewestCache.get(), failureReason)) { // New cache stored, now remove the old cache. if (oldNewestCache) m_storage->remove(oldNewestCache.get()); // Fire the final progress event. ASSERT(m_progressDone == m_progressTotal); postListenerTask(ApplicationCacheHost::PROGRESS_EVENT, m_progressTotal, m_progressDone, m_associatedDocumentLoaders); // Fire the success event. postListenerTask(isUpgradeAttempt ? ApplicationCacheHost::UPDATEREADY_EVENT : ApplicationCacheHost::CACHED_EVENT, m_associatedDocumentLoaders); // It is clear that the origin quota was not reached, so clear the flag if it was set. m_originQuotaExceededPreviously = false; } else { if (failureReason == ApplicationCacheStorage::OriginQuotaReached) { // We ran out of space for this origin. Fall down to the normal error handling // after recording this state. m_originQuotaExceededPreviously = true; m_frame->document()->addConsoleMessage(MessageSource::AppCache, MessageLevel::Error, ASCIILiteral("Application Cache update failed, because size quota was exceeded.")); } if (failureReason == ApplicationCacheStorage::TotalQuotaReached && !m_calledReachedMaxAppCacheSize) { // FIXME: Should this be handled more like Origin Quotas? Does this fail properly? // We ran out of space. All the changes in the cache storage have // been rolled back. We roll back to the previous state in here, // as well, call the chrome client asynchronously and retry to // save the new cache. // Save a reference to the new cache. m_cacheBeingUpdated = WTFMove(m_newestCache); if (oldNewestCache) { // Reinstate the oldNewestCache. setNewestCache(WTFMove(oldNewestCache)); } scheduleReachedMaxAppCacheSizeCallback(); return; } // Run the "cache failure steps" // Fire the error events to all pending master entries, as well any other cache hosts // currently associated with a cache in this group. postListenerTask(ApplicationCacheHost::ERROR_EVENT, m_associatedDocumentLoaders); // Disassociate the pending master entries from the failed new cache. Note that // all other loaders in the m_associatedDocumentLoaders are still associated with // some other cache in this group. They are not associated with the failed new cache. // Need to copy loaders, because the cache group may be destroyed at the end of iteration. Vector<DocumentLoader*> loaders; copyToVector(m_pendingMasterResourceLoaders, loaders); for (auto& loader : loaders) disassociateDocumentLoader(loader); // This can delete this group. // Reinstate the oldNewestCache, if there was one. if (oldNewestCache) { // This will discard the failed new cache. setNewestCache(WTFMove(oldNewestCache)); } else { // We must have been deleted by the last call to disassociateDocumentLoader(). return; } } break; } } // Empty cache group's list of pending master entries. m_pendingMasterResourceLoaders.clear(); m_completionType = None; setUpdateStatus(Idle); m_frame = nullptr; m_availableSpaceInQuota = ApplicationCacheStorage::unknownQuota(); m_calledReachedMaxAppCacheSize = false; } void ApplicationCacheGroup::startLoadingEntry() { ASSERT(m_cacheBeingUpdated); if (m_pendingEntries.isEmpty()) { m_completionType = Completed; deliverDelayedMainResources(); return; } EntryMap::const_iterator it = m_pendingEntries.begin(); postListenerTask(ApplicationCacheHost::PROGRESS_EVENT, m_progressTotal, m_progressDone, m_associatedDocumentLoaders); m_progressDone++; ASSERT(!m_currentHandle); m_currentHandle = createResourceHandle(URL(ParsedURLString, it->key), m_newestCache ? m_newestCache->resourceForURL(it->key) : 0); } void ApplicationCacheGroup::deliverDelayedMainResources() { // Need to copy loaders, because the cache group may be destroyed at the end of iteration. Vector<DocumentLoader*> loaders; copyToVector(m_pendingMasterResourceLoaders, loaders); size_t count = loaders.size(); for (size_t i = 0; i != count; ++i) { DocumentLoader* loader = loaders[i]; if (loader->isLoadingMainResource()) continue; const ResourceError& error = loader->mainDocumentError(); if (error.isNull()) finishedLoadingMainResource(loader); else failedLoadingMainResource(loader); } if (!count) checkIfLoadIsComplete(); } void ApplicationCacheGroup::addEntry(const String& url, unsigned type) { ASSERT(m_cacheBeingUpdated); ASSERT(!URL(ParsedURLString, url).hasFragmentIdentifier()); // Don't add the URL if we already have an master resource in the cache // (i.e., the main resource finished loading before the manifest). if (ApplicationCacheResource* resource = m_cacheBeingUpdated->resourceForURL(url)) { ASSERT(resource->type() & ApplicationCacheResource::Master); ASSERT(!m_frame->loader().documentLoader()->isLoadingMainResource()); resource->addType(type); return; } // Don't add the URL if it's the same as the manifest URL. ASSERT(m_manifestResource); if (m_manifestResource->url() == url) { m_manifestResource->addType(type); return; } EntryMap::AddResult result = m_pendingEntries.add(url, type); if (!result.isNewEntry) result.iterator->value |= type; } void ApplicationCacheGroup::associateDocumentLoaderWithCache(DocumentLoader* loader, ApplicationCache* cache) { // If teardown started already, revive the group. if (!m_newestCache && !m_cacheBeingUpdated) m_newestCache = cache; ASSERT(!m_isObsolete); loader->applicationCacheHost()->setApplicationCache(cache); ASSERT(!m_associatedDocumentLoaders.contains(loader)); m_associatedDocumentLoaders.add(loader); } class ChromeClientCallbackTimer: public TimerBase { public: ChromeClientCallbackTimer(ApplicationCacheGroup* cacheGroup) : m_cacheGroup(cacheGroup) { } private: void fired() override { m_cacheGroup->didReachMaxAppCacheSize(); delete this; } // Note that there is no need to use a RefPtr here. The ApplicationCacheGroup instance is guaranteed // to be alive when the timer fires since invoking the ChromeClient callback is part of its normal // update machinery and nothing can yet cause it to get deleted. ApplicationCacheGroup* m_cacheGroup; }; void ApplicationCacheGroup::scheduleReachedMaxAppCacheSizeCallback() { ASSERT(isMainThread()); ChromeClientCallbackTimer* timer = new ChromeClientCallbackTimer(this); timer->startOneShot(0); // The timer will delete itself once it fires. } void ApplicationCacheGroup::postListenerTask(ApplicationCacheHost::EventID eventID, int progressTotal, int progressDone, const HashSet<DocumentLoader*>& loaderSet) { for (auto& loader : loaderSet) postListenerTask(eventID, progressTotal, progressDone, loader); } void ApplicationCacheGroup::postListenerTask(ApplicationCacheHost::EventID eventID, int progressTotal, int progressDone, DocumentLoader* loader) { Frame* frame = loader->frame(); if (!frame) return; ASSERT(frame->loader().documentLoader() == loader); RefPtr<DocumentLoader> loaderProtector(loader); frame->document()->postTask([loaderProtector, eventID, progressTotal, progressDone] (ScriptExecutionContext& context) { ASSERT_UNUSED(context, context.isDocument()); Frame* frame = loaderProtector->frame(); if (!frame) return; ASSERT(frame->loader().documentLoader() == loaderProtector); loaderProtector->applicationCacheHost()->notifyDOMApplicationCache(eventID, progressTotal, progressDone); }); } void ApplicationCacheGroup::setUpdateStatus(UpdateStatus status) { m_updateStatus = status; } void ApplicationCacheGroup::clearStorageID() { m_storageID = 0; for (const auto& cache : m_caches) cache->clearStorageID(); } }
applesrc/WebCore
loader/appcache/ApplicationCacheGroup.cpp
C++
bsd-2-clause
46,690
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <link rel="stylesheet" href="/srcnet/css/srcnet.css" type="text/css"> <title> Assetur - http://www.assetur.com.br </title> <table width="757" border="0" align='center'> <tr> </td> </tr> </table> <br> <script type="text/javascript" src="/srcnet/js/srcnet.js"></script> <script language="JavaScript" type="text/JavaScript"> <!-- function popupLinha(theURL,winName,features) { //v2.0 window.open(theURL,winName,features); } //--> </script> <style type="text/css"> <!-- img { border: 0 none; } --> </style> </head> <body> <table width="789" border="0" align="center"> <tr> <td width="91" colspan="2"><div align="center"> <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0" width="800" height="74"> <param name="movie" value="assetur/flash/horario_itinerario.swf"> <param name="quality" value="high"> <embed src="assetur/flash/horario_itinerario.swf" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="800" height="74"></embed> </object> </div></td> </tr> <tr> <td colspan="2" class="dicaescura">&nbsp;</td> </tr> <tr> <td align="center"><img src="/srcnet/images/consultalinhas2.gif"></td> </tr> <tr> <td align="center">&nbsp;</td> </tr> <tr> <td colspan="2" class="dicaescura"> <div align="justify">Para consultar os itiner&aacute;rios e hor&aacute;rios, escolha o nome de uma linha na listagem e clique no bot&atilde;o &quot;Pesquisar&quot;. Para consultar pelo numero da linha (Exemplo &quot;085&quot;, &quot;070&quot;), escola o n&uacute;mero da linha no Campo &quot;N&uacute;mero da Linha&quot; e clique em &quot;Pesquisar&quot;, ou para consultar as linhas, digite a descri&ccedil;&atilde;o no campo &quot;Logradouro&quot; ou &quot;Bairro&quot; e clique no bot&atilde;o &quot;Pesquisar&quot;.</div></td> </tr></table> <form method=post action="/srcnet/ServletSrcNet" name="formpsq"> <input type="hidden" name="op" value="intinerariohorario"> <input type="hidden" name="SessionUsuario" value="8b7b4d69d89a35a97bdfb8ed8fd2"> <table border="0" class="tablecad" cellspacing="0" cellpadding="0" width="770" align="center"> <tr> <td width="1%"><div align="left"></div></td> <td width="99%"> <table width="770" border="0" align="center"> <tr> <td width="1%"><div align="left"></div> </td> <td width="99%"> <table width="770" border="0"> <tr> <td align="center"><font size="1" face="Verdana, Arial, Helvetica, sans-serif"><strong>Pesquisa por:</strong></font></td> </tr> <tr> <td align="center"><font size="1" face="Verdana, Arial, Helvetica, sans-serif"><strong>Linha:</strong></font><font size="2" face="Verdana, Arial, Helvetica, sans-serif"><strong> <select name='IdLinha' class='combo' onKeyPress="autoTab(this, event)"> <option value="0" selected>---- Selecione a Linha ----</option><option value="111"> AERO RANCHO/CENTENÁRIO - LINHA 111</option><option value="517"> ARNALDO FIGUEIRDO - PRAÇA - LINHA 517</option><option value="915">(EER) PEG-FÁCIL PI HÉRCULES Maymone - LINHA 915</option><option value="238">238 - LINHA 238</option><option value="83">AERO RANCHO - EXPRESSO - LINHA 083</option><option value="76">AERO RANCHO - HERCULES MAYMONE - LINHA 076</option><option value="129">AERO RANCHO - NOTURNO - LINHA 129</option><option value="198">AERO RANCHO - TURNO - LINHA 198</option><option value="80">AERO RANCHO/GAL. OSORIO - LINHA 080</option><option value="112">AERO RANCHO/MORENÃO-A - LINHA 112</option><option value="120">AERO RANCHO/MORENÃO-B - LINHA 120</option><option value="190">AERO RANCHO/PRAÇA(EXECUTIVA) - LINHA 190</option><option value="82">AERO RANCHO/SHOPPING - LINHA 082</option><option value="15">Aeroporto - Hoteis - LINHA 015</option><option value="408">AEROPORTO (AZUL) - LINHA 408</option><option value="314">ALBERT SABIN - CENTRO - LINHA 314</option><option value="407">ANA MARIA DO COUTO (AZUL) - LINHA 407</option><option value="209">ANACHE /NOVA LIMA - LINHA 209</option><option value="315">AQUARIUS - LINHA 315</option><option value="122">AV. DAS BANDEIRAS - LINHA 122</option><option value="116">AVENIDA DOS CAFEZAIS - LINHA 116</option><option value="113">BÁLSAMO/CENTRO OESTE (AZUL) - LINHA 113</option><option value="354">BANDEIRANTES - NORTE SUL - LINHA 354</option><option value="71">BANDEIRANTES/JÚLIO DE CASTILHO - LINHA 071</option><option value="320">Bertin/Induspan - LINHA 320</option><option value="303">BONANÇA - LINHA 303</option><option value="217">BOSQUE DO AVILÃ - LINHA 217</option><option value="306">BURITI /BOM JARDIM - LINHA 306</option><option value="229">CABREÚVA - SEMINÁRIO - LINHA 229</option><option value="309">CAIOBÁ - AERO RANCHO - LINHA 309</option><option value="302">CAIOBÁ II - LINHA 302</option><option value="213">CAMPO BELO (AZUL) - LINHA 213</option><option value="602">Campo Grande-Anhanduí - LINHA 602</option><option value="214">CAMPO NOVO (AZUL) - LINHA 214</option><option value="131">CENTENÁRIO/MORENAO - LINHA 131</option><option value="525">Centro - Noturno - LINHA 525</option><option value="107">CENTRO OESTE/UIRAPURU (AZUL) - LINHA 107</option><option value="119">CHÁCARA DAS MANSÕES - LINHA 119</option><option value="50">CIDADE DO NATAL - LINHA 050</option><option value="208">COLÚMBIA (AZUL) - LINHA 208</option><option value="145">Convencional substituindo executivo 190 - LINHA 145</option><option value="146">Convencional substituindo executivo 191 - LINHA 146</option><option value="147">Convencional substituindo executivo 193 - LINHA 147</option><option value="245">Convencional substituindo executivo 290 - LINHA 245</option><option value="246">Convencional substituindo executivo 291 - LINHA 246</option><option value="247">Convencional substituindo executivo 292 - LINHA 247</option><option value="345">Convencional substituindo executivo 390 - LINHA 345</option><option value="346">Convencional substituindo executivo 391 - LINHA 346</option><option value="347">Convencional substituindo executivo 393 - LINHA 347</option><option value="445">Convencional substituindo executivo 490 - LINHA 445</option><option value="446">Convencional substituindo executivo 491 - LINHA 446</option><option value="447">Convencional substituindo executivo 492 - LINHA 447</option><option value="547">Convencional substituindo executivo 592 - LINHA 547</option><option value="548">Convencional substituindo executivo 593 - LINHA 548</option><option value="508">COOPHARÁDIO - LINHA 508</option><option value="53">Coophasul/Arnaldo Estevao de Figueiredo - LINHA 053</option><option value="292">Coophasul/Nasser-Shopping - LINHA 292</option><option value="404">COOPHATRABALHO (AZUL) - LINHA 404</option><option value="328">COOPHAVILA 2 - NOTURNO - LINHA 328</option><option value="390">COOPHAVILA II/PRAÇA - LINHA 390</option><option value="329">COOPHAVILA/UNIÃO - TURNO - LINHA 329</option><option value="311">COPHAVILA II - TERMINAL AERO RANCHO - LINHA 311</option><option value="425">Corredor Jardim Carioca - LINHA 425</option><option value="423">CORREDOR JULIO DE CASTILHO - LINHA 423</option><option value="515">DAMHA/HERCULES MAYMONE - LINHA 515</option><option value="520">DIRETO - LINHA 520</option><option value="319">DOM ANTÔNIO-LAGEADO - LINHA 319</option><option value="511">DR. ALBUQUERQUE/TROPICAL (AZUL - LINHA 511</option><option value="236">ECO PARK - LINHA 236</option><option value="400">Especial cemiterio - LINHA 400</option><option value="300">Especial cemiterio - LINHA 300</option><option value="100">Especial cemiterio - LINHA 100</option><option value="500">Especial cemiterio - LINHA 500</option><option value="499">Especial outros - LINHA 499</option><option value="399">Especial outros - LINHA 399</option><option value="239">Especial RIACHUELO - LINHA 239</option><option value="911">ESTAÇÃO PEG FÁCIL 13 DE MAIO/PRAÇA - LINHA 911</option><option value="910">ESTAÇÃO PEG FÁCIL 14 DE JULHO/PRAÇA - LINHA 910</option><option value="909">ESTAÇÃO PEG FÁCIL 15 DE NOVEMBRO/PRAÇA - LINHA 909</option><option value="913">ESTAÇÃO PEG FÁCIL AFONSO PENA/PRAÇA - LINHA 913</option><option value="912">ESTAÇÃO PEG FÁCIL PLANETA REAL - LINHA 912</option><option value="206">ESTRELA DALVA - LINHA 206</option><option value="202">ESTRELA DALVA/ GIOCONDO ORSI - LINHA 202</option><option value="216">ESTRELA DO SUL (AZUL) - LINHA 216</option><option value="70">GAL. OSÓRIO/BANDEIRANTES - LINHA 070</option><option value="426">GAMELEIRA - LINHA 426</option><option value="317">GAMELEIRA/AERO RANCHO - LINHA 317</option><option value="87">GENERAL OSÓRIO/GUAICURUS - LINHA 087</option><option value="505">GUAICURUS - LINHA 505</option><option value="115">GUAICURUS - AERO RANCHO - LINHA 115</option><option value="197">GUAICURUS - TURNO - LINHA 197</option><option value="89">GUAICURUS EXPRESSO - LINHA 089</option><option value="88">GUAICURUS SHOPPING (VERMELHO) - LINHA 088</option><option value="101">gUAICURUS/AERO RANCHO - " B " - LINHA 101</option><option value="75">Guaicurus/BR - 262 - LINHA 075</option><option value="323">GUANANDI (AZUL) - LINHA 323</option><option value="502">HORTÊNCIAS (AZUL) - LINHA 502</option><option value="503">IRACY COELHO (AZUL) - LINHA 503</option><option value="103">ITAMARACÁ (AZUL) - LINHA 103</option><option value="114">JD. CANGURÚ (AZUL) - LINHA 114</option><option value="421">JD. CARIOCA - LINHA 421</option><option value="318">JD. PÊNFIGO (AZUL) - LINHA 318</option><option value="415">JD.IMÁ - LINHA 415</option><option value="401">JOSÉ ABRÃO - INT. - LINHA 401</option><option value="491">JOSÉ ABRÃO/EXECUTIVO - LINHA 491</option><option value="52">JULIO DE CASTILHO EXPRESSO - LINHA 052</option><option value="419">JÚLIO DE CASTILHO/PARQUE INDUSTRIAL - LINHA 419</option><option value="86">JULIO DE CASTILHO/SHOPPING (VE - LINHA 086</option><option value="474">JULIO DE CASTILHO/UCDB - LINHA 474</option><option value="220">LAGOA DA CRUZ - INT. - LINHA 220</option><option value="524">LEON DENIZART CONTE - LINHA 524</option><option value="108">LOS ANGELES (AZUL) - LINHA 108</option><option value="498">LOS ANGELES/POPULAR -TURNO - LINHA 498</option><option value="118">MACRO-ANEL / CARAVAGIO - LINHA 118</option><option value="512">MANSUR - LINHA 512</option><option value="228">MARABÁ - LINHA 228</option><option value="121">MARCOS ROBERTO A - LINHA 121</option><option value="523">MARIA APARECIDA PEDROSSIAN - CENTRO - LINHA 523</option><option value="516">MARIA APARECIDA PEDROSSIAN-OITI - LINHA 516</option><option value="526">MARIA PEDROSSIAN- NOVA BAHIA - LINHA 526</option><option value="327">MARINGÁ - NOTURNO - LINHA 327</option><option value="223">MARLI - INT. - LINHA 223</option><option value="232">MATA DO JACINTO - NOT. - LINHA 232</option><option value="203">MATA DO JACINTO (AZUL) - LINHA 203</option><option value="290">MATA DO JACINTO- SHOPPING DOS IPÊS EXECUTIVA - LINHA 290</option><option value="201">MONTE CARLO (INTEGRAÇÃO) - LINHA 201</option><option value="218">MONTE CASTELO (INTEGRAÇÃO) - LINHA 218</option><option value="85">MORENÃO/JULIO DE CASTILHO - LINHA 085</option><option value="199">MORENINHA - TURNO - LINHA 199</option><option value="130">MORENINHA 3 - NOTURNO - LINHA 130</option><option value="126">MORENINHA 3 E 4(AZUL) - LINHA 126</option><option value="191">MORENINHA/PRAÇA(EXECUTIVA) - LINHA 191</option><option value="61">MORENINHA/SHOPPING - LINHA 061</option><option value="63">Moreninhas - Aero Rancho - LINHA 063</option><option value="127">Moreninhas 3 e 4 - Sta Felicidade - LINHA 127</option><option value="62">MORENINHAS/EXPRESSO - LINHA 062</option><option value="226">NASSER - INT. - LINHA 226</option><option value="519">NOROESTE (INTEGRAÇÃO) - LINHA 519</option><option value="81">NOVA BAHIA - LINHA 081</option><option value="205">NOVA BAHIA - LINHA 205</option><option value="291">NOVA BAHIA/ SHOPPING DOS IPÊS- EXECUTIVA - LINHA 291</option><option value="73">NOVA BAHIA/JULIO DE CASTILIO - LINHA 073</option><option value="72">NOVA BAHIA/MORENÃO - LINHA 072</option><option value="84">NOVA BAHIA/PÇA. ARY COELHO (VE - LINHA 084</option><option value="414">NOVA CAMPO GRANDE (INTEGRAÇÃO) - LINHA 414</option><option value="490">NOVA CAMPO GRANDE/EXECUTIVO - LINHA 490</option><option value="298">NOVA LIMA - TURNO - LINHA 298</option><option value="212">NOVA LIMA (AZUL) - LINHA 212</option><option value="204">NOVOS ESTADOS (AZUL) - LINHA 204</option><option value="424">NUCLEO INDUSTRIAL - NOVA BAHIA - LINHA 424</option><option value="413">NÚCLEO INDUSTRIAL (AZUL) - LINHA 413</option><option value="418">NÚCLEO INDUSTRIAL / AERO RANCHO - LINHA 418</option><option value="304">OLIVEIRA (AZUL) - LINHA 304</option><option value="237">Oscar Salazar - LINHA 237</option><option value="231">OTÁVIO PÉCORA - LINHA 231</option><option value="219">OTÁVIO PÉCORA (INTEGRAÇÃO) - LINHA 219</option><option value="110">PARQUE DO SOL (AZUL) - LINHA 110</option><option value="241">PARQUE DOS PODERES - LINHA 241</option><option value="521">PARQUE DOS PODERES - LINHA 521</option><option value="230">PARQUE DOS PODERES (AZUL) - LINHA 230</option><option value="417">PARQUE INDUSTRIAL / SOPRANO - LINHA 417</option><option value="422">PARQUE INDUSTRIAL- MORENÃO - LINHA 422</option><option value="105">PAULO COELHO MACHADO - LINHA 105</option><option value="914">PEG-FÁCIL SHOPPING - LINHA 914</option><option value="102">PERPÉTUO SOCORRO (AZUL) - LINHA 102</option><option value="420">PETRÓPOLIS - NOTURNO - LINHA 420</option><option value="507">PIONEIROS (AZUL) - LINHA 507</option><option value="416">PLANALTO/SANTA CARMÉLIA INTEGRAÇÃO - LINHA 416</option><option value="234">PÓLO EMP. NORTE - LINHA 234</option><option value="409">POPULAR - INT. - LINHA 409</option><option value="410">POPULAR/JD. ITÁLIA - LINHA 410</option><option value="117">Ramez Tebet / Cohab - LINHA 117</option><option value="104">RECANTO DOS ROUXINÓIS (AZUL) - LINHA 104</option><option value="509">RITA VIEIRA - LINHA 509</option><option value="522">RITA VIEIRA / CRISTO REDENTOR - LINHA 522</option><option value="506">ROSELÂNDIA (AZUL) - LINHA 506</option><option value="293">ROUXINÓIS - Executivo - LINHA 293</option><option value="593">ROUXINÓIS - Executivo - LINHA 593</option><option value="403">SANTA CARMÉLIA - INT. - LINHA 403</option><option value="402">SANTA CARMÉLIA- SHOPPING - LINHA 402</option><option value="308">SANTA EMÍLIA (AZUL) - LINHA 308</option><option value="123">SANTA FELICIDADE (AZUL) - LINHA 123</option><option value="224">SANTA LUZIA - NASSER - INT. - LINHA 224</option><option value="240">SANTA LUZIA - NOTURNO - LINHA 240</option><option value="225">SANTA LUZIA- INT. - LINHA 225</option><option value="411">SANTA MÔNICA (AZUL) - LINHA 411</option><option value="405">SANTO AMARO - LINHA 405</option><option value="307">SÃO CONRADO (AZUL) - LINHA 307</option><option value="210">SÃO JULIÃO (AZUL) - LINHA 210</option><option value="310">SERRA AZUL/OURO VERDE (AZUL) - LINHA 310</option><option value="215">SHOPPING DOS IPÊS - LINHA 215</option><option value="299">STA LUZIA/STO AMARO - TURNO - LINHA 299</option><option value="124">T. Guaicurus / Enersul - LINHA 124</option><option value="64">T.Guaicurus/T.Morenao/Shopping Norte Sul Plaza - LINHA 064</option><option value="427">Tamandaré/Parque Industrial - LINHA 427</option><option value="207">TAQUARAL BOSQUE (AZUL) - LINHA 207</option><option value="312">TARUMA - AERO RANCHO - LINHA 312</option><option value="313">TARUMÃ / BANDEIRANTES - LINHA 313</option><option value="391">TARUMÃ/PRAÇA(EXECUTIVA) - LINHA 391</option><option value="326">TAVEIRÓPOLIS- UNIAO - LINHA 326</option><option value="51">TERMINAL BANDEIRANTES/SHOPPING - LINHA 051</option><option value="65">TERMINAL GUAICURUS - PRAÇA ARY COELHO - LINHA 065</option><option value="678">teste - LINHA 678</option><option value="567">teste - LINHA 567</option><option value="888">Testes dos Sistema de Bilhetagem - LINHA 888</option><option value="227">TIA EVA - SARAIVA - LINHA 227</option><option value="514">TIRADENTES - LINHA 514</option><option value="546">TURNO - BURITI /AERO RANCHO - LINHA 546</option><option value="545">TURNO I - LINHA 545</option><option value="513">TV. NICOMEDES - LINHA 513</option><option value="233">TVE - LINHA 233</option><option value="222">UCDB - GAL. OSÓRIO - LINHA 222</option><option value="221">UCDB - INT. - LINHA 221</option><option value="301">UNIÃO- OLIVEIRA - LINHA 301</option><option value="106">UNIVERSITÁRIA II (AZUL) - LINHA 106</option><option value="592">UNIVERSITÁRIA II/SHOPPING - LINHA 592</option><option value="109">VESPASIANO MARTINS (AZUL) - LINHA 109</option><option value="211">VIDA NOVA (AZUL) - LINHA 211</option><option value="518">VIVENDA DO PARQUE-SHOPPING - LINHA 518</option><option value="235">VSF - LINHA 235</option><option value="492">ZE PEREIRA - SHOPPING - LINHA 492</option><option value="406">ZÉ PEREIRA (AZUL) - LINHA 406</option> </select> </strong></font><font size="1" face="Verdana, Arial, Helvetica, sans-serif"><strong>&nbsp;ou &nbsp;o N&uacute;mero da Linha: <select name='IdCodigoLinha' class='combo' onKeyPress="autoTab(this, event)"> <option value="0" selected>-- N&ordm; da Linha --</option><option value="15">015</option><option value="50">050</option><option value="51">051</option><option value="52">052</option><option value="53">053</option><option value="61">061</option><option value="62">062</option><option value="63">063</option><option value="64">064</option><option value="65">065</option><option value="70">070</option><option value="71">071</option><option value="72">072</option><option value="73">073</option><option value="75">075</option><option value="76">076</option><option value="80">080</option><option value="81">081</option><option value="82">082</option><option value="83">083</option><option value="84">084</option><option value="85">085</option><option value="86">086</option><option value="87">087</option><option value="88">088</option><option value="89">089</option><option value="100">100</option><option value="101">101</option><option value="102">102</option><option value="103">103</option><option value="104">104</option><option value="105">105</option><option value="106">106</option><option value="107">107</option><option value="108">108</option><option value="109">109</option><option value="110">110</option><option value="111">111</option><option value="112">112</option><option value="113">113</option><option value="114">114</option><option value="115">115</option><option value="116">116</option><option value="117">117</option><option value="118">118</option><option value="119">119</option><option value="120">120</option><option value="121">121</option><option value="122">122</option><option value="123">123</option><option value="124">124</option><option value="126">126</option><option value="127">127</option><option value="129">129</option><option value="130">130</option><option value="131">131</option><option value="145">145</option><option value="146">146</option><option value="147">147</option><option value="190">190</option><option value="191">191</option><option value="197">197</option><option value="198">198</option><option value="199">199</option><option value="201">201</option><option value="202">202</option><option value="203">203</option><option value="204">204</option><option value="205">205</option><option value="206">206</option><option value="207">207</option><option value="208">208</option><option value="209">209</option><option value="210">210</option><option value="211">211</option><option value="212">212</option><option value="213">213</option><option value="214">214</option><option value="215">215</option><option value="216">216</option><option value="217">217</option><option value="218">218</option><option value="219">219</option><option value="220">220</option><option value="221">221</option><option value="222">222</option><option value="223">223</option><option value="224">224</option><option value="225">225</option><option value="226">226</option><option value="227">227</option><option value="228">228</option><option value="229">229</option><option value="230">230</option><option value="231">231</option><option value="232">232</option><option value="233">233</option><option value="234">234</option><option value="235">235</option><option value="236">236</option><option value="237">237</option><option value="238">238</option><option value="239">239</option><option value="240">240</option><option value="241">241</option><option value="245">245</option><option value="246">246</option><option value="247">247</option><option value="290">290</option><option value="291">291</option><option value="292">292</option><option value="293">293</option><option value="298">298</option><option value="299">299</option><option value="300">300</option><option value="301">301</option><option value="302">302</option><option value="303">303</option><option value="304">304</option><option value="306">306</option><option value="307">307</option><option value="308">308</option><option value="309">309</option><option value="310">310</option><option value="311">311</option><option value="312">312</option><option value="313">313</option><option value="314">314</option><option value="315">315</option><option value="317">317</option><option value="318">318</option><option value="319">319</option><option value="320">320</option><option value="323">323</option><option value="326">326</option><option value="327">327</option><option value="328">328</option><option value="329">329</option><option value="345">345</option><option value="346">346</option><option value="347">347</option><option value="354">354</option><option value="390">390</option><option value="391">391</option><option value="399">399</option><option value="400">400</option><option value="401">401</option><option value="402">402</option><option value="403">403</option><option value="404">404</option><option value="405">405</option><option value="406">406</option><option value="407">407</option><option value="408">408</option><option value="409">409</option><option value="410">410</option><option value="411">411</option><option value="413">413</option><option value="414">414</option><option value="415">415</option><option value="416">416</option><option value="417">417</option><option value="418">418</option><option value="419">419</option><option value="420">420</option><option value="421">421</option><option value="422">422</option><option value="423">423</option><option value="424">424</option><option value="425">425</option><option value="426">426</option><option value="427">427</option><option value="445">445</option><option value="446">446</option><option value="447">447</option><option value="474">474</option><option value="490">490</option><option value="491">491</option><option value="492">492</option><option value="498">498</option><option value="499">499</option><option value="500">500</option><option value="502">502</option><option value="503">503</option><option value="505">505</option><option value="506">506</option><option value="507">507</option><option value="508">508</option><option value="509">509</option><option value="511">511</option><option value="512">512</option><option value="513">513</option><option value="514">514</option><option value="515">515</option><option value="516">516</option><option value="517">517</option><option value="518">518</option><option value="519">519</option><option value="520">520</option><option value="521">521</option><option value="522">522</option><option value="523">523</option><option value="524">524</option><option value="525">525</option><option value="526">526</option><option value="545">545</option><option value="546">546</option><option value="547">547</option><option value="548">548</option><option value="567">567</option><option value="592">592</option><option value="593">593</option><option value="602">602</option><option value="678">678</option><option value="888">888</option><option value="909">909</option><option value="910">910</option><option value="911">911</option><option value="912">912</option><option value="913">913</option><option value="914">914</option><option value="915">915</option> </select> &nbsp;</strong></font><font size="2" face="Verdana, Arial, Helvetica, sans-serif"><strong> </strong></font></td> </tr> <tr> <td align="center"><font size="1" face="Verdana, Arial, Helvetica, sans-serif"><strong>&nbsp;ou a Descri&ccedil;&atilde;o do Logradouro:</strong></font><font size="2" face="Verdana, Arial, Helvetica, sans-serif"><strong> <input name="logradouro" type="text" id="logradouro2" size="70" maxlength="70"> </strong></font></td> </tr> <tr> <td align="center"><font size="1" face="Verdana, Arial, Helvetica, sans-serif"><strong>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ou a Descri&ccedil;&atilde;o do Bairro:</strong></font><font size="2" face="Verdana, Arial, Helvetica, sans-serif"><strong> <input name="bairro" type="text" id="logradouro" size="70" maxlength="70"> </strong></font></td> </tr> <tr> <td><div align="center">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <button type='submit' title='Pesquisar Hor?os e Itiner?os' onClick='ConsistirCampos()' class='buttongeral'><img src='/srcnet/images/pesquisar.gif'><span style='text-decoration:underline;'>P</span>esquisar</button> &nbsp;&nbsp;&nbsp; <button type='reset' title="Cancelar" accesskey="c" class="buttongeral"> <img src="/srcnet/images/cancelar.gif"><span style="text-decoration:underline;">R</span>edefinir</button> </div> </td> </tr> <tr> <!--<td align="center"><strong><a href="http://hiperrotas.assetur.com.br/Hiperrotas/Hiperrotas.html">Clique aqui e veja o mapa de rotas das linhas.</a></strong></td>--> </tr> </table> </td> </tr> </table></td> </tr> </table> </form> <table width='770' border="0" align="center"> <tr> <td align="center"><table width='500' height='27' border='0' align='center'><tr><td align='center'><img src='/srcnet/images/mapaslinhas/421.jpg'></td></tr></table><table align='center' width='90%'><tr><td colspan='2'><table width='100%' border='1' cellspacing='0' bordercolor='999999' bgcolor='#006fb0'><tr> <td align='left' class='tittab_maior'> LINHA: JD. CARIOCA - LINHA: 421 - TIPO: <img src='/srcnet/images/onibus_azul_f.gif' onClick="popupLinha('tiposlinhas.html','Linhas','width=600,height=230')" alt='S&atilde;o as linhas que fazem o sentido Bairro X Terminal e vice versa , tem seu ponto final nos terminais.'><br>EMPRESA: CAMPO GRANDE <br> <center>Tabela A </td></tr></td></table></td></tr><td valign='top'><table align='center' width='100%' border='1' cellpadding='0' cellspacing='0' bordercolor='#E9E9E9'><tr><td class='fontstatususuazul' align='left'><font face='Verdana'><strong>Sentido: Bairro / Terminal </b></font></td></tr><tr><td align='left' colspan='4' class='fontintinerario'><strong><font color='#000000'>01 - </font></strong>Avenida 07</td></tr><tr><td align='left' colspan='4' class='fontintinerario'><strong><font color='#000000'>02 - </font></strong>Rua Nara Leão</td></tr><tr><td align='left' colspan='4' class='fontintinerario'><strong><font color='#000000'>03 - </font></strong>Avenida 07</td></tr><tr><td align='left' colspan='4' class='fontintinerario'><strong><font color='#000000'>04 - </font></strong>Avenida Principal 02</td></tr><tr><td align='left' colspan='4' class='fontintinerario'><strong><font color='#000000'>05 - </font></strong>Rua 37</td></tr><tr><td align='left' colspan='4' class='fontintinerario'><strong><font color='#000000'>06 - </font></strong>Rua 22</td></tr><tr><td align='left' colspan='4' class='fontintinerario'><strong><font color='#000000'>07 - </font></strong>Rua 28</td></tr><tr><td align='left' colspan='4' class='fontintinerario'><strong><font color='#000000'>08 - </font></strong>Rua 21</td></tr><tr><td align='left' colspan='4' class='fontintinerario'><strong><font color='#000000'>09 - </font></strong>Rua 26</td></tr><tr><td align='left' colspan='4' class='fontintinerario'><strong><font color='#000000'>10 - </font></strong>Rua 59</td></tr><tr><td align='left' colspan='4' class='fontintinerario'><strong><font color='#000000'>11 - </font></strong>Avenida 09</td></tr><tr><td align='left' colspan='4' class='fontintinerario'><strong><font color='#000000'>12 - </font></strong>Rua Emília Teodora de Souza</td></tr><tr><td align='left' colspan='4' class='fontintinerario'><strong><font color='#000000'>13 - </font></strong>Rua Nilo Javari Barem</td></tr><tr><td align='left' colspan='4' class='fontintinerario'><strong><font color='#000000'>14 - </font></strong>Avenida Duque de Caxias</td></tr><tr><td align='left' colspan='4' class='fontintinerario'><strong><font color='#000000'>15 - </font></strong>Avenida Murilo Rolim Júnior</td></tr><tr><td align='left' colspan='4' class='fontintinerario'><strong><font color='#000000'>16 - </font></strong>Rua das Açucenas</td></tr><tr><td align='left' colspan='4' class='fontintinerario'><strong><font color='#000000'>17 - </font></strong>Rua Goiânia</td></tr><tr><td align='left' colspan='4' class='fontintinerario'><strong><font color='#000000'>18 - </font></strong>Rua Brasília</td></tr><tr><td align='left' colspan='4' class='fontintinerario'><strong><font color='#000000'>19 - </font></strong>Avenida Júlio de Castilho</td></tr><tr><td align='left' colspan='4' class='fontintinerario'><strong><font color='#000000'>20 - </font></strong>Ponto Int. Terminal Julio de Castilho</td></tr></table></td><td valign='top'><table align='center' width='100%' border='1' cellpadding='0' cellspacing='0' bordercolor='#E9E9E9'><tr><td align='left' class='fontstatususuazul'><font face='Verdana'><strong>Sentido: Terminal / Bairro </b></font></td></tr><tr><td align='left' colspan='4' class='fontintinerario'><strong><font color='#000000'>01 - </font></strong>Avenida Júlio de Castilho</td></tr><tr><td align='left' colspan='4' class='fontintinerario'><strong><font color='#000000'>02 - </font></strong>Rua Brasília</td></tr><tr><td align='left' colspan='4' class='fontintinerario'><strong><font color='#000000'>03 - </font></strong>Rua Goiânia</td></tr><tr><td align='left' colspan='4' class='fontintinerario'><strong><font color='#000000'>04 - </font></strong>Rua Açucena</td></tr><tr><td align='left' colspan='4' class='fontintinerario'><strong><font color='#000000'>05 - </font></strong>Avenida Murilo Rolim Júnior</td></tr><tr><td align='left' colspan='4' class='fontintinerario'><strong><font color='#000000'>06 - </font></strong>Avenida Duque de Caxias</td></tr><tr><td align='left' colspan='4' class='fontintinerario'><strong><font color='#000000'>07 - </font></strong>Rua Nilo Javari Barem</td></tr><tr><td align='left' colspan='4' class='fontintinerario'><strong><font color='#000000'>08 - </font></strong>Rua Emília Teodora de Souza</td></tr><tr><td align='left' colspan='4' class='fontintinerario'><strong><font color='#000000'>09 - </font></strong>Avenida 9</td></tr><tr><td align='left' colspan='4' class='fontintinerario'><strong><font color='#000000'>10 - </font></strong>Avenida 3</td></tr><tr><td align='left' colspan='4' class='fontintinerario'><strong><font color='#000000'>11 - </font></strong>Rua 76</td></tr><tr><td align='left' colspan='4' class='fontintinerario'><strong><font color='#000000'>12 - </font></strong>Avenida 2</td></tr><tr><td align='left' colspan='4' class='fontintinerario'><strong><font color='#000000'>13 - </font></strong>Avenida 7</td></tr></table></td></tr></table></td></table><br><table align='center' width='770' border='0'></td></tr><tr><td class='fontlinha' align='left' colspan='5'>Linha: JD. CARIOCA</td><td class='fontstatususuazul' align='right' colspan='2'><font face='Verdana'><strong> Plano Funcional: Segunda a Sexta </b></font></td></tr></table><table align='center' width='770'><tr bgcolor='#007AC7'><td align='center' class='tittab'>Bairro-Saída </td><td align='center' class='tittab'>Terminal Julio de Castilho </td><td align='center' class='tittab'>Terminal Julio de Castilho </td><td align='center' class='tittab'>Bairro-Chegada </td><td align='center' class='tittab'> &nbsp;&nbsp;&nbsp;&nbsp;</td><td align='center' class='tittab'> &nbsp;&nbsp;&nbsp;&nbsp;</td><td align='center' class='tittab'> &nbsp;&nbsp;&nbsp;&nbsp;</td><td align='center' class='tittab'> &nbsp;&nbsp;&nbsp;&nbsp;</td></tr><tr bgcolor='#D6E7EF'><td width='15%' align='center' class='fonthorarioazul'>0500</td><td width='15%' align='center' class='fonthorarioazul'>0522</td><td width='15%' align='center' class='fonthorarioazul'>0527 </td><td width='15%' align='center' class='fonthorarioazul'>0550</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#99CCFF'><td width='15%' align='center' class='fonthorarioazul'>05:28</td><td width='15%' align='center' class='fonthorarioazul'>05:51</td><td width='15%' align='center' class='fonthorarioazul'>05:56 </td><td width='15%' align='center' class='fonthorarioazul'>06:20</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#D6E7EF'><td width='15%' align='center' class='fonthorarioazul'>0550</td><td width='15%' align='center' class='fonthorarioazul'>0615</td><td width='15%' align='center' class='fonthorarioazul'>0617 </td><td width='15%' align='center' class='fonthorarioazul'>0640</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#99CCFF'><td width='15%' align='center' class='fonthorarioazul'>0605</td><td width='15%' align='center' class='fonthorarioazul'>0630</td><td width='15%' align='center' class='fonthorarioazul'>0632 </td><td width='15%' align='center' class='fonthorarioazul'>0655</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#D6E7EF'><td width='15%' align='center' class='fonthorarioazul'>0620</td><td width='15%' align='center' class='fonthorarioazul'>0650</td><td width='15%' align='center' class='fonthorarioazul'>0652 </td><td width='15%' align='center' class='fonthorarioazul'>0715</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#99CCFF'><td width='15%' align='center' class='fonthorarioazul'>0640</td><td width='15%' align='center' class='fonthorarioazul'>0707</td><td width='15%' align='center' class='fonthorarioazul'>0715 </td><td width='15%' align='center' class='fonthorarioazul'>0740</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#D6E7EF'><td width='15%' align='center' class='fonthorarioazul'>0655</td><td width='15%' align='center' class='fonthorarioazul'>0720</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#99CCFF'><td width='15%' align='center' class='fonthorarioazul'>0715</td><td width='15%' align='center' class='fonthorarioazul'>0740</td><td width='15%' align='center' class='fonthorarioazul'>0745 </td><td width='15%' align='center' class='fonthorarioazul'>0810</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#D6E7EF'><td width='15%' align='center' class='fonthorarioazul'>0740</td><td width='15%' align='center' class='fonthorarioazul'>0805</td><td width='15%' align='center' class='fonthorarioazul'>0810 </td><td width='15%' align='center' class='fonthorarioazul'>0835</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#99CCFF'><td width='15%' align='center' class='fonthorarioazul'>0810</td><td width='15%' align='center' class='fonthorarioazul'>0835</td><td width='15%' align='center' class='fonthorarioazul'>0840 </td><td width='15%' align='center' class='fonthorarioazul'>0905</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#D6E7EF'><td width='15%' align='center' class='fonthorarioazul'>0835</td><td width='15%' align='center' class='fonthorarioazul'>0900</td><td width='15%' align='center' class='fonthorarioazul'>0905 </td><td width='15%' align='center' class='fonthorarioazul'>0930</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#99CCFF'><td width='15%' align='center' class='fonthorarioazul'>0905</td><td width='15%' align='center' class='fonthorarioazul'>0930</td><td width='15%' align='center' class='fonthorarioazul'>0935 </td><td width='15%' align='center' class='fonthorarioazul'>1000</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#D6E7EF'><td width='15%' align='center' class='fonthorarioazul'>0930</td><td width='15%' align='center' class='fonthorarioazul'>0955</td><td width='15%' align='center' class='fonthorarioazul'>1000 </td><td width='15%' align='center' class='fonthorarioazul'>1025</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#99CCFF'><td width='15%' align='center' class='fonthorarioazul'>1000</td><td width='15%' align='center' class='fonthorarioazul'>1025</td><td width='15%' align='center' class='fonthorarioazul'>1030 </td><td width='15%' align='center' class='fonthorarioazul'>1055</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#D6E7EF'><td width='15%' align='center' class='fonthorarioazul'>1025</td><td width='15%' align='center' class='fonthorarioazul'>1050</td><td width='15%' align='center' class='fonthorarioazul'>1100 </td><td width='15%' align='center' class='fonthorarioazul'>1125</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#99CCFF'><td width='15%' align='center' class='fonthorarioazul'>1055</td><td width='15%' align='center' class='fonthorarioazul'>1120</td><td width='15%' align='center' class='fonthorarioazul'>1125 </td><td width='15%' align='center' class='fonthorarioazul'>1150</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#D6E7EF'><td width='15%' align='center' class='fonthorarioazul'>1125</td><td width='15%' align='center' class='fonthorarioazul'>1150</td><td width='15%' align='center' class='fonthorarioazul'>1155 </td><td width='15%' align='center' class='fonthorarioazul'>1220</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#99CCFF'><td width='15%' align='center' class='fonthorarioazul'>1150</td><td width='15%' align='center' class='fonthorarioazul'>1215</td><td width='15%' align='center' class='fonthorarioazul'>1220 </td><td width='15%' align='center' class='fonthorarioazul'>1245</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#D6E7EF'><td width='15%' align='center' class='fonthorarioazul'>1220</td><td width='15%' align='center' class='fonthorarioazul'>1245</td><td width='15%' align='center' class='fonthorarioazul'>1250 </td><td width='15%' align='center' class='fonthorarioazul'>1315</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#99CCFF'><td width='15%' align='center' class='fonthorarioazul'>1245</td><td width='15%' align='center' class='fonthorarioazul'>1310</td><td width='15%' align='center' class='fonthorarioazul'>1315 </td><td width='15%' align='center' class='fonthorarioazul'>1340</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#D6E7EF'><td width='15%' align='center' class='fonthorarioazul'>1315</td><td width='15%' align='center' class='fonthorarioazul'>1340</td><td width='15%' align='center' class='fonthorarioazul'>1345 </td><td width='15%' align='center' class='fonthorarioazul'>1407</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#99CCFF'><td width='15%' align='center' class='fonthorarioazul'>1340</td><td width='15%' align='center' class='fonthorarioazul'>1405</td><td width='15%' align='center' class='fonthorarioazul'>1410 </td><td width='15%' align='center' class='fonthorarioazul'>1432</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#D6E7EF'><td width='15%' align='center' class='fonthorarioazul'>1407</td><td width='15%' align='center' class='fonthorarioazul'>1430</td><td width='15%' align='center' class='fonthorarioazul'>1435 </td><td width='15%' align='center' class='fonthorarioazul'>1500</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#99CCFF'><td width='15%' align='center' class='fonthorarioazul'>1432</td><td width='15%' align='center' class='fonthorarioazul'>1455</td><td width='15%' align='center' class='fonthorarioazul'>1500 </td><td width='15%' align='center' class='fonthorarioazul'>1525</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#D6E7EF'><td width='15%' align='center' class='fonthorarioazul'>1500</td><td width='15%' align='center' class='fonthorarioazul'>1525</td><td width='15%' align='center' class='fonthorarioazul'>1530 </td><td width='15%' align='center' class='fonthorarioazul'>1555</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#99CCFF'><td width='15%' align='center' class='fonthorarioazul'>1525</td><td width='15%' align='center' class='fonthorarioazul'>1550</td><td width='15%' align='center' class='fonthorarioazul'>1555 </td><td width='15%' align='center' class='fonthorarioazul'>1620</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#D6E7EF'><td width='15%' align='center' class='fonthorarioazul'>1555</td><td width='15%' align='center' class='fonthorarioazul'>1620</td><td width='15%' align='center' class='fonthorarioazul'>1625 </td><td width='15%' align='center' class='fonthorarioazul'>1650</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#99CCFF'><td width='15%' align='center' class='fonthorarioazul'>1620</td><td width='15%' align='center' class='fonthorarioazul'>1645</td><td width='15%' align='center' class='fonthorarioazul'>1650 </td><td width='15%' align='center' class='fonthorarioazul'>1715</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#D6E7EF'><td width='15%' align='center' class='fonthorarioazul'>1650</td><td width='15%' align='center' class='fonthorarioazul'>1715</td><td width='15%' align='center' class='fonthorarioazul'>1720 </td><td width='15%' align='center' class='fonthorarioazul'>1745</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#99CCFF'><td width='15%' align='center' class='fonthorarioazul'>1715</td><td width='15%' align='center' class='fonthorarioazul'>1740</td><td width='15%' align='center' class='fonthorarioazul'>1745 </td><td width='15%' align='center' class='fonthorarioazul'>1810</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#D6E7EF'><td width='15%' align='center' class='fonthorarioazul'>1745</td><td width='15%' align='center' class='fonthorarioazul'>1810</td><td width='15%' align='center' class='fonthorarioazul'>1815 </td><td width='15%' align='center' class='fonthorarioazul'>1840</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#99CCFF'><td width='15%' align='center' class='fonthorarioazul'>1810</td><td width='15%' align='center' class='fonthorarioazul'>1835</td><td width='15%' align='center' class='fonthorarioazul'>1840 </td><td width='15%' align='center' class='fonthorarioazul'>1907</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#D6E7EF'><td width='15%' align='center' class='fonthorarioazul'>1840</td><td width='15%' align='center' class='fonthorarioazul'>1905</td><td width='15%' align='center' class='fonthorarioazul'>1910 </td><td width='15%' align='center' class='fonthorarioazul'>1935</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#99CCFF'><td width='15%' align='center' class='fonthorarioazul'>1907</td><td width='15%' align='center' class='fonthorarioazul'>1935</td><td width='15%' align='center' class='fonthorarioazul'>1940 </td><td width='15%' align='center' class='fonthorarioazul'>2005</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#D6E7EF'><td width='15%' align='center' class='fonthorarioazul'>1935</td><td width='15%' align='center' class='fonthorarioazul'>2000</td><td width='15%' align='center' class='fonthorarioazul'>2010 </td><td width='15%' align='center' class='fonthorarioazul'>2035</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#99CCFF'><td width='15%' align='center' class='fonthorarioazul'>2005</td><td width='15%' align='center' class='fonthorarioazul'>2030</td><td width='15%' align='center' class='fonthorarioazul'>2040 </td><td width='15%' align='center' class='fonthorarioazul'>2105</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#D6E7EF'><td width='15%' align='center' class='fonthorarioazul'>2035</td><td width='15%' align='center' class='fonthorarioazul'>2100</td><td width='15%' align='center' class='fonthorarioazul'>2110 </td><td width='15%' align='center' class='fonthorarioazul'>2135</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#99CCFF'><td width='15%' align='center' class='fonthorarioazul'>2105</td><td width='15%' align='center' class='fonthorarioazul'>2130</td><td width='15%' align='center' class='fonthorarioazul'>2140 </td><td width='15%' align='center' class='fonthorarioazul'>2205</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#D6E7EF'><td width='15%' align='center' class='fonthorarioazul'>2135</td><td width='15%' align='center' class='fonthorarioazul'>2200</td><td width='15%' align='center' class='fonthorarioazul'>2210 </td><td width='15%' align='center' class='fonthorarioazul'>2235</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#99CCFF'><td width='15%' align='center' class='fonthorarioazul'>2205</td><td width='15%' align='center' class='fonthorarioazul'>2230</td><td width='15%' align='center' class='fonthorarioazul'>2240 </td><td width='15%' align='center' class='fonthorarioazul'>2305</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#D6E7EF'><td width='15%' align='center' class='fonthorarioazul'>2235</td><td width='15%' align='center' class='fonthorarioazul'>2300</td><td width='15%' align='center' class='fonthorarioazul'>2310 </td><td width='15%' align='center' class='fonthorarioazul'>2335</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#99CCFF'><td width='15%' align='center' class='fonthorarioazul'>2305</td><td width='15%' align='center' class='fonthorarioazul'>2330</td><td width='15%' align='center' class='fonthorarioazul'>2335 </td><td width='15%' align='center' class='fonthorarioazul'>2358</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#D6E7EF'><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'>0015 </td><td width='15%' align='center' class='fonthorarioazul'>0036</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td></table><br><table align='center' width='770' border='0'></td></tr><tr><td class='fontlinha' align='left' colspan='5'>Linha: JD. CARIOCA</td><td class='fontstatususuazul' align='right' colspan='2'><font face='Verdana'><strong> Plano Funcional: Sábado </b></font></td></tr></table><table align='center' width='770'><tr bgcolor='#007AC7'><td align='center' class='tittab'>Bairro-Saída </td><td align='center' class='tittab'>Terminal Julio de Castilho </td><td align='center' class='tittab'>Terminal Julio de Castilho </td><td align='center' class='tittab'>Bairro-Chegada </td><td align='center' class='tittab'> &nbsp;&nbsp;&nbsp;&nbsp;</td><td align='center' class='tittab'> &nbsp;&nbsp;&nbsp;&nbsp;</td><td align='center' class='tittab'> &nbsp;&nbsp;&nbsp;&nbsp;</td><td align='center' class='tittab'> &nbsp;&nbsp;&nbsp;&nbsp;</td></tr><tr bgcolor='#99CCFF'><td width='15%' align='center' class='fonthorarioazul'>05:03</td><td width='15%' align='center' class='fonthorarioazul'>05:26</td><td width='15%' align='center' class='fonthorarioazul'>05:31 </td><td width='15%' align='center' class='fonthorarioazul'>05:54</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#D6E7EF'><td width='15%' align='center' class='fonthorarioazul'>05:28</td><td width='15%' align='center' class='fonthorarioazul'>05:51</td><td width='15%' align='center' class='fonthorarioazul'>05:56 </td><td width='15%' align='center' class='fonthorarioazul'>06:20</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#99CCFF'><td width='15%' align='center' class='fonthorarioazul'>05:54</td><td width='15%' align='center' class='fonthorarioazul'>06:19</td><td width='15%' align='center' class='fonthorarioazul'>06:21 </td><td width='15%' align='center' class='fonthorarioazul'>06:46</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#D6E7EF'><td width='15%' align='center' class='fonthorarioazul'>06:20</td><td width='15%' align='center' class='fonthorarioazul'>06:45</td><td width='15%' align='center' class='fonthorarioazul'>06:47 </td><td width='15%' align='center' class='fonthorarioazul'>07:12</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#99CCFF'><td width='15%' align='center' class='fonthorarioazul'>06:46</td><td width='15%' align='center' class='fonthorarioazul'>07:11</td><td width='15%' align='center' class='fonthorarioazul'>07:16 </td><td width='15%' align='center' class='fonthorarioazul'>07:40</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#D6E7EF'><td width='15%' align='center' class='fonthorarioazul'>0712</td><td width='15%' align='center' class='fonthorarioazul'>0740</td><td width='15%' align='center' class='fonthorarioazul'>0745 </td><td width='15%' align='center' class='fonthorarioazul'>0810</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#99CCFF'><td width='15%' align='center' class='fonthorarioazul'>07:40</td><td width='15%' align='center' class='fonthorarioazul'>08:05</td><td width='15%' align='center' class='fonthorarioazul'>08:10 </td><td width='15%' align='center' class='fonthorarioazul'>08:35</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#D6E7EF'><td width='15%' align='center' class='fonthorarioazul'>0810</td><td width='15%' align='center' class='fonthorarioazul'>0835</td><td width='15%' align='center' class='fonthorarioazul'>0840 </td><td width='15%' align='center' class='fonthorarioazul'>0905</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#99CCFF'><td width='15%' align='center' class='fonthorarioazul'>0835</td><td width='15%' align='center' class='fonthorarioazul'>0900</td><td width='15%' align='center' class='fonthorarioazul'>0905 </td><td width='15%' align='center' class='fonthorarioazul'>0930</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#D6E7EF'><td width='15%' align='center' class='fonthorarioazul'>0905</td><td width='15%' align='center' class='fonthorarioazul'>0930</td><td width='15%' align='center' class='fonthorarioazul'>0935 </td><td width='15%' align='center' class='fonthorarioazul'>1000</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#99CCFF'><td width='15%' align='center' class='fonthorarioazul'>0930</td><td width='15%' align='center' class='fonthorarioazul'>0955</td><td width='15%' align='center' class='fonthorarioazul'>1000 </td><td width='15%' align='center' class='fonthorarioazul'>1025</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#D6E7EF'><td width='15%' align='center' class='fonthorarioazul'>1000</td><td width='15%' align='center' class='fonthorarioazul'>1025</td><td width='15%' align='center' class='fonthorarioazul'>1030 </td><td width='15%' align='center' class='fonthorarioazul'>1055</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#99CCFF'><td width='15%' align='center' class='fonthorarioazul'>1025</td><td width='15%' align='center' class='fonthorarioazul'>1050</td><td width='15%' align='center' class='fonthorarioazul'>1100 </td><td width='15%' align='center' class='fonthorarioazul'>1124</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#D6E7EF'><td width='15%' align='center' class='fonthorarioazul'>1055</td><td width='15%' align='center' class='fonthorarioazul'>1120</td><td width='15%' align='center' class='fonthorarioazul'>1125 </td><td width='15%' align='center' class='fonthorarioazul'>1150</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#99CCFF'><td width='15%' align='center' class='fonthorarioazul'>1124</td><td width='15%' align='center' class='fonthorarioazul'>1148</td><td width='15%' align='center' class='fonthorarioazul'>1150 </td><td width='15%' align='center' class='fonthorarioazul'>1215</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#D6E7EF'><td width='15%' align='center' class='fonthorarioazul'>1150</td><td width='15%' align='center' class='fonthorarioazul'>1215</td><td width='15%' align='center' class='fonthorarioazul'>1217 </td><td width='15%' align='center' class='fonthorarioazul'>1242</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#99CCFF'><td width='15%' align='center' class='fonthorarioazul'>1215</td><td width='15%' align='center' class='fonthorarioazul'>1240</td><td width='15%' align='center' class='fonthorarioazul'>1245 </td><td width='15%' align='center' class='fonthorarioazul'>1310</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#D6E7EF'><td width='15%' align='center' class='fonthorarioazul'>1242</td><td width='15%' align='center' class='fonthorarioazul'>1305</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#99CCFF'><td width='15%' align='center' class='fonthorarioazul'>1310</td><td width='15%' align='center' class='fonthorarioazul'>1335</td><td width='15%' align='center' class='fonthorarioazul'>1340 </td><td width='15%' align='center' class='fonthorarioazul'>1405</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#D6E7EF'><td width='15%' align='center' class='fonthorarioazul'>1405</td><td width='15%' align='center' class='fonthorarioazul'>1430</td><td width='15%' align='center' class='fonthorarioazul'>1435 </td><td width='15%' align='center' class='fonthorarioazul'>1458</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#99CCFF'><td width='15%' align='center' class='fonthorarioazul'>1458</td><td width='15%' align='center' class='fonthorarioazul'>1522</td><td width='15%' align='center' class='fonthorarioazul'>1527 </td><td width='15%' align='center' class='fonthorarioazul'>1550</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#D6E7EF'><td width='15%' align='center' class='fonthorarioazul'>1550</td><td width='15%' align='center' class='fonthorarioazul'>1615</td><td width='15%' align='center' class='fonthorarioazul'>1620 </td><td width='15%' align='center' class='fonthorarioazul'>1645</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#99CCFF'><td width='15%' align='center' class='fonthorarioazul'>1645</td><td width='15%' align='center' class='fonthorarioazul'>1710</td><td width='15%' align='center' class='fonthorarioazul'>1715 </td><td width='15%' align='center' class='fonthorarioazul'>1740</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#D6E7EF'><td width='15%' align='center' class='fonthorarioazul'>1740</td><td width='15%' align='center' class='fonthorarioazul'>1805</td><td width='15%' align='center' class='fonthorarioazul'>1810 </td><td width='15%' align='center' class='fonthorarioazul'>1835</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#99CCFF'><td width='15%' align='center' class='fonthorarioazul'>1835</td><td width='15%' align='center' class='fonthorarioazul'>1900</td><td width='15%' align='center' class='fonthorarioazul'>1905 </td><td width='15%' align='center' class='fonthorarioazul'>1930</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#D6E7EF'><td width='15%' align='center' class='fonthorarioazul'>1930</td><td width='15%' align='center' class='fonthorarioazul'>1955</td><td width='15%' align='center' class='fonthorarioazul'>2000 </td><td width='15%' align='center' class='fonthorarioazul'>2025</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#99CCFF'><td width='15%' align='center' class='fonthorarioazul'>2025</td><td width='15%' align='center' class='fonthorarioazul'>2050</td><td width='15%' align='center' class='fonthorarioazul'>2055 </td><td width='15%' align='center' class='fonthorarioazul'>2120</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#D6E7EF'><td width='15%' align='center' class='fonthorarioazul'>2120</td><td width='15%' align='center' class='fonthorarioazul'>2145</td><td width='15%' align='center' class='fonthorarioazul'>2150 </td><td width='15%' align='center' class='fonthorarioazul'>2213</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#99CCFF'><td width='15%' align='center' class='fonthorarioazul'>2213</td><td width='15%' align='center' class='fonthorarioazul'>2237</td><td width='15%' align='center' class='fonthorarioazul'>2242 </td><td width='15%' align='center' class='fonthorarioazul'>2305</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#D6E7EF'><td width='15%' align='center' class='fonthorarioazul'>2305</td><td width='15%' align='center' class='fonthorarioazul'>2329</td><td width='15%' align='center' class='fonthorarioazul'>2334 </td><td width='15%' align='center' class='fonthorarioazul'>2354</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#99CCFF'><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'>0013 </td><td width='15%' align='center' class='fonthorarioazul'>0035</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td></table><br><table align='center' width='770' border='0'></td></tr><tr><td class='fontlinha' align='left' colspan='5'>Linha: JD. CARIOCA</td><td class='fontstatususuazul' align='right' colspan='2'><font face='Verdana'><strong> Plano Funcional: Domingos e Feriados </b></font></td></tr></table><table align='center' width='770'><tr bgcolor='#007AC7'><td align='center' class='tittab'>Bairro-Saída </td><td align='center' class='tittab'>Terminal Julio de Castilho </td><td align='center' class='tittab'>Terminal Julio de Castilho </td><td align='center' class='tittab'>Bairro-Chegada </td><td align='center' class='tittab'> &nbsp;&nbsp;&nbsp;&nbsp;</td><td align='center' class='tittab'> &nbsp;&nbsp;&nbsp;&nbsp;</td><td align='center' class='tittab'> &nbsp;&nbsp;&nbsp;&nbsp;</td><td align='center' class='tittab'> &nbsp;&nbsp;&nbsp;&nbsp;</td></tr><tr bgcolor='#D6E7EF'><td width='15%' align='center' class='fonthorarioazul'>05:05</td><td width='15%' align='center' class='fonthorarioazul'>05:28</td><td width='15%' align='center' class='fonthorarioazul'>05:33 </td><td width='15%' align='center' class='fonthorarioazul'>05:56</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#99CCFF'><td width='15%' align='center' class='fonthorarioazul'>05:56</td><td width='15%' align='center' class='fonthorarioazul'>06:18</td><td width='15%' align='center' class='fonthorarioazul'>06:23 </td><td width='15%' align='center' class='fonthorarioazul'>06:45</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#D6E7EF'><td width='15%' align='center' class='fonthorarioazul'>06:45</td><td width='15%' align='center' class='fonthorarioazul'>07:08</td><td width='15%' align='center' class='fonthorarioazul'>07:15 </td><td width='15%' align='center' class='fonthorarioazul'>07:39</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#99CCFF'><td width='15%' align='center' class='fonthorarioazul'>07:39</td><td width='15%' align='center' class='fonthorarioazul'>08:03</td><td width='15%' align='center' class='fonthorarioazul'>08:10 </td><td width='15%' align='center' class='fonthorarioazul'>08:34</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#D6E7EF'><td width='15%' align='center' class='fonthorarioazul'>08:34</td><td width='15%' align='center' class='fonthorarioazul'>08:58</td><td width='15%' align='center' class='fonthorarioazul'>09:05 </td><td width='15%' align='center' class='fonthorarioazul'>09:29</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#99CCFF'><td width='15%' align='center' class='fonthorarioazul'>09:29</td><td width='15%' align='center' class='fonthorarioazul'>09:53</td><td width='15%' align='center' class='fonthorarioazul'>10:00 </td><td width='15%' align='center' class='fonthorarioazul'>10:24</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#D6E7EF'><td width='15%' align='center' class='fonthorarioazul'>10:24</td><td width='15%' align='center' class='fonthorarioazul'>10:48</td><td width='15%' align='center' class='fonthorarioazul'>10:55 </td><td width='15%' align='center' class='fonthorarioazul'>11:19</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#99CCFF'><td width='15%' align='center' class='fonthorarioazul'>11:19</td><td width='15%' align='center' class='fonthorarioazul'>11:43</td><td width='15%' align='center' class='fonthorarioazul'>11:50 </td><td width='15%' align='center' class='fonthorarioazul'>12:14</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#D6E7EF'><td width='15%' align='center' class='fonthorarioazul'>12:14</td><td width='15%' align='center' class='fonthorarioazul'>12:38</td><td width='15%' align='center' class='fonthorarioazul'>12:45 </td><td width='15%' align='center' class='fonthorarioazul'>13:09</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#99CCFF'><td width='15%' align='center' class='fonthorarioazul'>13:09</td><td width='15%' align='center' class='fonthorarioazul'>13:33</td><td width='15%' align='center' class='fonthorarioazul'>13:40 </td><td width='15%' align='center' class='fonthorarioazul'>14:02</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#D6E7EF'><td width='15%' align='center' class='fonthorarioazul'>14:02</td><td width='15%' align='center' class='fonthorarioazul'>14:25</td><td width='15%' align='center' class='fonthorarioazul'>14:30 </td><td width='15%' align='center' class='fonthorarioazul'>14:54</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#99CCFF'><td width='15%' align='center' class='fonthorarioazul'>14:54</td><td width='15%' align='center' class='fonthorarioazul'>15:18</td><td width='15%' align='center' class='fonthorarioazul'>15:25 </td><td width='15%' align='center' class='fonthorarioazul'>15:49</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#D6E7EF'><td width='15%' align='center' class='fonthorarioazul'>15:49</td><td width='15%' align='center' class='fonthorarioazul'>16:13</td><td width='15%' align='center' class='fonthorarioazul'>16:20 </td><td width='15%' align='center' class='fonthorarioazul'>16:44</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#99CCFF'><td width='15%' align='center' class='fonthorarioazul'>16:44</td><td width='15%' align='center' class='fonthorarioazul'>17:08</td><td width='15%' align='center' class='fonthorarioazul'>17:15 </td><td width='15%' align='center' class='fonthorarioazul'>17:39</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#D6E7EF'><td width='15%' align='center' class='fonthorarioazul'>17:39</td><td width='15%' align='center' class='fonthorarioazul'>18:03</td><td width='15%' align='center' class='fonthorarioazul'>18:10 </td><td width='15%' align='center' class='fonthorarioazul'>18:34</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#99CCFF'><td width='15%' align='center' class='fonthorarioazul'>18:34</td><td width='15%' align='center' class='fonthorarioazul'>18:58</td><td width='15%' align='center' class='fonthorarioazul'>19:05 </td><td width='15%' align='center' class='fonthorarioazul'>19:29</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#D6E7EF'><td width='15%' align='center' class='fonthorarioazul'>19:29</td><td width='15%' align='center' class='fonthorarioazul'>19:53</td><td width='15%' align='center' class='fonthorarioazul'>20:00 </td><td width='15%' align='center' class='fonthorarioazul'>20:24</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#99CCFF'><td width='15%' align='center' class='fonthorarioazul'>20:24</td><td width='15%' align='center' class='fonthorarioazul'>20:48</td><td width='15%' align='center' class='fonthorarioazul'>20:55 </td><td width='15%' align='center' class='fonthorarioazul'>21:19</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#D6E7EF'><td width='15%' align='center' class='fonthorarioazul'>21:19</td><td width='15%' align='center' class='fonthorarioazul'>21:43</td><td width='15%' align='center' class='fonthorarioazul'>21:50 </td><td width='15%' align='center' class='fonthorarioazul'>22:12</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#99CCFF'><td width='15%' align='center' class='fonthorarioazul'>22:12</td><td width='15%' align='center' class='fonthorarioazul'>22:35</td><td width='15%' align='center' class='fonthorarioazul'>22:40 </td><td width='15%' align='center' class='fonthorarioazul'>23:04</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#D6E7EF'><td width='15%' align='center' class='fonthorarioazul'>23:04</td><td width='15%' align='center' class='fonthorarioazul'>23:27</td><td width='15%' align='center' class='fonthorarioazul'>23:34 </td><td width='15%' align='center' class='fonthorarioazul'>23:54</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td><tr bgcolor='#99CCFF'><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'>00:13 </td><td width='15%' align='center' class='fonthorarioazul'>00:35</td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='fonthorarioazul'> </td><td width='15%' align='center' class='dicaescura'>A</td></table></td> </tr> </table> </body> <script Language="JavaScript"><!-- function ConsistirCampos() { campo = document.formpsq.idcartao; if (campo.value == "") { alert('Campo Cdigo vazio ou inv?do! Digite um nmero para pesquisa'); campo.focus(); return; } document.formpsq.submit(); } --></script> </html>
olimpotec/busaoapp
web/data/421.html
HTML
bsd-2-clause
85,952
class Xonsh < Formula include Language::Python::Virtualenv desc "Python-ish, BASHwards-compatible shell language and command prompt" homepage "https://xon.sh/" url "https://github.com/xonsh/xonsh/archive/0.7.7.tar.gz" sha256 "8f63ed670439d7b065a3cb90c29ad89e3bf4a7553f4a8b7b1d0968a85a3d922e" head "https://github.com/xonsh/xonsh.git" bottle do cellar :any_skip_relocation sha256 "55c1800cfb7f4762b88c565f2aa151d153ecced6577db9a22d5ca5b549524543" => :mojave sha256 "30d3ffd6752f3624ce8a6daad76fb7db7d33e6187a15c421d079986f83b7d3f4" => :high_sierra sha256 "678dd291c1572271e91a64d3dfbd1293d5d43df658d6315d5233de57078c554c" => :sierra sha256 "c8665360781b8d4c3145af2376c05e57f1bbc80363d063c61f194a4aef821c68" => :el_capitan end depends_on "python" # Resources based on `pip3 install xonsh[ptk,pygments,proctitle]` # See https://xon.sh/osx.html#dependencies resource "prompt_toolkit" do url "https://files.pythonhosted.org/packages/77/bf/5d7664605c91db8f39a3e49abb57a3c933731a90b7a58cdcafd4a9bcbe97/prompt_toolkit-2.0.4.tar.gz" sha256 "ff58ce8bb82c11c43416dd3eec7701dcbe8c576e2d7649f1d2b9d21a2fd93808" end resource "Pygments" do url "https://files.pythonhosted.org/packages/71/2a/2e4e77803a8bd6408a2903340ac498cb0a2181811af7c9ec92cb70b0308a/Pygments-2.2.0.tar.gz" sha256 "dbae1046def0efb574852fab9e90209b23f556367b5a320c0bcb871c77c3e8cc" end resource "setproctitle" do url "https://files.pythonhosted.org/packages/5a/0d/dc0d2234aacba6cf1a729964383e3452c52096dc695581248b548786f2b3/setproctitle-1.1.10.tar.gz" sha256 "6283b7a58477dd8478fbb9e76defb37968ee4ba47b05ec1c053cb39638bd7398" end resource "six" do url "https://files.pythonhosted.org/packages/16/d8/bc6316cf98419719bd59c91742194c111b6f2e85abac88e496adefaf7afe/six-1.11.0.tar.gz" sha256 "70e8a77beed4562e7f14fe23a786b54f6296e34344c23bc42f07b15018ff98e9" end resource "wcwidth" do url "https://files.pythonhosted.org/packages/55/11/e4a2bb08bb450fdbd42cc709dd40de4ed2c472cf0ccb9e64af22279c5495/wcwidth-0.1.7.tar.gz" sha256 "3df37372226d6e63e1b1e1eda15c594bca98a22d33a23832a90998faa96bc65e" end def install virtualenv_install_with_resources end test do assert_match "4", shell_output("#{bin}/xonsh -c 2+2") end end
DomT4/homebrew-core
Formula/xonsh.rb
Ruby
bsd-2-clause
2,293
class Shmcat < Formula desc "Tool that dumps shared memory segments (System V and POSIX)" homepage "https://shmcat.sourceforge.io/" url "https://downloads.sourceforge.net/project/shmcat/shmcat-1.9.tar.xz" sha256 "831f1671e737bed31de3721b861f3796461ebf3b05270cf4c938749120ca8e5b" bottle do cellar :any_skip_relocation sha256 "f86090c36d839092913667dcfc924f76c71d318a03434a1e608b3960b1df7807" => :catalina sha256 "e052a4f6b21407c032c1ee5a79fe9b1c08e78b7980c1cd3d6bfbfa8ffe639a58" => :mojave sha256 "ff73e6df8b663b4f382098ce75a9ec4634d4658c5378b3ad122de135e30d44ab" => :high_sierra sha256 "5ee7bcafe69d653421e29b56cf2e48a55874dc1e092e817a83cb446cda4acf01" => :sierra sha256 "1b6ddaf528253df2e2d5b93e97b6f4ade717ff8f3f6bcf829ed7cf9d9e682539" => :el_capitan sha256 "ba5d4d130846537f603b399ea5896daf4125b0d19bd143a130c0b68a4006acee" => :x86_64_linux end def install system "./configure", "--prefix=#{prefix}", "--disable-dependency-tracking", "--disable-ftok", "--disable-nls" system "make", "install" end test do assert_match /#{version}/, shell_output("#{bin}/shmcat --version") end end
LinuxbrewTestBot/homebrew-core
Formula/shmcat.rb
Ruby
bsd-2-clause
1,224
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="csrf-token" content="{{ csrf_token() }}" /> <link rel="stylesheet" href="{{ asset('css/bootstrap.min.css') }}"> <link rel="stylesheet" href="{{ asset('css/mobile.css') }}"> <script type="text/javascript" src="{{ asset('js/jquery-3.3.1.min.js') }}"></script> <script type="text/javascript" src="{{ asset('js/popper.min.js')}}"></script> <script type="text/javascript" src="{{ asset('js/bootstrap.min.js')}}"></script> <title>Self Adjustment</title> <style> .footer { position: fixed; right: 0.3%; bottom: 0%; /*width: 100%;*/ background-color: transparent; color: white; } .leftBtn{ padding: 0rem; font-size: 2.2rem; line-height:inherit; border-radius:.3rem; width: 100px; height: 75px; align-self: center; } .rightBtn{ padding: 0rem; font-size: 2.2rem; line-height: inherit; border-radius:.3rem; left:0; width:100px; height: 75px; align-self: center; } .okay{ padding: 0rem; font-size: 1.4rem; line-height: inherit; border-radius:.3rem; left:0; width:90px; height: 75px; align-self: center; vertical-align: top; } .save{ padding: .5rem; font-size:1.4rem; line-height:1.2; border-radius:.2rem; align-self: left; width:110px; height: 70px; margin-left: 10%; margin-bottom: 0; } .saveAs{ padding: .5rem; font-size:1.4rem; line-height:1.2; border-radius:.2rem; right:0; width:110px; height: 70px; margin-right: 10%; margin-bottom: 0; margin-left: 8%; } .dontSave{ padding: .5rem; font-size:1.4rem; line-height:1.2; border-radius:.2rem; width:110px; height: 70px; margin-right: 10%; margin-bottom: 0; margin-right: 10%; } </style> </head> <body style="background-color: #e8ecf1;"> <div class="container-fluid" style="margin-bottom: 2px"> <div class="row"> <div class="col"> <button type="button" class="btn btn-outline-dark btn-block" style="background-color: white;" data-toggle="modal" data-target="#infoModal"> HA Values </button> </div> <div class="col"> <button id="lvhValues" class="btn btn-outline-dark btn-block" style="background-color: white;"> {{ $listener->listener }} </button> </div> </div> </div> <div class="container-fluid" style="background-color: #e8ecf1"> <!--CRSIPNESS--> <div id="crispness_section" class="container" style="background-color: #f4d03f; padding: 1rem; visibility: hidden;"> <h3 style="display:none" id="h_value" type="integer">0</h3> <div class="row"> <div class="col-12 text-center h3"> CRISPNESS </div> </div> <div class="row" style="height:33%"> <div class= "col-4 text-center"> <button id="h_less" type="button" class="leftBtn"> Less </button> </div> <div class="col-4 text-center"> <button type="button" id="h_okay" class="okay"> Ok </button> </div> <div class="col-4 text-center"> <button id="h_more" type="button" class="rightBtn"> More </button> </div> </div> </div> <!--LOUDNESS--> <div id="loudness_section" class="container" style= "background-color: #6bb9f0; padding:1rem; visibility: hidden;" > <h3 style="display:none" id="v_value" type="integer">0</h3> <div class="row"> <div class="col-12 text-center h3"> LOUDNESS </div> </div> <div class= "row" style="height:33%"> <div class="col-4 text-center"> <button id="v_less" type="button" class="leftBtn"> Less </button> </div> <div class="col-4 text-center"> <button type="button" id="v_okay" class="okay"> Ok </button> </div> <div class="col-4 text-center"> <button id="v_more" type="button" class="rightBtn"> More </button> </div> </div> </div> <!--FULLNESS--> <div id="fullness_section" class="container" style= "background-color: #fabe58; padding:1rem; visibility: hidden;"> <h3 style="display:none" id="l_value" type="integer">0</h3> <div class="row"> <div class="col-12 text-center h3"> FULLNESS </div> </div> <div class="row" style="height:33%"> <div class="col-4 text-center"> <button id="l_less" type="button" class="leftBtn"> Less </button> </div> <div class="col-4 text-center"> <button type="button" id="l_okay" class="okay"> Ok </button> </div> <div class="col-4 text-center"> <button id="l_more" type="button" class="rightBtn"> More </button> </div> </div> </div> <div class="container footer" id="end_buttons" style="display: none;"> <div class="row" > <div class="col-4 text-center" > <button type="button" id="save_button" class="save btn-info"> Save </button> </div> <div class="col-4 text-center" style="align-items:center"> <button type="button" id="save_as_modal_trigger" class="saveAs btn-info" data-toggle="modal" data-target="#saveAsModal"> Save As </button> </div> <div class="col-4 text-center" style="align-items:center"> <button type="button" id="dont_save_button" class="save btn-info" style="display: inline-block;"> Don't Save </button> </div> </div> </div> <div class="container-fluid footer" id="finish_footer" style="margin-top: 0.5rem;"> <div class="row" style="margin-bottom: 0.5rem"> <div class="col-12 text-center"> <button type="button" id="finish_button" class="okay btn-info" style="visibility: hidden; display: inline-block;"> Finish </button> </div> </div> </div> </div> <!--Modal for saving new program--> <div class="modal fade" id="saveAsModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Save New Program</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <label for="modalInput" style="padding-right: 5px">Program name </label> <input id="modalInput" name="programName" type="text" placeholder="Quiet, Noisy, etc." value="{{ $next_name }}"> <p style="color: red" id="modalInputError"></p> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button id="save_as_button" type="button" class="btn btn-primary">Save</button> </div> </div> </div> </div> <!--Modal for viewing hearing aid state--> <div class="modal fade" id="infoModal" tabindex="-1" role="dialog" aria-labelledby="infoModalLabel" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="infoModalLabel">Logout Listener</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" style="float: left;" onclick="location='{{ url("goldilocks/listener/logout") }}'">Logout</button> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </div> </div> </div> <script language="JavaScript"> /** Initialize parameters for two channels **/ var parametersTwoChannels = { left:{ 'targets': [0, 0, 0, 0, 0, 0], 'ltass': [0, 0, 0, 0, 0, 0], 'hearing_loss': [0, 0, 0, 0, 0, 0], 'compression_ratio': [1, 1, 1, 1, 1, 1], 'g50': [0, 0, 0, 0, 0, 0], 'g65': [0, 0, 0, 0, 0, 0], 'g80': [0, 0, 0, 0, 0, 0], 'g50_max': [0, 0, 0, 0, 0, 0], 'knee_low': [45, 45, 45, 45, 45, 45], 'mpo_band': [110, 110, 110, 110, 110, 110], 'attack': [5, 5, 5, 5, 5, 5], 'release': [100, 100, 100, 100, 100, 100], }, right:{ 'targets': [0, 0, 0, 0, 0, 0], 'ltass': [0, 0, 0, 0, 0, 0], 'hearing_loss': [0, 0, 0, 0, 0, 0], 'compression_ratio': [1, 1, 1, 1, 1, 1], 'g50': [0, 0, 0, 0, 0, 0], 'g65': [0, 0, 0, 0, 0, 0], 'g80': [0, 0, 0, 0, 0, 0], 'g50_max': [0, 0, 0, 0, 0, 0], 'knee_low': [45, 45, 45, 45, 45, 45], 'mpo_band': [110, 110, 110, 110, 110, 110], 'attack': [5, 5, 5, 5, 5, 5], 'release': [100, 100, 100, 100, 100, 100], } }; /** Initialize parameters for single channel **/ var parametersSingleChannel = { 'multiplier_l': [0, 0, 0, 0, 0, 0], 'multiplier_h': [0, 0, 0, 0, 0, 0], 'l_min': -40, 'l_max': 40, 'l_step': 1, 'v_min': -40, 'v_max': 40, 'v_step': 3, 'h_min': -40, 'h_max': 40, 'h_step': 1, 'control_via': 0, //0 - CR/G65, 1 - G50/G80 'afc': 1, //1 - on, 0 - off 'sequence_num': 3, 'sequence_order': 0, //0 - V, 1- H 'app_behavior': 1 //0 - one by one, 1 - volume only, 2 - all 3 }; var programId = -1; var programIdStart = -1; /** Need to calculate for right and left channel seperately **/ var channels = ['left', 'right']; /** Pull parameters if they have been passed through **/ if("{{$parameters}}" != ""){ var parameters = JSON.parse("{{$parameters}}".replace(/&quot;/g,'"')); var parametersTwoChannels = parameters.parametersTwoChannels; var parametersSingleChannel = parameters.parameters; console.log("parameters passed through:", parameters); } if("{{$program_id}}" != null && "{{$program_id}}" != ""){ this['programId'] = this['programIdStart'] = '{{$program_id}}'; console.log("program_id passed through", this['programId']); } /* To keep track of adjustment logs */ //store the starting g65 so that we may use it in updating function // index 0 is starting_g65 for left channel, index 1 is starting_g65 for right channel var starting_g65 = [this['parametersTwoChannels']['left']['g65'].slice(), this['parametersTwoChannels']['right']['g65'].slice()]; var l_multipliers = this['parametersSingleChannel']['multiplier_l'].slice(); var h_multipliers = this['parametersSingleChannel']['multiplier_h'].slice(); // index 0 is cr for left channel, index 1 is cr for right channel var cr = [this['parametersTwoChannels']['left']['compression_ratio'].slice(),this['parametersTwoChannels']['right']['compression_ratio'].slice()]; var changeString = ""; var steps = 0; // set up L and H step sizes based on dB // L (fullness) - max lmult (250,500,1000) var l_mul = Math.max(parametersSingleChannel['multiplier_l'][0], parametersSingleChannel['multiplier_l'][1], parametersSingleChannel['multiplier_l'][2]); // H (crispness) - max hmult (2000,4000,8000) var h_mul = Math.max(parametersSingleChannel['multiplier_h'][3], parametersSingleChannel['multiplier_h'][4], parametersSingleChannel['multiplier_h'][5]); /** Set up sequence based on parameters passed through **/ var sequence; //case: sequence if(parametersSingleChannel['app_behavior'] === 0) { if (parametersSingleChannel['sequence_num'] === 3) { if (parametersSingleChannel['sequence_order'] === 0) { //3,V: [V, H, V, L, three] sequence = ['V', 'H', 'V', 'L', 3]; } else { //3,H: [H, V, H, L, three] sequence = ['H', 'V', 'H', 'L', 3]; } } else { if (parametersSingleChannel['sequence_order'] === 0) { //2,V: [V, H, two] sequence = ['V', 'H', 2]; } else { //2,H: [H, V, two] sequence = ['H', 'V', 2]; } } } //case: loudness only else if(parametersSingleChannel['app_behavior'] === 1){ sequence = [1]; } //case: either all three or two, without sequence else{ sequence = [parametersSingleChannel['sequence_num']]; } //load the first panel nextPanel(); /** * Loading this page will transmit the most recent program (decided by researcher). This has the effect that * refreshing the page resets the sequence and starts with the hearing aid in the correct state. */ transmit(); //log that the app has started logButtonPress('started_app'); var start = new Date(); /** Fullness button control **/ $('#l_less').click(function(){ var dec = decrement('l_value', 'l_step', 'l_min'); if (dec != -1) { logButtonPress('l_less'); steps += 1; } }); $('#l_okay').click(function(){ nextPanel(); logButtonPress('l_okay'); }); $('#l_more').click(function(){ var inc = increment('l_value', 'l_step', 'l_max'); if (inc != -1) { logButtonPress('l_more'); steps += 1; } }); /** Loudness button control **/ $('#v_less').click(function(){ var dec = decrement('v_value', 'v_step', 'v_min'); if (dec != -1) { logButtonPress('v_less'); steps += 1; } }); $('#v_okay').click(function(){ nextPanel(); logButtonPress('v_okay'); }); $('#v_more').click(function(){ var inc = increment('v_value', 'v_step', 'v_max'); if (inc != -1) { logButtonPress('v_more'); steps += 1; } }); /** Crispness button control **/ $('#h_less').click(function(){ var dec = decrement('h_value', 'h_step', 'h_min'); // link with fullness for 2-parameter option var inc = 0; if (parametersSingleChannel['sequence_num'] == 2 && dec != -1) { inc = increment('l_value', 'l_step', 'l_max'); // error in increment -- rollback decrement as well if (inc == -1) { increment('h_value', 'h_step', 'h_max'); } else { logButtonPress('l_more') } } if (dec != -1 && inc != -1) { logButtonPress('h_less'); steps += 1; } }); $('#h_okay').click(function(){ nextPanel(); logButtonPress('h_okay'); }); $('#h_more').click(function(){ var inc = increment('h_value', 'h_step', 'h_max'); // link with fullness for 2-parameter option var dec = 0; // default value in scope if (parametersSingleChannel['sequence_num'] == 2 && inc != -1) { dec = decrement('l_value', 'l_step', 'l_min'); // error in decrement -- rollback increment as well if (dec == -1) { decrement('h_value', 'h_step', 'h_min'); } else { logButtonPress('l_less'); } } // log only if both successful if (inc != -1 && dec != -1) { logButtonPress('h_more'); steps += 1; } }); /** Finish button control **/ $('#finish_button').click(function(){ nextPanel(); logButtonPress('finish_button'); }); /** Don't save button control **/ $('#dont_save_button').click(function(){ backToProgramsPage(); }); /** Save button control **/ $('#save_button').click(function(){ updateProgram(); logButtonPress('save_button'); }); /** Save as button control (in modal) **/ $('#save_as_button').click(function(){ saveProgram(); logButtonPress('save_as_button'); }) /** Pop up box control **/ $('#saveAsModal').on('shown.bs.modal', function () { $('#modalInput').trigger('focus') }); $('#infoModal').on('shown.bs.modal', function () { monitorValues(); }); $('#lvhValues').click(function(){ updateLVHText(); }); /** * Redirects to programs page */ function backToProgramsPage() { let newUrl = window.location.origin + "/goldilocks/listener/programs"; window.location.replace(newUrl); } disableButtonOnMaxOvershoot(); disableButtonOnMinOvershoot(); /** * Logic to handle panel changes. Uses variable 'sequence' array to see what goes next. */ function nextPanel(){ hideAllPanels(); console.log(this['sequence']) if(this['sequence'].length > 1){ var elem = this['sequence'].shift(); switch(elem){ case 'V': document.getElementById("loudness_section").style.visibility = "visible"; break; case 'H': document.getElementById("crispness_section").style.visibility = "visible"; break; case 'L': document.getElementById("fullness_section").style.visibility = "visible"; break; } } else if(this['sequence'].length == 1){ var elem = this['sequence'].shift(); switch (elem) { case 1: document.getElementById("loudness_section").style.visibility = "visible" document.getElementById("v_okay").style.visibility = "hidden"; document.getElementById("finish_button").style.visibility = "visible"; break; case 2: document.getElementById("crispness_section").style.visibility = "visible"; document.getElementById("loudness_section").style.visibility = "visible"; document.getElementById("h_okay").style.visibility = "hidden"; document.getElementById("v_okay").style.visibility = "hidden"; document.getElementById("finish_button").style.visibility = "visible"; break; case 3: document.getElementById("crispness_section").style.visibility = "visible"; document.getElementById("loudness_section").style.visibility = "visible"; document.getElementById("fullness_section").style.visibility = "visible"; document.getElementById("h_okay").style.visibility = "hidden"; document.getElementById("v_okay").style.visibility = "hidden"; document.getElementById("l_okay").style.visibility = "hidden"; document.getElementById("finish_button").style.visibility = "visible"; break; } } //empty sequence array implies finish button has been pressed else{ document.getElementById("end_buttons").style.display = "block"; document.getElementById("save_button").style.visibility = "visible"; document.getElementById("dont_save_button").style.visibility = "visible"; document.getElementById("save_as_modal_trigger").style.visibility = parametersSingleChannel['app_behavior'] == 1 ? 'hidden' : "visible"; } } /** * Reset page to show no panels. Useful at the beginning of updating next panel. */ function hideAllPanels(){ document.getElementById("crispness_section").style.visibility = "hidden"; document.getElementById("loudness_section").style.visibility = "hidden"; document.getElementById("fullness_section").style.visibility = "hidden"; document.getElementById("finish_button").style.visibility = "hidden"; document.getElementById("save_button").style.visibility = "hidden"; document.getElementById("dont_save_button").style.visibility = "hidden"; document.getElementById("finish_footer").style.visibility = "hidden"; document.getElementById("end_buttons").style.visibility = "hidden"; document.getElementById("save_as_modal_trigger").style.visibility = "hidden"; } /** * Calculate g50[id] and g80[id] based on g65[id] and compression_ration[id] on the passed in channel */ function crg65(id, channel){ var cr = this['parametersTwoChannels'][channel]['compression_ratio'][id]; if (cr != 0) { slope = (1 - cr) / cr; var g65 = this['parametersTwoChannels'][channel]['g65'][id]; var g50 = g65 - (slope * 15); var g80 = g65 + (slope * 15); this['parametersTwoChannels'][channel]['g50'][id] = g50; this['parametersTwoChannels'][channel]['g80'][id] = g80; } } /** * Calculate g65[id] and compression_ration[id] based on g50[id] and g80[id] */ function g50g80(id, channel){ var g50 = parametersTwoChannels[channel]['g50'][id]; var g80 = parametersTwoChannels[channel]['g80'][id]; var slope = (g80 - g50)/30; var g65 = g50 + slope * 15; this['parametersTwoChannels'][channel]['g65'][id] = g65; if(slope != -1){ var cr = Math.round( (1 / (1 + slope)) * 10 ) / 10; this['parametersTwoChannels'][channel]['compression_ratio'][id] = cr; } } /** * Returns true if change would exceed maximum for one channel */ function exceedsMax(l_val, v_val, h_val){ for(i = 0; i < 6; i++){ //loop through two channels of starting_g65 and cr for(j = 0; j < 2; j++){ var g65 = this['starting_g65'][j][i] + v_val + (l_val * this['parametersSingleChannel']['multiplier_l'][i]) + (h_val * this['parametersSingleChannel']['multiplier_h'][i]); var cr = this['parametersTwoChannels'][channels[j]]['compression_ratio'][i]; if(cr != 0){ var slope = (1 - cr) / cr; var g50 = g65 - (slope * 15); if(g50 > this['parametersTwoChannels'][channels[j]]['g50_max'][i]){ return true; } } else{ alert("Compression ratio should not be set to zero. Please ask for assistance."); return true; } } } return false; } /** * Calculate new value for l/v/h and check to see if it exceeds maximum. If so show warning, otherwise update * values and transmit. */ function increment(id, step_type, max){ var old_value = +document.getElementById(id).innerHTML; //plus sign is to denote as integer var add = this['parametersSingleChannel'][step_type]; var new_value = old_value + add; if (id === 'l_value') { add *= l_mul; } else if (id === 'h_value') { add *= h_mul; } if(new_value <= this['parametersSingleChannel'][max]){ document.getElementById(id).innerHTML = old_value + add; var l_val = +document.getElementById("l_value").innerHTML / l_mul; var v_val = +document.getElementById("v_value").innerHTML; var h_val = +document.getElementById("h_value").innerHTML / h_mul; //check to see if this change exceeds max g50 gain if(exceedsMax(l_val, v_val, h_val)){ //output max message // alert("Warning: you've attempted to exceed maximum gain. No change will take place."); //change back the value // document.getElementById(id).innerHTML = old_value; // return -1; } else { //update parameters for (i = 0; i < 6; i++) { for( j = 0; j<2; j++){ this['parametersTwoChannels'][channels[j]]['g65'][i] = this['starting_g65'][j][i] + v_val + (l_val * this['parametersSingleChannel']['multiplier_l'][i]) + (h_val * this['parametersSingleChannel']['multiplier_h'][i]); crg65(i, channels[j]); } } //send values to hearing aid transmit(); updateLVHText(); } } else{ // alert("Warning: Cannot exceed maximum value for " + step_type); // document.getElementById(id).innerHTML = old_value; // return -1; } this.disableButtonOnMaxOvershoot(); this.enableButtonOnBypassMinOvershoot(); } function enableButtonOnBypassMinOvershoot() { // preemptive calculaions to determine button enables var l_less = document.getElementById("l_less"); var v_less = document.getElementById("v_less"); var h_less = document.getElementById("h_less"); var sub_l = this['parametersSingleChannel']['l_step']; var sub_h = this['parametersSingleChannel']['h_step']; var sub_v = this['parametersSingleChannel']['v_step']; var old_value_l = +document.getElementById("l_value").innerHTML; var old_value_h = +document.getElementById("h_value").innerHTML; var old_value_v = +document.getElementById("v_value").innerHTML; var new_value_l = old_value_l - sub_l; var new_value_h = old_value_h - sub_h; var new_value_v = old_value_v - sub_v; // enable l button if doesn't overshoot min anymore if(new_value_l > this['parametersSingleChannel']['l_min']){ l_less.disabled = false; l_less.innerHTML = "Less"; } if(new_value_h > this['parametersSingleChannel']['h_min']){ h_less.disabled = false; h_less.innerHTML = "Less"; } if(new_value_v > this['parametersSingleChannel']['v_min']){ v_less.disabled = false; v_less.innerHTML = "Less"; } } function disableButtonOnMaxOvershoot() { // preemptive calculaions to determine button disables var l_more = document.getElementById("l_more"); var v_more = document.getElementById("v_more"); var h_more = document.getElementById("h_more"); var add_l = this['parametersSingleChannel']['l_step']; var add_h = this['parametersSingleChannel']['h_step']; var add_v = this['parametersSingleChannel']['v_step']; var old_value_l = +document.getElementById("l_value").innerHTML; var old_value_h = +document.getElementById("h_value").innerHTML; var old_value_v = +document.getElementById("v_value").innerHTML; var new_value_l = old_value_l + add_l; var new_value_h = old_value_h + add_h; var new_value_v = old_value_v + add_v; add_l *= l_mul; add_h *= h_mul; // disable l button on overshoot if(new_value_l <= this['parametersSingleChannel']['l_max']){ var new_value_l_2 = old_value_l + add_l; var l_val = new_value_l_2 / l_mul; var v_val = old_value_v; var h_val = old_value_h / h_mul; if(exceedsMax(l_val, v_val, h_val)){ l_more.disabled = true; l_more.innerHTML = "MAX"; l_more.style.color = "red"; } } else { l_more.disabled = true; l_more.innerHTML = "MAX"; l_more.style.color = "red"; } // disable h button on overshoot if(new_value_h <= this['parametersSingleChannel']['h_max']){ var new_value_h_2 = old_value_h + add_h; var l_val = old_value_l / l_mul; var v_val = old_value_v; var h_val = new_value_h_2 / h_mul; if(exceedsMax(l_val, v_val, h_val)){ h_more.disabled = true; h_more.innerHTML = "MAX"; } } else { h_more.disabled = true; h_more.innerHTML = "MAX"; } // disable v button on overshoot if(new_value_v <= this['parametersSingleChannel']['v_max']){ var new_value_v_2 = old_value_v + add_v; var l_val = old_value_l / l_mul; var v_val = new_value_v_2; var h_val = old_value_h / h_mul; if(exceedsMax(l_val, v_val, h_val)){ v_more.disabled = true; v_more.innerHTML = "MAX"; } } else { v_more.disabled = true; v_more.innerHTML = "MAX"; } } /** * Calculate new value for l/v/h and check to see if it exceeds minimum. If so show warning, otherwise update * values and transmit. */ function decrement(id, step_type, min){ var old_value = +document.getElementById(id).innerHTML; //plus sign is to denote as integer var sub = this['parametersSingleChannel'][step_type]; var new_value = old_value - sub; // calculate the values in decibels for display if (id === 'l_value') { sub *= l_mul; } else if (id === 'h_value') { sub *= h_mul; } if(new_value >= this['parametersSingleChannel'][min]){ document.getElementById(id).innerHTML = old_value - sub; var l_val = +document.getElementById("l_value").innerHTML / l_mul; var v_val = +document.getElementById("v_value").innerHTML; var h_val = +document.getElementById("h_value").innerHTML / h_mul; //update parameters for left and right channel for(i = 0; i < 6; i++){ for(j = 0; j < 2; j++){ this['parametersTwoChannels'][channels[j]]['g65'][i] = this['starting_g65'][j][i] + v_val + (l_val * this['parametersSingleChannel']['multiplier_l'][i]) + (h_val * this['parametersSingleChannel']['multiplier_h'][i]); crg65(i, channels[j]); } } //send values to hearing aid transmit(); updateLVHText(); } this.disableButtonOnMinOvershoot(); this.enableButtonOnBypassMaxOvershoot(); } function enableButtonOnBypassMaxOvershoot() { // preemptive calculaions to determine button enables var l_more = document.getElementById("l_more"); var v_more = document.getElementById("v_more"); var h_more = document.getElementById("h_more"); var add_l = this['parametersSingleChannel']['l_step']; var add_h = this['parametersSingleChannel']['h_step']; var add_v = this['parametersSingleChannel']['v_step']; var old_value_l = +document.getElementById("l_value").innerHTML; var old_value_h = +document.getElementById("h_value").innerHTML; var old_value_v = +document.getElementById("v_value").innerHTML; var new_value_l = old_value_l + add_l; var new_value_h = old_value_h + add_h; var new_value_v = old_value_v + add_v; add_l *= l_mul; add_h *= h_mul; // enable l button if doesn't bypass max threshold anymore if(new_value_l <= this['parametersSingleChannel']['l_max']){ var new_value_l_2 = old_value_l + add_l; var l_val = new_value_l_2 / l_mul; var v_val = old_value_v; var h_val = old_value_h / h_mul; if(!exceedsMax(l_val, v_val, h_val)){ l_more.disabled = false; l_more.innerHTML = "More"; } } // enable v button if doesn't bypass max threshold anymore if(new_value_v <= this['parametersSingleChannel']['v_max']){ var new_value_v_2 = old_value_v + add_v; var l_val = old_value_l / l_mul; var v_val = new_value_v_2; var h_val = old_value_h / h_mul; if(!exceedsMax(l_val, v_val, h_val)){ v_more.disabled = false; v_more.innerHTML = "More"; } } // enable h button if doesn't bypass max threshold anymore if(new_value_h <= this['parametersSingleChannel']['h_max']){ var new_value_h_2 = old_value_h + add_h; var l_val = old_value_l / l_mul; var v_val = old_value_v; var h_val = new_value_h_2 / h_mul; if(!exceedsMax(l_val, v_val, h_val)){ h_more.disabled = false; h_more.innerHTML = "More"; } } } function disableButtonOnMinOvershoot() { // preemptive calculaions to determine button disables var l_less = document.getElementById("l_less"); var v_less = document.getElementById("v_less"); var h_less = document.getElementById("h_less"); var sub_l = this['parametersSingleChannel']['l_step']; var sub_h = this['parametersSingleChannel']['h_step']; var sub_v = this['parametersSingleChannel']['v_step']; var old_value_l = +document.getElementById("l_value").innerHTML; var old_value_h = +document.getElementById("h_value").innerHTML; var old_value_v = +document.getElementById("v_value").innerHTML; var new_value_l = old_value_l - sub_l; var new_value_h = old_value_h - sub_h; var new_value_v = old_value_v - sub_v; if(new_value_l < this['parametersSingleChannel']['l_min']){ l_less.disabled = true; l_less.innerHTML = "MIN"; } if(new_value_h < this['parametersSingleChannel']['h_min']){ h_less.disabled = true; h_less.innerHTML = "MIN"; } if(new_value_v < this['parametersSingleChannel']['v_min']){ v_less.disabled = true; v_less.innerHTML = "MIN"; } } /** * Update the lvhValues HTML element using the current values */ function updateLVHText(){ var elem = document.getElementById("lvhValues"); var l_val = document.getElementById("l_value").innerHTML; var v_val = document.getElementById("v_value").innerHTML; var h_val = document.getElementById("h_value").innerHTML; // 03/28/2019 -- commented out for production // elem.innerHTML = l_val + ", " + v_val + ", " + h_val; } /** * Make a POST request to /api/params with the proper data to update the state of the hearing aid. This should * be done after any changes to the values are made and upon loading the page. */ function transmit(){ $.ajax({ method: 'POST', url: '/api/params', dataType: 'text json', contentType: 'application/json', data: JSON.stringify({ user_id: this['listener_id'], method: "set", request_action: 1, data: { left: { en_ha: 1, afc: this['parametersTwoChannels']['left']['afc'], rear_mics: 0, g50: this['parametersTwoChannels']['left']['g50'], g80: this['parametersTwoChannels']['left']['g80'], knee_low: this['parametersTwoChannels']['left']['knee_low'], mpo_band: this['parametersTwoChannels']['left']['mpo_band'], attack: this['parametersTwoChannels']['left']['attack'], release: this['parametersTwoChannels']['left']['release'] }, right: { en_ha: 1, afc: this['parametersTwoChannels']['right']['afc'], rear_mics: 0, g50: this['parametersTwoChannels']['right']['g50'], g80: this['parametersTwoChannels']['right']['g80'], knee_low: this['parametersTwoChannels']['right']['knee_low'], mpo_band: this['parametersTwoChannels']['right']['mpo_band'], attack: this['parametersTwoChannels']['right']['attack'], release: this['parametersTwoChannels']['right']['release'] } } }), success: function(response){ console.log(response); }, error: function(jqXHR, textStatus, errorThrown) { console.log(JSON.stringify(jqXHR)); console.log("AJAX error: " + textStatus + ' : ' + errorThrown); } }); } /** * Update and save program in the database that already exists. Program in database is denoted by programId * variable. */ function updateProgram(){ // throw error if no program has been selected if(this['programId'] == -1){ if(confirm('No program selected. Press okay to go to programs, press cancel to stay.')) { location.href = '{{ url('programs') }}'; } } else{ $.ajax({ method: 'PUT', headers: {'X-CSRF-TOKEN': "{{ csrf_token() }}" }, url: '/goldilocks/listener', dataType: 'text json', contentType: 'application/json', data: JSON.stringify([ this['programId'], this['parametersSingleChannel'], this['parametersTwoChannels'], ]), success: function(response){ console.log(response); logAdjustmentSession(); alert('Program saved'); location.href= '{{ url('/goldilocks/listener/programs') }}'; }, error: function(jqXHR, textStatus, errorThrown) { console.log(JSON.stringify(jqXHR)); console.log("AJAX error: " + textStatus + ' : ' + errorThrown); alert('There was an error with your request'); } }); } } /** * Create a new program in the database tied to the listener. Requires a non-empty name field. */ function saveProgram(){ console.log("Saving program"); if(document.getElementById("modalInput").value == ''){ document.getElementById("modalInputError").innerHTML = "Must include a name"; console.log("Error: input is empty"); } else{ $.ajax({ method: 'POST', headers: {'X-CSRF-TOKEN': "{{ csrf_token() }}" }, url: '/goldilocks/listener', dataType: 'text json', contentType: 'application/json', data: JSON.stringify([ document.getElementById("modalInput").value, this['parametersSingleChannel'], this['parametersTwoChannels'], ]), success: function(response){ if(response['status'] == "failure"){ document.getElementById("modalInputError").innerHTML = "The name \"" + (document.getElementById("modalInput").value) + "\" is already taken."; } else { console.log(response); programId = response["id"]; logAdjustmentSession(); $('#saveAsModal').modal('hide'); location.href = '{{ url('/goldilocks/listener/programs') }}'; } }, error: function(jqXHR, textStatus, errorThrown) { console.log(JSON.stringify(jqXHR)); console.log("AJAX error: " + textStatus + ' : ' + errorThrown); document.getElementById("modalInputError").innerHTML = "There was an error with your request"; } }); } } /** * Makes a GET request on /api/getParams to pull the parameters from the hearing aid and fills the variables * in the page based off of these parameters. */ function monitorValues(){ $.ajax({ method: 'GET', url: '/api/getParams', success: function(response){ console.log(response); params = JSON.parse(response); for(i = 0; i < 2; i++){ let channel = channels[i]; parametersTwoChannels[channel]['g50'] = params[channel]['g50']; parametersTwoChannels[channel]['g80'] = params[channel]['g80']; parametersTwoChannels[channel]['knee_low'] = params[channel]['knee_low']; parametersTwoChannels[channel]['mpo_band'] = params[channel]['mpo_band']; parametersTwoChannels[channel]['afc'] = params[channel]['afc']; parametersTwoChannels[channel]['attack'] = params[channel]['attack']; parametersTwoChannels[channel]['release'] = params[channel]['release']; } for(i = 0; i < 6; i++){ for(j=0; j <2; j++){ g50g80(i, channels[j]); } } document.getElementById("infoModalText").innerHTML = JSON.stringify( { CR: parameters['compression_ratio'], G65: parameters['g65'], KL: parameters['knee_low'], MPO: parameters['mpo_band'], AT: parameters['attack'], RT: parameters['release'] } ); }, error: function(jqXHR, textStatus, errorThrown) { console.log(JSON.stringify(jqXHR)); console.log("AJAX error: " + textStatus + ' : ' + errorThrown); } }); } /** * Logs the button press in the database. Should called after calculations occur (if any), so that we have * updated lvh values. * * @param button_id */ function logButtonPress(button_id){ var l_val = +document.getElementById("l_value").innerHTML; var v_val = +document.getElementById("v_value").innerHTML; var h_val = +document.getElementById("h_value").innerHTML; // build changeString if (button_id === "l_more" || button_id === "l_less") { changeString += "L" + l_val + "|"; } else if (button_id === "v_more" || button_id === "v_less") { changeString += "V" + v_val + "|"; } else if (button_id === "h_more" || button_id === "h_less") { changeString += "H" + h_val + "|"; } // log to db $.ajax({ method: 'POST', headers: {'X-CSRF-TOKEN': "{{ csrf_token() }}" }, url: '/goldilocks/listener/log', dataType: 'text json', contentType: 'application/json', data: JSON.stringify({ action: button_id, program_state: { parameters: parametersSingleChannel, parametersTwoChannels }, lvh_values: { l_value: l_val, v_value: v_val, h_value: h_val }, }), success: function(response) { console.log(response); }, error: function(jqXHR, textStatus, errorThrown) { console.log(JSON.stringify(jqXHR)); console.log("AJAX error: " + textStatus + ' : ' + errorThrown); } }); } /** * Logs the adjustment session on the press of finish button to the * table `listener_adjustment_logs` */ function logAdjustmentSession(){ // get finish timestamp var dt = new Date(); var tz = dt.getTimezoneOffset() / -60; // elapsed ms since start of session until finish var ms = dt - start; // strip last '|' delimiter from changeString changeString = changeString.slice(0, -1); var l_val = +document.getElementById("l_value").innerHTML; var v_val = +document.getElementById("v_value").innerHTML; var h_val = +document.getElementById("h_value").innerHTML; console.log("millisecs: " + ms); console.log("g65: " + starting_g65); console.log("cr: " + cr); console.log("lmul: " + l_multipliers); console.log("hmul: " + h_multipliers); console.log("step-by-step changes: " + changeString); console.log("timestamp: " + dt); var jsonData = JSON.stringify({ final_lvh: { l_value: l_val, v_value: v_val, h_value: h_val }, starting_g65: starting_g65, ending_g65: [this['parametersTwoChannels']['left']['g65'].slice(), this['parametersTwoChannels']['right']['g65'].slice()], cr: cr, lmul: l_multipliers, hmul: h_multipliers, time_ms: ms, steps: steps, changes: changeString, start_program_id: programIdStart, end_program_id: programId, timestamp: dt, timezone: tz }); console.log(jsonData); // log to db $.ajax({ async: false, method: 'POST', headers: {'X-CSRF-TOKEN': "{{ csrf_token() }}" }, url: '/goldilocks/listener/adjustmentLog', dataType: 'text json', contentType: 'application/json', data: jsonData, success: function(response) { console.log(response); }, error: function(jqXHR, textStatus, errorThrown) { console.log(JSON.stringify(jqXHR)); console.log("AJAX error: " + textStatus + ' : ' + errorThrown); } }); } </script> </body> </html>
nihospr01/OpenSpeechPlatform-UCSD
Sources/embeddedwebserver/resources/views/goldilocks/listener.blade.php
PHP
bsd-2-clause
52,770
class Clamav < Formula desc "Anti-virus software" homepage "https://www.clamav.net/" url "https://www.clamav.net/downloads/production/clamav-0.102.0.tar.gz" mirror "https://fossies.org/linux/misc/clamav-0.102.0.tar.gz" sha256 "48fe188c46c793c2d0cb5c81c106e4690251aff6dc8aa6575dc688343291bee1" bottle do sha256 "4e78b3649f40ff746343f6593074cca1df281d480323e31e9d08e6cdda77e48a" => :catalina sha256 "e0ca454c1ef225dcaf647a3f709819b73b28c66861256159b6718c80098f8a70" => :mojave sha256 "887186bdbadcb1c2aec51a4152c8a244b4ee767fd162786f4625d2017fc97d2f" => :high_sierra end head do url "https://github.com/Cisco-Talos/clamav-devel.git" depends_on "autoconf" => :build depends_on "automake" => :build depends_on "libtool" => :build end depends_on "pkg-config" => :build depends_on "json-c" depends_on "openssl@1.1" depends_on "pcre" depends_on "yara" skip_clean "share/clamav" def install args = %W[ --disable-dependency-tracking --disable-silent-rules --prefix=#{prefix} --libdir=#{lib} --sysconfdir=#{etc}/clamav --disable-zlib-vcheck --enable-llvm=no --with-libjson=#{Formula["json-c"].opt_prefix} --with-openssl=#{Formula["openssl@1.1"].opt_prefix} --with-pcre=#{Formula["pcre"].opt_prefix} --with-zlib=#{MacOS.sdk_path_if_needed}/usr ] pkgshare.mkpath system "autoreconf", "-fvi" if build.head? system "./configure", *args system "make", "install" end def caveats; <<~EOS To finish installation & run clamav you will need to edit the example conf files at #{etc}/clamav/ EOS end test do system "#{bin}/clamav-config", "--version" end end
zmwangx/homebrew-core
Formula/clamav.rb
Ruby
bsd-2-clause
1,720
package org.jcodec.moovtool.streaming; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.channels.Channels; import java.nio.channels.FileChannel; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadFactory; import org.jcodec.common.IOUtils; import org.jcodec.containers.mp4.MP4Util; import org.jcodec.containers.mp4.boxes.MovieBox; import org.jcodec.movtool.streaming.ConcurrentMovieRangeService; import org.jcodec.movtool.streaming.MovieRange; import org.jcodec.movtool.streaming.VirtualMP4Movie; import org.jcodec.movtool.streaming.VirtualMovie; import org.jcodec.movtool.streaming.tracks.FilePool; import org.jcodec.movtool.streaming.tracks.RealTrack; public class TestConcurrentMovieRangeService { public static void main(String[] args) throws IOException { if (args.length < 1) { System.out.println("Syntax: <movie.mov>"); return; } File file = new File(args[0]); FilePool fp = new FilePool(file, 10); MovieBox movie = MP4Util.parseMovie(file); RealTrack vt = new RealTrack(movie, movie.getVideoTrack(), fp); VirtualMovie vm = new VirtualMP4Movie(vt); InputStream is = new MovieRange(vm, 0, vm.size()); File ref = File.createTempFile("cool", "super"); ref.deleteOnExit(); FileOutputStream tmpOs = new FileOutputStream(ref); IOUtils.copy(is, tmpOs); is.close(); tmpOs.close(); ConcurrentMovieRangeService cmrs = new ConcurrentMovieRangeService(vm, 2); ExecutorService tp = Executors.newFixedThreadPool(20, new ThreadFactory() { public Thread newThread(Runnable runnable) { Thread thread = Executors.defaultThreadFactory().newThread(runnable); thread.setDaemon(true); return thread; } }); Future[] ff = new Future[1000]; for (int i = 0; i < 1000; i++) { ff[i] = tp.submit(new OneTest(vm, ref, cmrs)); } for (int i = 0; i < 1000; i++) { try { ff[i].get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } } public static class OneTest implements Runnable { private VirtualMovie vm; private File ref; private ConcurrentMovieRangeService cmrs; public OneTest(VirtualMovie vm, File ref, ConcurrentMovieRangeService cmrs) { this.vm = vm; this.ref = ref; this.cmrs = cmrs; } public void run() { try { long size = vm.size(); long from = (long) (Math.random() * size); long to = from + (long) (Math.random() * (size - from)); System.out.println("RANGE: " + from + " - " + to); InputStream is1 = cmrs.getRange(from, to); FileChannel in = new FileInputStream(ref).getChannel(); in.position(from); InputStream is2 = Channels.newInputStream(in); byte[] buf1 = new byte[4096], buf2 = new byte[4096]; int b, ii = 0; do { b = is1.read(buf1); int b2 = is2.read(buf2); if (b != -1) { for (int k = 0; k < b; k++) { if (buf1[k] != buf2[k]) throw new RuntimeException("[" + (ii + k) + "]" + buf1[k] + ":" + buf2[k]); } ii += b; } } while (b != -1); if (ii != to - from + 1) throw new RuntimeException("Read less [" + ii + " < " + (to - from + 1)); is1.close(); is2.close(); } catch (IOException e) { e.printStackTrace(); } } } }
java02014/jcodec
src/test/java/org/jcodec/moovtool/streaming/TestConcurrentMovieRangeService.java
Java
bsd-2-clause
4,262
/** @file Support routines for memory allocation routines based on SMM Services Table services for SMM phase drivers, with memory profile support. The PI System Management Mode Core Interface Specification only allows the use of EfiRuntimeServicesCode and EfiRuntimeServicesData memory types for memory allocations through the SMM Services Table as the SMRAM space should be reserved after BDS phase. The functions in the Memory Allocation Library use EfiBootServicesData as the default memory allocation type. For this SMM specific instance of the Memory Allocation Library, EfiRuntimeServicesData is used as the default memory type for all allocations. In addition, allocation for the Reserved memory types are not supported and will always return NULL. Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.<BR> This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License which accompanies this distribution. The full text of the license may be found at http://opensource.org/licenses/bsd-license.php. THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. **/ #include <PiSmm.h> #include <Protocol/SmmAccess2.h> #include <Library/MemoryAllocationLib.h> #include <Library/UefiBootServicesTableLib.h> #include <Library/SmmServicesTableLib.h> #include <Library/BaseMemoryLib.h> #include <Library/DebugLib.h> #include <Library/MemoryProfileLib.h> EFI_SMRAM_DESCRIPTOR *mSmramRanges; UINTN mSmramRangeCount; /** The constructor function caches SMRAM ranges that are present in the system. It will ASSERT() if SMM Access2 Protocol doesn't exist. It will ASSERT() if SMRAM ranges can't be got. It will ASSERT() if Resource can't be allocated for cache SMRAM range. It will always return EFI_SUCCESS. @param ImageHandle The firmware allocated handle for the EFI image. @param SystemTable A pointer to the EFI System Table. @retval EFI_SUCCESS The constructor always returns EFI_SUCCESS. **/ EFI_STATUS EFIAPI SmmMemoryAllocationLibConstructor ( IN EFI_HANDLE ImageHandle, IN EFI_SYSTEM_TABLE *SystemTable ) { EFI_STATUS Status; EFI_SMM_ACCESS2_PROTOCOL *SmmAccess; UINTN Size; // // Locate SMM Access2 Protocol // Status = gBS->LocateProtocol ( &gEfiSmmAccess2ProtocolGuid, NULL, (VOID **)&SmmAccess ); ASSERT_EFI_ERROR (Status); // // Get SMRAM range information // Size = 0; Status = SmmAccess->GetCapabilities (SmmAccess, &Size, NULL); ASSERT (Status == EFI_BUFFER_TOO_SMALL); mSmramRanges = (EFI_SMRAM_DESCRIPTOR *) AllocatePool (Size); ASSERT (mSmramRanges != NULL); Status = SmmAccess->GetCapabilities (SmmAccess, &Size, mSmramRanges); ASSERT_EFI_ERROR (Status); mSmramRangeCount = Size / sizeof (EFI_SMRAM_DESCRIPTOR); return EFI_SUCCESS; } /** If SMM driver exits with an error, it must call this routine to free the allocated resource before the exiting. @param[in] ImageHandle The firmware allocated handle for the EFI image. @param[in] SystemTable A pointer to the EFI System Table. @retval EFI_SUCCESS The deconstructor always returns EFI_SUCCESS. **/ EFI_STATUS EFIAPI SmmMemoryAllocationLibDestructor ( IN EFI_HANDLE ImageHandle, IN EFI_SYSTEM_TABLE *SystemTable ) { FreePool (mSmramRanges); return EFI_SUCCESS; } /** Check whether the start address of buffer is within any of the SMRAM ranges. @param[in] Buffer The pointer to the buffer to be checked. @retval TRUE The buffer is in SMRAM ranges. @retval FALSE The buffer is out of SMRAM ranges. **/ BOOLEAN EFIAPI BufferInSmram ( IN VOID *Buffer ) { UINTN Index; for (Index = 0; Index < mSmramRangeCount; Index ++) { if (((EFI_PHYSICAL_ADDRESS) (UINTN) Buffer >= mSmramRanges[Index].CpuStart) && ((EFI_PHYSICAL_ADDRESS) (UINTN) Buffer < (mSmramRanges[Index].CpuStart + mSmramRanges[Index].PhysicalSize))) { return TRUE; } } return FALSE; } /** Allocates one or more 4KB pages of a certain memory type. Allocates the number of 4KB pages of a certain memory type and returns a pointer to the allocated buffer. The buffer returned is aligned on a 4KB boundary. If Pages is 0, then NULL is returned. If there is not enough memory remaining to satisfy the request, then NULL is returned. @param MemoryType The type of memory to allocate. @param Pages The number of 4 KB pages to allocate. @return A pointer to the allocated buffer or NULL if allocation fails. **/ VOID * InternalAllocatePages ( IN EFI_MEMORY_TYPE MemoryType, IN UINTN Pages ) { EFI_STATUS Status; EFI_PHYSICAL_ADDRESS Memory; if (Pages == 0) { return NULL; } Status = gSmst->SmmAllocatePages (AllocateAnyPages, MemoryType, Pages, &Memory); if (EFI_ERROR (Status)) { return NULL; } return (VOID *) (UINTN) Memory; } /** Allocates one or more 4KB pages of type EfiRuntimeServicesData. Allocates the number of 4KB pages of type EfiRuntimeServicesData and returns a pointer to the allocated buffer. The buffer returned is aligned on a 4KB boundary. If Pages is 0, then NULL is returned. If there is not enough memory remaining to satisfy the request, then NULL is returned. @param Pages The number of 4 KB pages to allocate. @return A pointer to the allocated buffer or NULL if allocation fails. **/ VOID * EFIAPI AllocatePages ( IN UINTN Pages ) { VOID *Buffer; Buffer = InternalAllocatePages (EfiRuntimeServicesData, Pages); if (Buffer != NULL) { MemoryProfileLibRecord ( (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), MEMORY_PROFILE_ACTION_LIB_ALLOCATE_PAGES, EfiRuntimeServicesData, Buffer, EFI_PAGES_TO_SIZE(Pages), NULL ); } return Buffer; } /** Allocates one or more 4KB pages of type EfiRuntimeServicesData. Allocates the number of 4KB pages of type EfiRuntimeServicesData and returns a pointer to the allocated buffer. The buffer returned is aligned on a 4KB boundary. If Pages is 0, then NULL is returned. If there is not enough memory remaining to satisfy the request, then NULL is returned. @param Pages The number of 4 KB pages to allocate. @return A pointer to the allocated buffer or NULL if allocation fails. **/ VOID * EFIAPI AllocateRuntimePages ( IN UINTN Pages ) { VOID *Buffer; Buffer = InternalAllocatePages (EfiRuntimeServicesData, Pages); if (Buffer != NULL) { MemoryProfileLibRecord ( (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RUNTIME_PAGES, EfiRuntimeServicesData, Buffer, EFI_PAGES_TO_SIZE(Pages), NULL ); } return Buffer; } /** Allocates one or more 4KB pages of type EfiReservedMemoryType. Allocates the number of 4KB pages of type EfiReservedMemoryType and returns a pointer to the allocated buffer. The buffer returned is aligned on a 4KB boundary. If Pages is 0, then NULL is returned. If there is not enough memory remaining to satisfy the request, then NULL is returned. @param Pages The number of 4 KB pages to allocate. @return A pointer to the allocated buffer or NULL if allocation fails. **/ VOID * EFIAPI AllocateReservedPages ( IN UINTN Pages ) { return NULL; } /** Frees one or more 4KB pages that were previously allocated with one of the page allocation functions in the Memory Allocation Library. Frees the number of 4KB pages specified by Pages from the buffer specified by Buffer. Buffer must have been allocated on a previous call to the page allocation services of the Memory Allocation Library. If it is not possible to free allocated pages, then this function will perform no actions. If Buffer was not allocated with a page allocation function in the Memory Allocation Library, then ASSERT(). If Pages is zero, then ASSERT(). @param Buffer The pointer to the buffer of pages to free. @param Pages The number of 4 KB pages to free. **/ VOID EFIAPI FreePages ( IN VOID *Buffer, IN UINTN Pages ) { EFI_STATUS Status; ASSERT (Pages != 0); if (BufferInSmram (Buffer)) { // // When Buffer is in SMRAM range, it should be allocated by gSmst->SmmAllocatePages() service. // So, gSmst->SmmFreePages() service is used to free it. // Status = gSmst->SmmFreePages ((EFI_PHYSICAL_ADDRESS) (UINTN) Buffer, Pages); } else { // // When Buffer is out of SMRAM range, it should be allocated by gBS->AllocatePages() service. // So, gBS->FreePages() service is used to free it. // Status = gBS->FreePages ((EFI_PHYSICAL_ADDRESS) (UINTN) Buffer, Pages); } ASSERT_EFI_ERROR (Status); } /** Allocates one or more 4KB pages of a certain memory type at a specified alignment. Allocates the number of 4KB pages specified by Pages of a certain memory type with an alignment specified by Alignment. The allocated buffer is returned. If Pages is 0, then NULL is returned. If there is not enough memory at the specified alignment remaining to satisfy the request, then NULL is returned. If Alignment is not a power of two and Alignment is not zero, then ASSERT(). If Pages plus EFI_SIZE_TO_PAGES (Alignment) overflows, then ASSERT(). @param MemoryType The type of memory to allocate. @param Pages The number of 4 KB pages to allocate. @param Alignment The requested alignment of the allocation. Must be a power of two. If Alignment is zero, then byte alignment is used. @return A pointer to the allocated buffer or NULL if allocation fails. **/ VOID * InternalAllocateAlignedPages ( IN EFI_MEMORY_TYPE MemoryType, IN UINTN Pages, IN UINTN Alignment ) { EFI_STATUS Status; EFI_PHYSICAL_ADDRESS Memory; UINTN AlignedMemory; UINTN AlignmentMask; UINTN UnalignedPages; UINTN RealPages; // // Alignment must be a power of two or zero. // ASSERT ((Alignment & (Alignment - 1)) == 0); if (Pages == 0) { return NULL; } if (Alignment > EFI_PAGE_SIZE) { // // Calculate the total number of pages since alignment is larger than page size. // AlignmentMask = Alignment - 1; RealPages = Pages + EFI_SIZE_TO_PAGES (Alignment); // // Make sure that Pages plus EFI_SIZE_TO_PAGES (Alignment) does not overflow. // ASSERT (RealPages > Pages); Status = gSmst->SmmAllocatePages (AllocateAnyPages, MemoryType, RealPages, &Memory); if (EFI_ERROR (Status)) { return NULL; } AlignedMemory = ((UINTN) Memory + AlignmentMask) & ~AlignmentMask; UnalignedPages = EFI_SIZE_TO_PAGES (AlignedMemory - (UINTN) Memory); if (UnalignedPages > 0) { // // Free first unaligned page(s). // Status = gSmst->SmmFreePages (Memory, UnalignedPages); ASSERT_EFI_ERROR (Status); } Memory = AlignedMemory + EFI_PAGES_TO_SIZE (Pages); UnalignedPages = RealPages - Pages - UnalignedPages; if (UnalignedPages > 0) { // // Free last unaligned page(s). // Status = gSmst->SmmFreePages (Memory, UnalignedPages); ASSERT_EFI_ERROR (Status); } } else { // // Do not over-allocate pages in this case. // Status = gSmst->SmmAllocatePages (AllocateAnyPages, MemoryType, Pages, &Memory); if (EFI_ERROR (Status)) { return NULL; } AlignedMemory = (UINTN) Memory; } return (VOID *) AlignedMemory; } /** Allocates one or more 4KB pages of type EfiRuntimeServicesData at a specified alignment. Allocates the number of 4KB pages specified by Pages of type EfiRuntimeServicesData with an alignment specified by Alignment. The allocated buffer is returned. If Pages is 0, then NULL is returned. If there is not enough memory at the specified alignment remaining to satisfy the request, then NULL is returned. If Alignment is not a power of two and Alignment is not zero, then ASSERT(). If Pages plus EFI_SIZE_TO_PAGES (Alignment) overflows, then ASSERT(). @param Pages The number of 4 KB pages to allocate. @param Alignment The requested alignment of the allocation. Must be a power of two. If Alignment is zero, then byte alignment is used. @return A pointer to the allocated buffer or NULL if allocation fails. **/ VOID * EFIAPI AllocateAlignedPages ( IN UINTN Pages, IN UINTN Alignment ) { VOID *Buffer; Buffer = InternalAllocateAlignedPages (EfiRuntimeServicesData, Pages, Alignment); if (Buffer != NULL) { MemoryProfileLibRecord ( (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), MEMORY_PROFILE_ACTION_LIB_ALLOCATE_ALIGNED_PAGES, EfiRuntimeServicesData, Buffer, EFI_PAGES_TO_SIZE(Pages), NULL ); } return Buffer; } /** Allocates one or more 4KB pages of type EfiRuntimeServicesData at a specified alignment. Allocates the number of 4KB pages specified by Pages of type EfiRuntimeServicesData with an alignment specified by Alignment. The allocated buffer is returned. If Pages is 0, then NULL is returned. If there is not enough memory at the specified alignment remaining to satisfy the request, then NULL is returned. If Alignment is not a power of two and Alignment is not zero, then ASSERT(). If Pages plus EFI_SIZE_TO_PAGES (Alignment) overflows, then ASSERT(). @param Pages The number of 4 KB pages to allocate. @param Alignment The requested alignment of the allocation. Must be a power of two. If Alignment is zero, then byte alignment is used. @return A pointer to the allocated buffer or NULL if allocation fails. **/ VOID * EFIAPI AllocateAlignedRuntimePages ( IN UINTN Pages, IN UINTN Alignment ) { VOID *Buffer; Buffer = InternalAllocateAlignedPages (EfiRuntimeServicesData, Pages, Alignment); if (Buffer != NULL) { MemoryProfileLibRecord ( (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), MEMORY_PROFILE_ACTION_LIB_ALLOCATE_ALIGNED_RUNTIME_PAGES, EfiRuntimeServicesData, Buffer, EFI_PAGES_TO_SIZE(Pages), NULL ); } return Buffer; } /** Allocates one or more 4KB pages of type EfiReservedMemoryType at a specified alignment. Allocates the number of 4KB pages specified by Pages of type EfiReservedMemoryType with an alignment specified by Alignment. The allocated buffer is returned. If Pages is 0, then NULL is returned. If there is not enough memory at the specified alignment remaining to satisfy the request, then NULL is returned. If Alignment is not a power of two and Alignment is not zero, then ASSERT(). If Pages plus EFI_SIZE_TO_PAGES (Alignment) overflows, then ASSERT(). @param Pages The number of 4 KB pages to allocate. @param Alignment The requested alignment of the allocation. Must be a power of two. If Alignment is zero, then byte alignment is used. @return A pointer to the allocated buffer or NULL if allocation fails. **/ VOID * EFIAPI AllocateAlignedReservedPages ( IN UINTN Pages, IN UINTN Alignment ) { return NULL; } /** Frees one or more 4KB pages that were previously allocated with one of the aligned page allocation functions in the Memory Allocation Library. Frees the number of 4KB pages specified by Pages from the buffer specified by Buffer. Buffer must have been allocated on a previous call to the aligned page allocation services of the Memory Allocation Library. If it is not possible to free allocated pages, then this function will perform no actions. If Buffer was not allocated with an aligned page allocation function in the Memory Allocation Library, then ASSERT(). If Pages is zero, then ASSERT(). @param Buffer The pointer to the buffer of pages to free. @param Pages The number of 4 KB pages to free. **/ VOID EFIAPI FreeAlignedPages ( IN VOID *Buffer, IN UINTN Pages ) { EFI_STATUS Status; ASSERT (Pages != 0); if (BufferInSmram (Buffer)) { // // When Buffer is in SMRAM range, it should be allocated by gSmst->SmmAllocatePages() service. // So, gSmst->SmmFreePages() service is used to free it. // Status = gSmst->SmmFreePages ((EFI_PHYSICAL_ADDRESS) (UINTN) Buffer, Pages); } else { // // When Buffer is out of SMRAM range, it should be allocated by gBS->AllocatePages() service. // So, gBS->FreePages() service is used to free it. // Status = gBS->FreePages ((EFI_PHYSICAL_ADDRESS) (UINTN) Buffer, Pages); } ASSERT_EFI_ERROR (Status); } /** Allocates a buffer of a certain pool type. Allocates the number bytes specified by AllocationSize of a certain pool type and returns a pointer to the allocated buffer. If AllocationSize is 0, then a valid buffer of 0 size is returned. If there is not enough memory remaining to satisfy the request, then NULL is returned. @param MemoryType The type of memory to allocate. @param AllocationSize The number of bytes to allocate. @return A pointer to the allocated buffer or NULL if allocation fails. **/ VOID * InternalAllocatePool ( IN EFI_MEMORY_TYPE MemoryType, IN UINTN AllocationSize ) { EFI_STATUS Status; VOID *Memory; Status = gSmst->SmmAllocatePool (MemoryType, AllocationSize, &Memory); if (EFI_ERROR (Status)) { Memory = NULL; } return Memory; } /** Allocates a buffer of type EfiRuntimeServicesData. Allocates the number bytes specified by AllocationSize of type EfiRuntimeServicesData and returns a pointer to the allocated buffer. If AllocationSize is 0, then a valid buffer of 0 size is returned. If there is not enough memory remaining to satisfy the request, then NULL is returned. @param AllocationSize The number of bytes to allocate. @return A pointer to the allocated buffer or NULL if allocation fails. **/ VOID * EFIAPI AllocatePool ( IN UINTN AllocationSize ) { VOID *Buffer; Buffer = InternalAllocatePool (EfiRuntimeServicesData, AllocationSize); if (Buffer != NULL) { MemoryProfileLibRecord ( (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), MEMORY_PROFILE_ACTION_LIB_ALLOCATE_POOL, EfiRuntimeServicesData, Buffer, AllocationSize, NULL ); } return Buffer; } /** Allocates a buffer of type EfiRuntimeServicesData. Allocates the number bytes specified by AllocationSize of type EfiRuntimeServicesData and returns a pointer to the allocated buffer. If AllocationSize is 0, then a valid buffer of 0 size is returned. If there is not enough memory remaining to satisfy the request, then NULL is returned. @param AllocationSize The number of bytes to allocate. @return A pointer to the allocated buffer or NULL if allocation fails. **/ VOID * EFIAPI AllocateRuntimePool ( IN UINTN AllocationSize ) { VOID *Buffer; Buffer = InternalAllocatePool (EfiRuntimeServicesData, AllocationSize); if (Buffer != NULL) { MemoryProfileLibRecord ( (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RUNTIME_POOL, EfiRuntimeServicesData, Buffer, AllocationSize, NULL ); } return Buffer; } /** Allocates a buffer of type EfiReservedMemoryType. Allocates the number bytes specified by AllocationSize of type EfiReservedMemoryType and returns a pointer to the allocated buffer. If AllocationSize is 0, then a valid buffer of 0 size is returned. If there is not enough memory remaining to satisfy the request, then NULL is returned. @param AllocationSize The number of bytes to allocate. @return A pointer to the allocated buffer or NULL if allocation fails. **/ VOID * EFIAPI AllocateReservedPool ( IN UINTN AllocationSize ) { return NULL; } /** Allocates and zeros a buffer of a certain pool type. Allocates the number bytes specified by AllocationSize of a certain pool type, clears the buffer with zeros, and returns a pointer to the allocated buffer. If AllocationSize is 0, then a valid buffer of 0 size is returned. If there is not enough memory remaining to satisfy the request, then NULL is returned. @param PoolType The type of memory to allocate. @param AllocationSize The number of bytes to allocate and zero. @return A pointer to the allocated buffer or NULL if allocation fails. **/ VOID * InternalAllocateZeroPool ( IN EFI_MEMORY_TYPE PoolType, IN UINTN AllocationSize ) { VOID *Memory; Memory = InternalAllocatePool (PoolType, AllocationSize); if (Memory != NULL) { Memory = ZeroMem (Memory, AllocationSize); } return Memory; } /** Allocates and zeros a buffer of type EfiRuntimeServicesData. Allocates the number bytes specified by AllocationSize of type EfiRuntimeServicesData, clears the buffer with zeros, and returns a pointer to the allocated buffer. If AllocationSize is 0, then a valid buffer of 0 size is returned. If there is not enough memory remaining to satisfy the request, then NULL is returned. @param AllocationSize The number of bytes to allocate and zero. @return A pointer to the allocated buffer or NULL if allocation fails. **/ VOID * EFIAPI AllocateZeroPool ( IN UINTN AllocationSize ) { VOID *Buffer; Buffer = InternalAllocateZeroPool (EfiRuntimeServicesData, AllocationSize); if (Buffer != NULL) { MemoryProfileLibRecord ( (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), MEMORY_PROFILE_ACTION_LIB_ALLOCATE_ZERO_POOL, EfiRuntimeServicesData, Buffer, AllocationSize, NULL ); } return Buffer; } /** Allocates and zeros a buffer of type EfiRuntimeServicesData. Allocates the number bytes specified by AllocationSize of type EfiRuntimeServicesData, clears the buffer with zeros, and returns a pointer to the allocated buffer. If AllocationSize is 0, then a valid buffer of 0 size is returned. If there is not enough memory remaining to satisfy the request, then NULL is returned. @param AllocationSize The number of bytes to allocate and zero. @return A pointer to the allocated buffer or NULL if allocation fails. **/ VOID * EFIAPI AllocateRuntimeZeroPool ( IN UINTN AllocationSize ) { VOID *Buffer; Buffer = InternalAllocateZeroPool (EfiRuntimeServicesData, AllocationSize); if (Buffer != NULL) { MemoryProfileLibRecord ( (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RUNTIME_ZERO_POOL, EfiRuntimeServicesData, Buffer, AllocationSize, NULL ); } return Buffer; } /** Allocates and zeros a buffer of type EfiReservedMemoryType. Allocates the number bytes specified by AllocationSize of type EfiReservedMemoryType, clears the buffer with zeros, and returns a pointer to the allocated buffer. If AllocationSize is 0, then a valid buffer of 0 size is returned. If there is not enough memory remaining to satisfy the request, then NULL is returned. @param AllocationSize The number of bytes to allocate and zero. @return A pointer to the allocated buffer or NULL if allocation fails. **/ VOID * EFIAPI AllocateReservedZeroPool ( IN UINTN AllocationSize ) { return NULL; } /** Copies a buffer to an allocated buffer of a certain pool type. Allocates the number bytes specified by AllocationSize of a certain pool type, copies AllocationSize bytes from Buffer to the newly allocated buffer, and returns a pointer to the allocated buffer. If AllocationSize is 0, then a valid buffer of 0 size is returned. If there is not enough memory remaining to satisfy the request, then NULL is returned. If Buffer is NULL, then ASSERT(). If AllocationSize is greater than (MAX_ADDRESS - Buffer + 1), then ASSERT(). @param PoolType The type of pool to allocate. @param AllocationSize The number of bytes to allocate and zero. @param Buffer The buffer to copy to the allocated buffer. @return A pointer to the allocated buffer or NULL if allocation fails. **/ VOID * InternalAllocateCopyPool ( IN EFI_MEMORY_TYPE PoolType, IN UINTN AllocationSize, IN CONST VOID *Buffer ) { VOID *Memory; ASSERT (Buffer != NULL); ASSERT (AllocationSize <= (MAX_ADDRESS - (UINTN) Buffer + 1)); Memory = InternalAllocatePool (PoolType, AllocationSize); if (Memory != NULL) { Memory = CopyMem (Memory, Buffer, AllocationSize); } return Memory; } /** Copies a buffer to an allocated buffer of type EfiRuntimeServicesData. Allocates the number bytes specified by AllocationSize of type EfiRuntimeServicesData, copies AllocationSize bytes from Buffer to the newly allocated buffer, and returns a pointer to the allocated buffer. If AllocationSize is 0, then a valid buffer of 0 size is returned. If there is not enough memory remaining to satisfy the request, then NULL is returned. If Buffer is NULL, then ASSERT(). If AllocationSize is greater than (MAX_ADDRESS - Buffer + 1), then ASSERT(). @param AllocationSize The number of bytes to allocate and zero. @param Buffer The buffer to copy to the allocated buffer. @return A pointer to the allocated buffer or NULL if allocation fails. **/ VOID * EFIAPI AllocateCopyPool ( IN UINTN AllocationSize, IN CONST VOID *Buffer ) { VOID *NewBuffer; NewBuffer = InternalAllocateCopyPool (EfiRuntimeServicesData, AllocationSize, Buffer); if (NewBuffer != NULL) { MemoryProfileLibRecord ( (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), MEMORY_PROFILE_ACTION_LIB_ALLOCATE_COPY_POOL, EfiRuntimeServicesData, NewBuffer, AllocationSize, NULL ); } return NewBuffer; } /** Copies a buffer to an allocated buffer of type EfiRuntimeServicesData. Allocates the number bytes specified by AllocationSize of type EfiRuntimeServicesData, copies AllocationSize bytes from Buffer to the newly allocated buffer, and returns a pointer to the allocated buffer. If AllocationSize is 0, then a valid buffer of 0 size is returned. If there is not enough memory remaining to satisfy the request, then NULL is returned. If Buffer is NULL, then ASSERT(). If AllocationSize is greater than (MAX_ADDRESS - Buffer + 1), then ASSERT(). @param AllocationSize The number of bytes to allocate and zero. @param Buffer The buffer to copy to the allocated buffer. @return A pointer to the allocated buffer or NULL if allocation fails. **/ VOID * EFIAPI AllocateRuntimeCopyPool ( IN UINTN AllocationSize, IN CONST VOID *Buffer ) { VOID *NewBuffer; NewBuffer = InternalAllocateCopyPool (EfiRuntimeServicesData, AllocationSize, Buffer); if (NewBuffer != NULL) { MemoryProfileLibRecord ( (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RUNTIME_COPY_POOL, EfiRuntimeServicesData, NewBuffer, AllocationSize, NULL ); } return NewBuffer; } /** Copies a buffer to an allocated buffer of type EfiReservedMemoryType. Allocates the number bytes specified by AllocationSize of type EfiReservedMemoryType, copies AllocationSize bytes from Buffer to the newly allocated buffer, and returns a pointer to the allocated buffer. If AllocationSize is 0, then a valid buffer of 0 size is returned. If there is not enough memory remaining to satisfy the request, then NULL is returned. If Buffer is NULL, then ASSERT(). If AllocationSize is greater than (MAX_ADDRESS - Buffer + 1), then ASSERT(). @param AllocationSize The number of bytes to allocate and zero. @param Buffer The buffer to copy to the allocated buffer. @return A pointer to the allocated buffer or NULL if allocation fails. **/ VOID * EFIAPI AllocateReservedCopyPool ( IN UINTN AllocationSize, IN CONST VOID *Buffer ) { return NULL; } /** Reallocates a buffer of a specified memory type. Allocates and zeros the number bytes specified by NewSize from memory of the type specified by PoolType. If OldBuffer is not NULL, then the smaller of OldSize and NewSize bytes are copied from OldBuffer to the newly allocated buffer, and OldBuffer is freed. A pointer to the newly allocated buffer is returned. If NewSize is 0, then a valid buffer of 0 size is returned. If there is not enough memory remaining to satisfy the request, then NULL is returned. If the allocation of the new buffer is successful and the smaller of NewSize and OldSize is greater than (MAX_ADDRESS - OldBuffer + 1), then ASSERT(). @param PoolType The type of pool to allocate. @param OldSize The size, in bytes, of OldBuffer. @param NewSize The size, in bytes, of the buffer to reallocate. @param OldBuffer The buffer to copy to the allocated buffer. This is an optional parameter that may be NULL. @return A pointer to the allocated buffer or NULL if allocation fails. **/ VOID * InternalReallocatePool ( IN EFI_MEMORY_TYPE PoolType, IN UINTN OldSize, IN UINTN NewSize, IN VOID *OldBuffer OPTIONAL ) { VOID *NewBuffer; NewBuffer = InternalAllocateZeroPool (PoolType, NewSize); if (NewBuffer != NULL && OldBuffer != NULL) { CopyMem (NewBuffer, OldBuffer, MIN (OldSize, NewSize)); FreePool (OldBuffer); } return NewBuffer; } /** Reallocates a buffer of type EfiRuntimeServicesData. Allocates and zeros the number bytes specified by NewSize from memory of type EfiRuntimeServicesData. If OldBuffer is not NULL, then the smaller of OldSize and NewSize bytes are copied from OldBuffer to the newly allocated buffer, and OldBuffer is freed. A pointer to the newly allocated buffer is returned. If NewSize is 0, then a valid buffer of 0 size is returned. If there is not enough memory remaining to satisfy the request, then NULL is returned. If the allocation of the new buffer is successful and the smaller of NewSize and OldSize is greater than (MAX_ADDRESS - OldBuffer + 1), then ASSERT(). @param OldSize The size, in bytes, of OldBuffer. @param NewSize The size, in bytes, of the buffer to reallocate. @param OldBuffer The buffer to copy to the allocated buffer. This is an optional parameter that may be NULL. @return A pointer to the allocated buffer or NULL if allocation fails. **/ VOID * EFIAPI ReallocatePool ( IN UINTN OldSize, IN UINTN NewSize, IN VOID *OldBuffer OPTIONAL ) { VOID *Buffer; Buffer = InternalReallocatePool (EfiRuntimeServicesData, OldSize, NewSize, OldBuffer); if (Buffer != NULL) { MemoryProfileLibRecord ( (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), MEMORY_PROFILE_ACTION_LIB_REALLOCATE_POOL, EfiRuntimeServicesData, Buffer, NewSize, NULL ); } return Buffer; } /** Reallocates a buffer of type EfiRuntimeServicesData. Allocates and zeros the number bytes specified by NewSize from memory of type EfiRuntimeServicesData. If OldBuffer is not NULL, then the smaller of OldSize and NewSize bytes are copied from OldBuffer to the newly allocated buffer, and OldBuffer is freed. A pointer to the newly allocated buffer is returned. If NewSize is 0, then a valid buffer of 0 size is returned. If there is not enough memory remaining to satisfy the request, then NULL is returned. If the allocation of the new buffer is successful and the smaller of NewSize and OldSize is greater than (MAX_ADDRESS - OldBuffer + 1), then ASSERT(). @param OldSize The size, in bytes, of OldBuffer. @param NewSize The size, in bytes, of the buffer to reallocate. @param OldBuffer The buffer to copy to the allocated buffer. This is an optional parameter that may be NULL. @return A pointer to the allocated buffer or NULL if allocation fails. **/ VOID * EFIAPI ReallocateRuntimePool ( IN UINTN OldSize, IN UINTN NewSize, IN VOID *OldBuffer OPTIONAL ) { VOID *Buffer; Buffer = InternalReallocatePool (EfiRuntimeServicesData, OldSize, NewSize, OldBuffer); if (Buffer != NULL) { MemoryProfileLibRecord ( (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), MEMORY_PROFILE_ACTION_LIB_REALLOCATE_RUNTIME_POOL, EfiRuntimeServicesData, Buffer, NewSize, NULL ); } return Buffer; } /** Reallocates a buffer of type EfiReservedMemoryType. Allocates and zeros the number bytes specified by NewSize from memory of type EfiReservedMemoryType. If OldBuffer is not NULL, then the smaller of OldSize and NewSize bytes are copied from OldBuffer to the newly allocated buffer, and OldBuffer is freed. A pointer to the newly allocated buffer is returned. If NewSize is 0, then a valid buffer of 0 size is returned. If there is not enough memory remaining to satisfy the request, then NULL is returned. If the allocation of the new buffer is successful and the smaller of NewSize and OldSize is greater than (MAX_ADDRESS - OldBuffer + 1), then ASSERT(). @param OldSize The size, in bytes, of OldBuffer. @param NewSize The size, in bytes, of the buffer to reallocate. @param OldBuffer The buffer to copy to the allocated buffer. This is an optional parameter that may be NULL. @return A pointer to the allocated buffer or NULL if allocation fails. **/ VOID * EFIAPI ReallocateReservedPool ( IN UINTN OldSize, IN UINTN NewSize, IN VOID *OldBuffer OPTIONAL ) { return NULL; } /** Frees a buffer that was previously allocated with one of the pool allocation functions in the Memory Allocation Library. Frees the buffer specified by Buffer. Buffer must have been allocated on a previous call to the pool allocation services of the Memory Allocation Library. If it is not possible to free pool resources, then this function will perform no actions. If Buffer was not allocated with a pool allocation function in the Memory Allocation Library, then ASSERT(). @param Buffer The pointer to the buffer to free. **/ VOID EFIAPI FreePool ( IN VOID *Buffer ) { EFI_STATUS Status; if (BufferInSmram (Buffer)) { // // When Buffer is in SMRAM range, it should be allocated by gSmst->SmmAllocatePool() service. // So, gSmst->SmmFreePool() service is used to free it. // Status = gSmst->SmmFreePool (Buffer); } else { // // When Buffer is out of SMRAM range, it should be allocated by gBS->AllocatePool() service. // So, gBS->FreePool() service is used to free it. // Status = gBS->FreePool (Buffer); } ASSERT_EFI_ERROR (Status); }
MattDevo/edk2
MdeModulePkg/Library/SmmMemoryAllocationProfileLib/MemoryAllocationLib.c
C
bsd-2-clause
36,890
/* * F.DomEvent contains functions for working with DOM events. * Inspired by John Resig, Dean Edwards and YUI addEvent implementations. */ var eventsKey = '_findhit_events'; F.DomEvent = { on: function (obj, types, a, b, c) { if (typeof types === 'object') { for (var type in types) { this._on(obj, type, types[type], a); } } else { types = F.Util.splitWords(types); for (var i = 0, len = types.length; i < len; i++) { this._on(obj, types[i], a, b, c); } } return this; }, once: function ( obj, types, fn, context){ var that = this; types = types.split(' '); for( var i in types ){ if( types[i] === '' ) continue; var type = types[i]; this.on(obj, type, function (e){ fn.call( context || obj, e ); that.off(obj, type, arguments.callee); },context); } return this; }, off: function (obj, types, fn, context) { if (typeof types === 'object') { for (var type in types) { this._off(obj, type, types[type], fn); } } else { types = F.Util.splitWords(types); for (var i = 0, len = types.length; i < len; i++) { this._off(obj, types[i], fn, context); } } return this; }, fire: function ( el, type, ext){ if (document.createEvent) { e = document.createEvent("HTMLEvents"); e.initEvent(type, true, true); } else { e = document.createEventObject(); e.eventType = type; } if(typeof ext == 'object') F.Util.extend(e,ext); e.eventName = type; if (document.createEvent) { el.dispatchEvent(e); } else { el.fireEvent("on" + type, e); } return e; }, fireOn: function ( el, interval, type, ext) { if ( ! interval || ! parseInt( interval ) > 0 || ! type ) return this; var that = this; setTimeout( function () { that.fire( el, type, ext ); }, interval ); return this; }, _on: function (obj, type, fn, context) { // But it could be (HTMLElement, String, String, Function[, Object]) if( arguments.length > 3 && typeof arguments[2] == 'string' ){ // change variables var filter = arguments[2], fn = arguments[3], context = arguments[4] || undefined; } var id = type + F.stamp(fn) + (context ? '_' + F.stamp(context) : ''); if (obj[eventsKey] && obj[eventsKey][id]) { return this; } var handler = function (e) { // If we have a filter and the target doesn't match our filter, return if( filter ){ if( e.target.matches(filter) ) { e.filterTarget = e.target; fn.call(context || e.filterTarget, e || window.event); } // Now check parents e.target.parents( filter ).each(function (){ e.filterTarget = this; fn.call(context || e.filterTarget, e || window.event); }); return; } return fn.call(context || obj, e || window.event); }; var originalHandler = handler; if (F.Browser.pointer && type.indexOf('touch') === 0) { return this.addPointerListener(obj, type, handler, id); } if (F.Browser.touch && (type === 'dblclick') && this.addDoubleTapListener) { this.addDoubleTapListener(obj, handler, id); } if ('addEventListener' in obj) { if (type === 'mousewheel') { obj.addEventListener('DOMMouseScroll', handler, false); obj.addEventListener(type, handler, false); } else if ((type === 'mouseenter') || (type === 'mouseleave')) { handler = function (e) { e = e || window.event; if (!F.DomEvent._checkMouse(obj, e)) { return; } return originalHandler(e); }; obj.addEventListener(type === 'mouseenter' ? 'mouseover' : 'mouseout', handler, false); } else { if (type === 'click' && F.Browser.android) { handler = function (e) { return F.DomEvent._filterClick(e, originalHandler); }; } obj.addEventListener(type, handler, false); } } else if ('attachEvent' in obj) { obj.attachEvent('on' + type, handler); } obj[eventsKey] = obj[eventsKey] || {}; obj[eventsKey][id] = handler; return this; }, _off: function (obj, type, fn, context) { var id = type + F.stamp(fn) + (context ? '_' + F.stamp(context) : ''), handler = obj[eventsKey] && obj[eventsKey][id]; if (!handler) { return this; } if (F.Browser.pointer && type.indexOf('touch') === 0) { this.removePointerListener(obj, type, id); } else if (F.Browser.touch && (type === 'dblclick') && this.removeDoubleTapListener) { this.removeDoubleTapListener(obj, id); } else if ('removeEventListener' in obj) { if (type === 'mousewheel') { obj.removeEventListener('DOMMouseScroll', handler, false); obj.removeEventListener(type, handler, false); } else { obj.removeEventListener( type === 'mouseenter' ? 'mouseover' : type === 'mouseleave' ? 'mouseout' : type, handler, false); } } else if ('detachEvent' in obj) { obj.detachEvent('on' + type, handler); } obj[eventsKey][id] = null; return this; }, stopPropagation: function (e) { if (e.stopPropagation) { e.stopPropagation(); } else { e.cancelBubble = true; } F.DomEvent._skipped(e); return this; }, disableScrollPropagation: function (el) { return F.DomEvent.on(el, 'mousewheel MozMousePixelScroll', F.DomEvent.stopPropagation); }, disableClickPropagation: function (el) { var stop = F.DomEvent.stopPropagation; F.DomEvent.on(el, F.Dom.Draggable.START.join(' '), stop); return F.DomEvent.on(el, { click: F.DomEvent._fakeStop, dblclick: stop }); }, preventDefault: function (e) { if (e.preventDefault) { e.preventDefault(); } else { e.returnValue = false; } return this; }, stop: function (e) { return F.DomEvent .preventDefault(e) .stopPropagation(e); }, getMousePosition: function (e, container) { if (!container) { return new F.Leaflet.Point(e.clientX, e.clientY); } var rect = container.getBoundingClientRect(); return new F.Leaflet.Point( e.clientX - rect.left - container.clientLeft, e.clientY - rect.top - container.clientTop); }, getWheelDelta: function (e) { var delta = 0; if (e.wheelDelta) { delta = e.wheelDelta / 120; } if (e.detail) { delta = -e.detail / 3; } return delta; }, _skipEvents: {}, _fakeStop: function (e) { // fakes stopPropagation by setting a special event flag, checked/reset with F.DomEvent._skipped(e) F.DomEvent._skipEvents[e.type] = true; }, _skipped: function (e) { var skipped = this._skipEvents[e.type]; // reset when checking, as it's only used in map container and propagates outside of the map this._skipEvents[e.type] = false; return skipped; }, // check if element really left/entered the event target (for mouseenter/mouseleave) _checkMouse: function (el, e) { var related = e.relatedTarget; if (!related) { return true; } try { while (related && (related !== el)) { related = related.parentNode; } } catch (err) { return false; } return (related !== el); }, // this is a horrible workaround for a bug in Android where a single touch triggers two click events _filterClick: function (e, handler) { var timeStamp = (e.timeStamp || e.originalEvent.timeStamp), elapsed = F.DomEvent._lastClick && (timeStamp - F.DomEvent._lastClick); // are they closer together than 500ms yet more than 100ms? // Android typically triggers them ~300ms apart while multiple listeners // on the same event should be triggered far faster; // or check if click is simulated on the element, and if it is, reject any non-simulated events if ((elapsed && elapsed > 100 && elapsed < 500) || (e.target._simulatedClick && !e._simulated)) { F.DomEvent.stop(e); return; } F.DomEvent._lastClick = timeStamp; return handler(e); } }; F.DomEvent.addListener = F.DomEvent.on; F.DomEvent.removeListener = F.DomEvent.off; F.DomEvent.addOnceListener = F.DomEvent.once; F.DomEvent.trigger = F.DomEvent.dispatch = F.DomEvent.fire; F.DomEvent.triggerOn = F.DomEvent.dispatchOn = F.DomEvent.fireOn; (function () { var proxy = function (fn, el, oarguments){ if( typeof fn != 'string' || typeof el != 'object' || typeof oarguments != 'object' || typeof F.DomEvent[fn] != 'function' ) return false; // Prepend el to arguments var args = [el]; for( var i in oarguments ) args.push(oarguments[i]); var res = F.DomEvent[fn].apply(F.DomEvent, args); return ( res != F.DomEvent ) ? res : el; }; F.Proto.Doc.on = F.Proto.Doc.addListener = F.Proto.Elem.on = F.Proto.Elem.addListener = F.Proto.Win.on = F.Proto.Win.addListener = function (){ return proxy('on',this,arguments); }; F.Proto.Doc.off = F.Proto.Doc.removeListener = F.Proto.Elem.off = F.Proto.Elem.removeListener = F.Proto.Win.off = F.Proto.Win.removeListener = function (){ return proxy('off',this,arguments); }; F.Proto.Doc.once = F.Proto.Doc.addOnceListener = F.Proto.Elem.once = F.Proto.Elem.addOnceListener = F.Proto.Win.once = F.Proto.Win.addOnceListener = function (){ return proxy('once',this,arguments); }; F.Proto.Doc.fire = F.Proto.Doc.trigger = F.Proto.Doc.dispatch = F.Proto.Elem.fire = F.Proto.Elem.trigger = F.Proto.Elem.dispatch = F.Proto.Win.fire = F.Proto.Win.trigger = F.Proto.Win.dispatch = function (){ return proxy('fire',this,arguments); }; F.Proto.Doc.fireOn = F.Proto.Doc.triggerOn = F.Proto.Doc.dispatchOn = F.Proto.Elem.fireOn = F.Proto.Elem.triggerOn = F.Proto.Elem.dispatchOn = F.Proto.Win.fireOn = F.Proto.Win.triggerOn = F.Proto.Win.dispatchOn = function (){ return proxy('fireOn',this,arguments); }; }());
gabrielpconceicao/frontend-asset-leaflet
src/dom/DomEvent.js
JavaScript
bsd-2-clause
9,864
/** * @file * @author Alexander Sherikov */ #include <iostream> #include <fstream> #include <cstdio> #include <limits> #include <cmath> // abs, M_PI #include <cstring> //strcmp #include "WMG.h" #include "smpc_solver.h" #include "nao_igm.h" #include "joints_sensors_id.h" using namespace std; #include "init_steps_nao.cpp" #include "tests_common.cpp" int main(int argc, char **argv) { //----------------------------------------------------------- // sampling int control_sampling_time_ms = 20; int preview_sampling_time_ms = 40; int next_preview_len_ms = 0; //----------------------------------------------------------- //----------------------------------------------------------- // initialize classes // init_09 tdata("test_07", preview_sampling_time_ms, false); init_10 tdata("test_07", preview_sampling_time_ms, true); smpc::solver_as solver( tdata.wmg->N, // size of the preview window 4000.0, 1.0, 0.02, 1.0, 1e-7); // tolerance //----------------------------------------------------------- //----------------------------------------------------------- tdata.nao.getCoM(tdata.nao.state_sensor, tdata.nao.CoM_position); tdata.par->init_state.set (tdata.nao.CoM_position[0], tdata.nao.CoM_position[1]); tdata.X_tilde.set (tdata.nao.CoM_position[0], tdata.nao.CoM_position[1]); //----------------------------------------------------------- //----------------------------------------------------------- // output test_log log(tdata.fs_out_filename.c_str()); //----------------------------------------------------------- tdata.wmg->T_ms[0] = control_sampling_time_ms; tdata.wmg->T_ms[1] = control_sampling_time_ms; for(int i=0 ;; i++) { tdata.nao.state_sensor = tdata.nao.state_model; if (tdata.wmg->formPreviewWindow(*tdata.par) == WMG_HALT) { cout << "EXIT (halt = 1)" << endl; break; } for (unsigned int j = 0; j < tdata.wmg->N; j++) { log.addZMPrefPoint(tdata.par->zref_x[j], tdata.par->zref_y[j]); } cout << tdata.wmg->isSupportSwitchNeeded() << endl; if (tdata.wmg->isSupportSwitchNeeded()) { tdata.nao.switchSupportFoot(); } //------------------------------------------------------ solver.set_parameters (tdata.par->T, tdata.par->h, tdata.par->h[0], tdata.par->angle, tdata.par->zref_x, tdata.par->zref_y, tdata.par->lb, tdata.par->ub); solver.form_init_fp (tdata.par->fp_x, tdata.par->fp_y, tdata.par->init_state, tdata.par->X); solver.solve(); //----------------------------------------------------------- // update state solver.get_next_state(tdata.par->init_state); //----------------------------------------------------------- //----------------------------------------------------------- // output smpc::state_com state; solver.get_state(state, 1); if (next_preview_len_ms == 0) { next_preview_len_ms = preview_sampling_time_ms; log.addZMPpoint (tdata.X_tilde.x(), tdata.X_tilde.y()); solver.get_state(tdata.X_tilde, 1); } log.addCoMpoint (state.x(), state.y()); next_preview_len_ms -= control_sampling_time_ms; //----------------------------------------------------------- //----------------------------------------------------------- // support foot and swing foot position/orientation tdata.wmg->getFeetPositions ( control_sampling_time_ms, tdata.nao.left_foot_posture.data(), tdata.nao.right_foot_posture.data()); // position of CoM tdata.nao.setCoM(tdata.par->init_state.x(), tdata.par->init_state.y(), tdata.par->hCoM); if (tdata.nao.igm(tdata.ref_angles, 1.2, 0.0015, 20) < 0) { cout << "IGM failed!" << endl; break; } int failed_joint = tdata.nao.state_model.checkJointBounds(); if (failed_joint >= 0) { cout << "MAX or MIN joint limit is violated! Number of the joint: " << failed_joint << endl; break; } //----------------------------------------------------------- //----------------------------------------------------------- // output log.addFeetPositions (tdata.nao); //----------------------------------------------------------- //----------------------------------------------------------- tdata.wmg->getFeetPositions ( 2*control_sampling_time_ms, tdata.nao.left_foot_posture.data(), tdata.nao.right_foot_posture.data()); // position of CoM smpc::state_com next_CoM; solver.get_state (next_CoM, 1); tdata.nao.setCoM(next_CoM.x(), next_CoM.y(), tdata.par->hCoM); if (tdata.nao.igm(tdata.ref_angles, 1.2, 0.0015, 20) < 0) { cout << "IGM failed!" << endl; break; } failed_joint = tdata.nao.state_model.checkJointBounds(); if (failed_joint >= 0) { cout << "MAX or MIN joint limit is violated! Number of the joint: " << failed_joint << endl; break; } //----------------------------------------------------------- } //----------------------------------------------------------- // output log.flushLeftFoot (); log.flushRightFoot (); log.flushZMP (); log.flushZMPref (); log.flushCoM (); //----------------------------------------------------------- return 0; }
asherikov/oru_walk_module
test/test_07.cpp
C++
bsd-2-clause
5,838
using System.Threading; using System.Threading.Tasks; using MatterHackers.MatterControl.PartPreviewWindow; using NUnit.Framework; namespace MatterHackers.MatterControl.Tests.Automation { [TestFixture, Category("MatterControl.UI.Automation"), RunInApplicationDomain, Apartment(ApartmentState.STA)] public class SqLiteLibraryProviderTests { [Test] public async Task LibraryQueueViewRefreshesOnAddItem() { await MatterControlUtilities.RunTest((testRunner) => { testRunner.OpenEmptyPartTab(); testRunner.AddItemToBedplate(); var view3D = testRunner.GetWidgetByName("View3DWidget", out _) as View3DWidget; var scene = view3D.InteractionLayer.Scene; testRunner.WaitFor(() => scene.SelectedItem != null); Assert.IsNotNull(scene.SelectedItem, "Expect part selection after Add to Bed action"); testRunner.ClickByName("Duplicate Button"); // wait for the copy to finish testRunner.Delay(.1); testRunner.ClickByName("Remove Button"); testRunner.SaveBedplateToFolder("0Test Part", "Local Library Row Item Collection"); // Click Home -> Local Library testRunner.NavigateToLibraryHome(); testRunner.NavigateToFolder("Local Library Row Item Collection"); // ensure that it is now in the library folder (that the folder updated) Assert.IsTrue(testRunner.WaitForName("Row Item 0Test Part"), "The part we added should be in the library"); testRunner.Delay(.5); return Task.CompletedTask; }, queueItemFolderToAdd: QueueTemplate.Three_Queue_Items, overrideWidth: 1300); } } }
unlimitedbacon/MatterControl
Tests/MatterControl.AutomationTests/SqLiteLibraryProvider.cs
C#
bsd-2-clause
1,562
class Nvc < Formula desc "VHDL compiler and simulator" homepage "https://github.com/nickg/nvc" url "https://github.com/nickg/nvc/releases/download/r1.2.1/nvc-1.2.1.tar.gz" sha256 "ff6b1067a665c6732286239e539ae448a52bb11e9ea193569af1c147d0b4fce0" bottle do sha256 "f11933a05847b9433fd505c03755767043872e145f247b7d87603e3a9dc51dc4" => :high_sierra sha256 "23b8d156e8ee517b80e7736eeb31bfa3ac59e30bbdca157b53320b8cf987b633" => :sierra sha256 "fec8eab13df57ffec18283f6a83366afcf431640f9e25142a4da04f63e43e2bf" => :el_capitan sha256 "f33ffc17ef6123f97750b76fddedbb6ba3865fab02ebbca04c7441631740092d" => :yosemite end head do url "https://github.com/nickg/nvc.git" depends_on "autoconf" => :build depends_on "automake" => :build end depends_on "pkg-config" => :build depends_on "llvm" => :build depends_on "check" => :build resource "vim-hdl-examples" do url "https://github.com/suoto/vim-hdl-examples.git", :revision => "c112c17f098f13719784df90c277683051b61d05" end def install system "./autogen.sh" if build.head? system "./tools/fetch-ieee.sh" system "./configure", "--with-llvm=#{Formula["llvm"].opt_bin}/llvm-config", "--prefix=#{prefix}" system "make" system "make", "install" end test do resource("vim-hdl-examples").stage testpath system "#{bin}/nvc", "-a", "#{testpath}/basic_library/very_common_pkg.vhd" end end
bfontaine/homebrew-core
Formula/nvc.rb
Ruby
bsd-2-clause
1,451
package sql import ( "bytes" "os" "path" "strconv" "testing" "github.com/repbin/repbin/utils/repproto/structs" ) var testBlobMessage = &structs.MessageStruct{ ReceiverConstantPubKey: *testReceiverPubKey, MessageID: *sliceToMessageID([]byte( strconv.Itoa( int( CurrentTime(), ), ) + "MessageBlob", )), SignerPub: *sliceToEDPublicKey([]byte( strconv.Itoa( int( CurrentTime(), ), ) + "SignerBlob", )), PostTime: 10, ExpireTime: uint64(CurrentTime() + 1000), ExpireRequest: 291090912, Distance: 2, OneTime: false, Sync: true, Hidden: false, } var testMessageBlob = &MessageBlob{ // ID uint64 // numeric ID, local unique MessageID: testBlobMessage.MessageID, SignerPublicKey: testBlobMessage.SignerPub, OneTime: false, Data: bytes.Repeat([]byte{0x00, 0xff, 0x01, 0x03, 0x07, 0x13, 0x23, 0x40}, 65536), } func TestBlobMysql(t *testing.T) { if !testing.Short() { dir := "" //path.Join(os.TempDir(), "repbinmsg") db, err := newMySQLForTest(dir, 100) if err != nil { t.Fatalf("New Mysql: %s", err) } defer db.Close() testMessageBlob.ID, err = db.InsertMessage(testBlobMessage) if err != nil { t.Errorf("InsertMessage: %s", err) } err = db.InsertBlobStruct(testMessageBlob) if err != nil { t.Errorf("InsertBlobStruct: %s", err) } testBlobRes, err := db.GetBlobDB(&testMessageBlob.MessageID) if err != nil { t.Errorf("GetBlob: %s", err) } if testMessageBlob.ID != testBlobRes.ID { t.Errorf("ID mismatch: %d != %d", testMessageBlob.ID, testBlobRes.ID) } if testMessageBlob.MessageID != testBlobRes.MessageID { t.Errorf("MessageID mismatch: %x != %x", testMessageBlob.MessageID, testBlobRes.MessageID) } if testMessageBlob.SignerPublicKey != testBlobRes.SignerPublicKey { t.Errorf("SignerPublicKey mismatch: %x != %x", testMessageBlob.SignerPublicKey, testBlobRes.SignerPublicKey) } if testMessageBlob.OneTime != testBlobRes.OneTime { t.Errorf("OneTime mismatch: %t != %t", testMessageBlob.OneTime, testBlobRes.OneTime) } if !bytes.Equal(testMessageBlob.Data, testBlobRes.Data) { t.Errorf("Data mismatch: %d != %d", len(testMessageBlob.Data), len(testBlobRes.Data)) } err = db.DeleteBlobDB(&testMessageBlob.MessageID) if err != nil { t.Errorf("DeleteBlob: %s", err) } _, err = db.GetBlobDB(&testMessageBlob.MessageID) if err == nil { t.Error("GetBlob must fail on deleted message") } } } func TestBlobSQLite(t *testing.T) { dir := "" //path.Join(os.TempDir(), "repbinmsg") dbFile := path.Join(os.TempDir(), "db.test-blob") db, err := New("sqlite3", dbFile, dir, 100) if err != nil { t.Fatalf("New sqlite3: %s", err) } defer os.Remove(dbFile) defer db.Close() testMessageBlob.ID, err = db.InsertMessage(testBlobMessage) if err != nil { t.Errorf("InsertMessage: %s", err) } err = db.InsertBlobStruct(testMessageBlob) if err != nil { t.Errorf("InsertBlobStruct: %s", err) } testBlobRes, err := db.GetBlobDB(&testMessageBlob.MessageID) if err != nil { t.Errorf("GetBlob: %s", err) } if testMessageBlob.ID != testBlobRes.ID { t.Errorf("ID mismatch: %d != %d", testMessageBlob.ID, testBlobRes.ID) } if testMessageBlob.MessageID != testBlobRes.MessageID { t.Errorf("MessageID mismatch: %x != %x", testMessageBlob.MessageID, testBlobRes.MessageID) } if testMessageBlob.SignerPublicKey != testBlobRes.SignerPublicKey { t.Errorf("SignerPublicKey mismatch: %x != %x", testMessageBlob.SignerPublicKey, testBlobRes.SignerPublicKey) } if testMessageBlob.OneTime != testBlobRes.OneTime { t.Errorf("OneTime mismatch: %t != %t", testMessageBlob.OneTime, testBlobRes.OneTime) } if !bytes.Equal(testMessageBlob.Data, testBlobRes.Data) { t.Errorf("Data mismatch: %d != %d", len(testMessageBlob.Data), len(testBlobRes.Data)) } err = db.DeleteBlobDB(&testMessageBlob.MessageID) if err != nil { t.Errorf("DeleteBlob: %s", err) } _, err = db.GetBlobDB(&testMessageBlob.MessageID) if err == nil { t.Error("GetBlob must fail on deleted message") } } func TestBlobDirSQLite(t *testing.T) { dir := path.Join(os.TempDir(), "repbinmsg") dbFile := path.Join(os.TempDir(), "db.test-blobdir") db, err := New("sqlite3", dbFile, dir, 100) if err != nil { t.Fatalf("New sqlite3: %s", err) } defer os.Remove(dbFile) defer db.Close() testMessageBlob.ID, err = db.InsertMessage(testBlobMessage) if err != nil { t.Errorf("InsertMessage: %s", err) } err = db.InsertBlobStruct(testMessageBlob) if err != nil { t.Errorf("InsertBlobStruct: %s", err) } testBlobRes, err := db.GetBlob(&testMessageBlob.MessageID) if err != nil { t.Errorf("GetBlob: %s", err) } if testMessageBlob.ID != testBlobRes.ID { t.Errorf("ID mismatch: %d != %d", testMessageBlob.ID, testBlobRes.ID) } if testMessageBlob.MessageID != testBlobRes.MessageID { t.Errorf("MessageID mismatch: %x != %x", testMessageBlob.MessageID, testBlobRes.MessageID) } if testMessageBlob.SignerPublicKey != testBlobRes.SignerPublicKey { t.Errorf("SignerPublicKey mismatch: %x != %x", testMessageBlob.SignerPublicKey, testBlobRes.SignerPublicKey) } if testMessageBlob.OneTime != testBlobRes.OneTime { t.Errorf("OneTime mismatch: %t != %t", testMessageBlob.OneTime, testBlobRes.OneTime) } if !bytes.Equal(testMessageBlob.Data, testBlobRes.Data) { t.Errorf("Data mismatch: %d != %d", len(testMessageBlob.Data), len(testBlobRes.Data)) } err = db.DeleteBlobFS(&testMessageBlob.MessageID) if err != nil { t.Errorf("DeleteBlob: %s", err) } _, err = db.GetBlob(&testMessageBlob.MessageID) if err == nil { t.Error("GetBlob must fail on deleted message") } }
xeddmc/repbin
cmd/repserver/messagestore/sql/blob_test.go
GO
bsd-2-clause
5,707
from collections import namedtuple from weakref import finalize as _finalize from numba.core.runtime import nrtdynmod from llvmlite import binding as ll from numba.core.compiler_lock import global_compiler_lock from numba.core.typing.typeof import typeof_impl from numba.core import types from numba.core.runtime import _nrt_python as _nrt _nrt_mstats = namedtuple("nrt_mstats", ["alloc", "free", "mi_alloc", "mi_free"]) class _Runtime(object): def __init__(self): self._init = False @global_compiler_lock def initialize(self, ctx): """Initializes the NRT Must be called before any actual call to the NRT API. Safe to be called multiple times. """ if self._init: # Already initialized return # Register globals into the system for py_name in _nrt.c_helpers: c_name = "NRT_" + py_name c_address = _nrt.c_helpers[py_name] ll.add_symbol(c_name, c_address) # Compile atomic operations self._library = nrtdynmod.compile_nrt_functions(ctx) self._ptr_inc = self._library.get_pointer_to_function("nrt_atomic_add") self._ptr_dec = self._library.get_pointer_to_function("nrt_atomic_sub") self._ptr_cas = self._library.get_pointer_to_function("nrt_atomic_cas") # Install atomic ops to NRT _nrt.memsys_set_atomic_inc_dec(self._ptr_inc, self._ptr_dec) _nrt.memsys_set_atomic_cas(self._ptr_cas) self._init = True def _init_guard(self): if not self._init: msg = "Runtime must be initialized before use." raise RuntimeError(msg) @staticmethod def shutdown(): """ Shutdown the NRT Safe to be called without calling Runtime.initialize first """ _nrt.memsys_shutdown() @property def library(self): """ Return the Library object containing the various NRT functions. """ self._init_guard() return self._library def meminfo_new(self, data, pyobj): """ Returns a MemInfo object that tracks memory at `data` owned by `pyobj`. MemInfo will acquire a reference on `pyobj`. The release of MemInfo will release a reference on `pyobj`. """ self._init_guard() mi = _nrt.meminfo_new(data, pyobj) return MemInfo(mi) def meminfo_alloc(self, size, safe=False): """ Allocate a new memory of `size` bytes and returns a MemInfo object that tracks the allocation. When there is no more reference to the MemInfo object, the underlying memory will be deallocated. If `safe` flag is True, the memory is allocated using the `safe` scheme. This is used for debugging and testing purposes. See `NRT_MemInfo_alloc_safe()` in "nrt.h" for details. """ self._init_guard() if safe: mi = _nrt.meminfo_alloc_safe(size) else: mi = _nrt.meminfo_alloc(size) return MemInfo(mi) def get_allocation_stats(self): """ Returns a namedtuple of (alloc, free, mi_alloc, mi_free) for count of each memory operations. """ # No init guard needed to access stats members return _nrt_mstats(alloc=_nrt.memsys_get_stats_alloc(), free=_nrt.memsys_get_stats_free(), mi_alloc=_nrt.memsys_get_stats_mi_alloc(), mi_free=_nrt.memsys_get_stats_mi_free()) # Alias to _nrt_python._MemInfo MemInfo = _nrt._MemInfo @typeof_impl.register(MemInfo) def typeof_meminfo(val, c): return types.MemInfoPointer(types.voidptr) # Create runtime _nrt.memsys_use_cpython_allocator() rtsys = _Runtime() # Install finalizer _finalize(rtsys, _Runtime.shutdown) # Avoid future use of the class del _Runtime
gmarkall/numba
numba/core/runtime/nrt.py
Python
bsd-2-clause
3,908
#!/usr/bin/perl -w # # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2008 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # #pragma ident "%Z%%M% %I% %E% SMI" # # get.ipv4remote.pl [tcpport] # # Find an IPv4 reachable remote host using both ifconfig(1M) and ping(1M). # If a tcpport is specified, return a host that is also listening on this # TCP port. Print the local address and the remote address, or an # error message if no suitable remote host was found. Exit status is 0 if # a host was found. # use strict; use IO::Socket; my $MAXHOSTS = 32; # max hosts to port scan my $TIMEOUT = 3; # connection timeout my $tcpport = @ARGV == 1 ? $ARGV[0] : 0; # # Determine local IP address # my $local = ""; my $remote = ""; my %Broadcast; my $up; open IFCONFIG, '/sbin/ifconfig -a |' or die "Couldn't run ifconfig: $!\n"; while (<IFCONFIG>) { next if /^lo/; # "UP" is always printed first (see print_flags() in ifconfig.c): $up = 1 if /^[a-z].*<UP,/; $up = 0 if /^[a-z].*<,/; # assume output is "inet X ... broadcast Z": if (/inet (\S+) .* broadcast (\S+)/) { my ($addr, $bcast) = ($1, $2); $Broadcast{$addr} = $bcast; $local = $addr if $up and $local eq ""; $up = 0; } } close IFCONFIG; die "Could not determine local IP address" if $local eq ""; # # Find the first remote host that responds to an icmp echo, # which isn't a local address. # open PING, "/sbin/ping -n -s 56 -c $MAXHOSTS $Broadcast{$local} |" or die "Couldn't run ping: $!\n"; while (<PING>) { if (/bytes from (.*): / and not defined $Broadcast{$1}) { my $addr = $1; if ($tcpport != 0) { # # Test TCP # my $socket = IO::Socket::INET->new( Proto => "tcp", PeerAddr => $addr, PeerPort => $tcpport, Timeout => $TIMEOUT, ); next unless $socket; close $socket; } $remote = $addr; last; } } close PING; die "Can't find a remote host for testing: No suitable response from " . "$Broadcast{$local}\n" if $remote eq ""; print "$local $remote\n";
dplbsd/soc2013
head/cddl/contrib/opensolaris/cmd/dtrace/test/tst/common/ip/get.ipv4remote.pl
Perl
bsd-2-clause
2,789
/* Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ using System.Collections.Generic; using XenAdmin.Actions; using XenAdmin.Core; using XenAPI; using XenAdmin.Dialogs; namespace XenAdmin.Commands { /// <summary> /// Destroys the selected SRs. Shows a confirmation dialog. /// </summary> internal class DestroySRCommand : Command { /// <summary> /// Initializes a new instance of this Command. The parameter-less constructor is required in the derived /// class if it is to be attached to a ToolStrip menu item or button. It should not be used in any other scenario. /// </summary> public DestroySRCommand() { } public DestroySRCommand(IMainWindow mainWindow, IEnumerable<SelectedItem> selection) : base(mainWindow, selection) { } public DestroySRCommand(IMainWindow mainWindow, SR selection) : base(mainWindow, selection) { } public DestroySRCommand(IMainWindow mainWindow, IEnumerable<SR> selection) : base(mainWindow, ConvertToSelection(selection)) { } protected override void ExecuteCore(SelectedItemCollection selection) { List<AsyncAction> actions = new List<AsyncAction>(); foreach (SR sr in selection.AsXenObjects<SR>(CanExecute)) { actions.Add(new SrAction(SrActionKind.Destroy, sr)); } RunMultipleActions(actions, Messages.ACTION_SRS_DESTROYING, string.Empty, string.Empty, true); } protected override bool CanExecuteCore(SelectedItemCollection selection) { return selection.AllItemsAre<SR>() && selection.AtLeastOneXenObjectCan<SR>(CanExecute); } private static bool CanExecute(SR sr) { return sr != null && !sr.HasRunningVMs() && sr.CanCreateWithXenCenter && sr.allowed_operations.Contains(storage_operations.destroy) && !HelpersGUI.GetActionInProgress(sr); } /// <summary> /// Gets the text for a menu item which launches this Command. /// </summary> public override string MenuText { get { return Messages.MAINWINDOW_DESTROY_SR; } } protected override bool ConfirmationRequired { get { return true; } } protected override string ConfirmationDialogText { get { List<SR> srs = GetSelection().AsXenObjects<SR>(); if (srs.Count == 1) { return string.Format(Messages.MESSAGEBOX_DESTROY_SR_CONTINUE, srs[0].Name); } return Messages.MESSAGEBOX_DESTROY_SRS_CONTINUE; } } protected override string ConfirmationDialogTitle { get { if (GetSelection().Count == 1) { return Messages.MESSAGEBOX_DESTROY_SR_CONTINUE_TITLE; } return Messages.MESSAGEBOX_DESTROY_SRS_CONTINUE_TITLE; } } protected override CommandErrorDialog GetErrorDialogCore(IDictionary<SelectedItem, string> cantExecuteReasons) { return new CommandErrorDialog(Messages.ERROR_DIALOG_DESTROY_SR_TITLE, Messages.ERROR_DIALOG_DESTROY_SR_TEXT, cantExecuteReasons); } protected override string GetCantExecuteReasonCore(SelectedItem item) { SR sr = item.XenObject as SR; if (sr == null) { return base.GetCantExecuteReasonCore(item); } if (!sr.HasPBDs) { return Messages.SR_DETACHED; } else if (sr.HasRunningVMs()) { return Messages.SR_HAS_RUNNING_VMS; } else if (!sr.CanCreateWithXenCenter) { return Messages.SR_CANNOT_BE_DESTROYED_WITH_XC; } else if (HelpersGUI.GetActionInProgress(sr)) { return Messages.SR_ACTION_IN_PROGRESS; } return base.GetCantExecuteReasonCore(item); } protected override string ConfirmationDialogYesButtonLabel { get { return Messages.MESSAGEBOX_DESTROY_SR_YES_BUTTON_LABEL; } } protected override bool ConfirmationDialogNoButtonSelected { get { return true; } } } }
ushamandya/xenadmin
XenAdmin/Commands/DestroySRCommand.cs
C#
bsd-2-clause
6,284
import sys import unittest from dynd import nd, ndt @unittest.skip('Test disabled since callables were reworked') class TestArraySetItem(unittest.TestCase): def test_strided_dim(self): a = nd.empty(100, ndt.int32) a[...] = nd.range(100) a[0] = 1000 self.assertEqual(nd.as_py(a[0]), 1000) a[1:8:3] = 120 self.assertEqual(nd.as_py(a[:11]), [1000, 120, 2, 3, 120, 5, 6, 120, 8, 9, 10]) a[5:2:-1] = [-10, -20, -30] self.assertEqual(nd.as_py(a[:11]), [1000, 120, 2, -30, -20, -10, 6, 120, 8, 9, 10]) a[1] = False self.assertEqual(nd.as_py(a[1]), 0) a[2] = True self.assertEqual(nd.as_py(a[2]), 1) a[3] = -10.0 self.assertEqual(nd.as_py(a[3]), -10) # Should the following even be supported? # a[4] = 101.0 + 0j # self.assertEqual(nd.as_py(a[4]), 101) """ Todo: Fix this test when structs can assign to named tuples. def test_assign_to_struct(self): value = [(8, u'world', 4.5), (16, u'!', 8.75)] # Assign list of tuples a = nd.empty('2 * { i : int32, msg : string, price : float64 }') a[:] = value self.assertEqual(nd.as_py(a), value) # Assign iterator of tuples a = nd.empty('2 * { i : int32, msg : string, price : float64 }') a[:] = iter(value) self.assertEqual(nd.as_py(a, tuple=True), value) """ if __name__ == '__main__': unittest.main(verbosity=2)
ContinuumIO/dynd-python
dynd/nd/test/test_array_setitem.py
Python
bsd-2-clause
1,531
{% extends 'manage/product/base.html' %} {% block content %} <section class="{% block sectionclass %}{% endblock %}"> <h2> {% block sectionhead %}create a new product{% endblock sectionhead %} {% include "_helplink.html" with helpURL="products.html#product-edit-fields" %} </h2> <form id="{% block formid %}{% endblock %}" method="POST" class="manage-form product-form"> {% csrf_token %} {{ form.cc_version }} {{ form.non_field_errors }} {% block fields %} {% include "forms/_field.html" with field=form.name %} {% include "forms/_field.html" with field=form.description %} {% endblock %} {% comment %} <section class="userselect details{% if form.team.errors or form.team.value %} open{% endif %}"> <h3 class="summary">assign specific users to this product &raquo;</h3> <div> {# @@@ needs the slick multiple-select widget #} {% include "forms/_field.html" with field=form.team %} </div> </section> {% endcomment %} <div class="form-actions"> <button type="submit">save product</button> {% url 'manage_products' as manage_url %} {% include "manage/_cancel_button.html" with manage_url=manage_url %} </div> </form> </section> {% endblock content %}
bobsilverberg/moztrap
templates/manage/product/product_form.html
HTML
bsd-2-clause
1,272
/* * Copyright 2018 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. */ extern crate smallvec; use std::cmp::max; use std::marker::PhantomData; use std::ptr::write_bytes; use std::slice::from_raw_parts; use endian_scalar::{emplace_scalar, read_scalar_at}; use primitives::*; use push::{Push, PushAlignment}; use table::Table; use vector::{SafeSliceAccess, Vector}; use vtable::{field_index_to_field_offset, VTable}; use vtable_writer::VTableWriter; pub const N_SMALLVEC_STRING_VECTOR_CAPACITY: usize = 16; #[derive(Clone, Copy, Debug, Eq, PartialEq)] struct FieldLoc { off: UOffsetT, id: VOffsetT, } /// FlatBufferBuilder builds a FlatBuffer through manipulating its internal /// state. It has an owned `Vec<u8>` that grows as needed (up to the hardcoded /// limit of 2GiB, which is set by the FlatBuffers format). #[derive(Clone, Debug, Eq, PartialEq)] pub struct FlatBufferBuilder<'fbb> { owned_buf: Vec<u8>, head: usize, field_locs: Vec<FieldLoc>, written_vtable_revpos: Vec<UOffsetT>, nested: bool, finished: bool, min_align: usize, _phantom: PhantomData<&'fbb ()>, } impl<'fbb> FlatBufferBuilder<'fbb> { /// Create a FlatBufferBuilder that is ready for writing. pub fn new() -> Self { Self::new_with_capacity(0) } /// Create a FlatBufferBuilder that is ready for writing, with a /// ready-to-use capacity of the provided size. /// /// The maximum valid value is `FLATBUFFERS_MAX_BUFFER_SIZE`. pub fn new_with_capacity(size: usize) -> Self { // we need to check the size here because we create the backing buffer // directly, bypassing the typical way of using grow_owned_buf: assert!( size <= FLATBUFFERS_MAX_BUFFER_SIZE, "cannot initialize buffer bigger than 2 gigabytes" ); FlatBufferBuilder { owned_buf: vec![0u8; size], head: size, field_locs: Vec::new(), written_vtable_revpos: Vec::new(), nested: false, finished: false, min_align: 0, _phantom: PhantomData, } } /// Reset the FlatBufferBuilder internal state. Use this method after a /// call to a `finish` function in order to re-use a FlatBufferBuilder. /// /// This function is the only way to reset the `finished` state and start /// again. /// /// If you are using a FlatBufferBuilder repeatedly, make sure to use this /// function, because it re-uses the FlatBufferBuilder's existing /// heap-allocated `Vec<u8>` internal buffer. This offers significant speed /// improvements as compared to creating a new FlatBufferBuilder for every /// new object. pub fn reset(&mut self) { // memset only the part of the buffer that could be dirty: { let to_clear = self.owned_buf.len() - self.head; let ptr = (&mut self.owned_buf[self.head..]).as_mut_ptr(); unsafe { write_bytes(ptr, 0, to_clear); } } self.head = self.owned_buf.len(); self.written_vtable_revpos.clear(); self.nested = false; self.finished = false; self.min_align = 0; } /// Destroy the FlatBufferBuilder, returning its internal byte vector /// and the index into it that represents the start of valid data. pub fn collapse(self) -> (Vec<u8>, usize) { (self.owned_buf, self.head) } /// Push a Push'able value onto the front of the in-progress data. /// /// This function uses traits to provide a unified API for writing /// scalars, tables, vectors, and WIPOffsets. #[inline] pub fn push<P: Push>(&mut self, x: P) -> WIPOffset<P::Output> { let sz = P::size(); self.align(sz, P::alignment()); self.make_space(sz); { let (dst, rest) = (&mut self.owned_buf[self.head..]).split_at_mut(sz); x.push(dst, rest); } WIPOffset::new(self.used_space() as UOffsetT) } /// Push a Push'able value onto the front of the in-progress data, and /// store a reference to it in the in-progress vtable. If the value matches /// the default, then this is a no-op. #[inline] pub fn push_slot<X: Push + PartialEq>(&mut self, slotoff: VOffsetT, x: X, default: X) { self.assert_nested("push_slot"); if x == default { return; } self.push_slot_always(slotoff, x); } /// Push a Push'able value onto the front of the in-progress data, and /// store a reference to it in the in-progress vtable. #[inline] pub fn push_slot_always<X: Push>(&mut self, slotoff: VOffsetT, x: X) { self.assert_nested("push_slot_always"); let off = self.push(x); self.track_field(slotoff, off.value()); } /// Retrieve the number of vtables that have been serialized into the /// FlatBuffer. This is primarily used to check vtable deduplication. #[inline] pub fn num_written_vtables(&self) -> usize { self.written_vtable_revpos.len() } /// Start a Table write. /// /// Asserts that the builder is not in a nested state. /// /// Users probably want to use `push_slot` to add values after calling this. #[inline] pub fn start_table(&mut self) -> WIPOffset<TableUnfinishedWIPOffset> { self.assert_not_nested( "start_table can not be called when a table or vector is under construction", ); self.nested = true; WIPOffset::new(self.used_space() as UOffsetT) } /// End a Table write. /// /// Asserts that the builder is in a nested state. #[inline] pub fn end_table( &mut self, off: WIPOffset<TableUnfinishedWIPOffset>, ) -> WIPOffset<TableFinishedWIPOffset> { self.assert_nested("end_table"); let o = self.write_vtable(off); self.nested = false; self.field_locs.clear(); WIPOffset::new(o.value()) } /// Start a Vector write. /// /// Asserts that the builder is not in a nested state. /// /// Most users will prefer to call `create_vector`. /// Speed optimizing users who choose to create vectors manually using this /// function will want to use `push` to add values. #[inline] pub fn start_vector<T: Push>(&mut self, num_items: usize) { self.assert_not_nested( "start_vector can not be called when a table or vector is under construction", ); self.nested = true; self.align(num_items * T::size(), T::alignment().max_of(SIZE_UOFFSET)); } /// End a Vector write. /// /// Note that the `num_elems` parameter is the number of written items, not /// the byte count. /// /// Asserts that the builder is in a nested state. #[inline] pub fn end_vector<T: Push>(&mut self, num_elems: usize) -> WIPOffset<Vector<'fbb, T>> { self.assert_nested("end_vector"); self.nested = false; let o = self.push::<UOffsetT>(num_elems as UOffsetT); WIPOffset::new(o.value()) } /// Create a utf8 string. /// /// The wire format represents this as a zero-terminated byte vector. #[inline] pub fn create_string<'a: 'b, 'b>(&'a mut self, s: &'b str) -> WIPOffset<&'fbb str> { self.assert_not_nested( "create_string can not be called when a table or vector is under construction", ); WIPOffset::new(self.create_byte_string(s.as_bytes()).value()) } /// Create a zero-terminated byte vector. #[inline] pub fn create_byte_string(&mut self, data: &[u8]) -> WIPOffset<&'fbb [u8]> { self.assert_not_nested( "create_byte_string can not be called when a table or vector is under construction", ); self.align(data.len() + 1, PushAlignment::new(SIZE_UOFFSET)); self.push(0u8); self.push_bytes_unprefixed(data); self.push(data.len() as UOffsetT); WIPOffset::new(self.used_space() as UOffsetT) } /// Create a vector by memcpy'ing. This is much faster than calling /// `create_vector`, but the underlying type must be represented as /// little-endian on the host machine. This property is encoded in the /// type system through the SafeSliceAccess trait. The following types are /// always safe, on any platform: bool, u8, i8, and any /// FlatBuffers-generated struct. #[inline] pub fn create_vector_direct<'a: 'b, 'b, T: SafeSliceAccess + Push + Sized + 'b>( &'a mut self, items: &'b [T], ) -> WIPOffset<Vector<'fbb, T>> { self.assert_not_nested( "create_vector_direct can not be called when a table or vector is under construction", ); let elem_size = T::size(); self.align(items.len() * elem_size, T::alignment().max_of(SIZE_UOFFSET)); let bytes = { let ptr = items.as_ptr() as *const T as *const u8; unsafe { from_raw_parts(ptr, items.len() * elem_size) } }; self.push_bytes_unprefixed(bytes); self.push(items.len() as UOffsetT); WIPOffset::new(self.used_space() as UOffsetT) } /// Create a vector of strings. /// /// Speed-sensitive users may wish to reduce memory usage by creating the /// vector manually: use `start_vector`, `push`, and `end_vector`. #[inline] pub fn create_vector_of_strings<'a, 'b>( &'a mut self, xs: &'b [&'b str], ) -> WIPOffset<Vector<'fbb, ForwardsUOffset<&'fbb str>>> { self.assert_not_nested("create_vector_of_strings can not be called when a table or vector is under construction"); // internally, smallvec can be a stack-allocated or heap-allocated vector: // if xs.len() > N_SMALLVEC_STRING_VECTOR_CAPACITY then it will overflow to the heap. let mut offsets: smallvec::SmallVec<[WIPOffset<&str>; N_SMALLVEC_STRING_VECTOR_CAPACITY]> = smallvec::SmallVec::with_capacity(xs.len()); unsafe { offsets.set_len(xs.len()); } // note that this happens in reverse, because the buffer is built back-to-front: for (i, &s) in xs.iter().enumerate().rev() { let o = self.create_string(s); offsets[i] = o; } self.create_vector(&offsets[..]) } /// Create a vector of Push-able objects. /// /// Speed-sensitive users may wish to reduce memory usage by creating the /// vector manually: use `start_vector`, `push`, and `end_vector`. #[inline] pub fn create_vector<'a: 'b, 'b, T: Push + Copy + 'b>( &'a mut self, items: &'b [T], ) -> WIPOffset<Vector<'fbb, T::Output>> { let elem_size = T::size(); self.align(items.len() * elem_size, T::alignment().max_of(SIZE_UOFFSET)); for i in (0..items.len()).rev() { self.push(items[i]); } WIPOffset::new(self.push::<UOffsetT>(items.len() as UOffsetT).value()) } /// Get the byte slice for the data that has been written, regardless of /// whether it has been finished. #[inline] pub fn unfinished_data(&self) -> &[u8] { &self.owned_buf[self.head..] } /// Get the byte slice for the data that has been written after a call to /// one of the `finish` functions. #[inline] pub fn finished_data(&self) -> &[u8] { self.assert_finished("finished_bytes cannot be called when the buffer is not yet finished"); &self.owned_buf[self.head..] } /// Assert that a field is present in the just-finished Table. /// /// This is somewhat low-level and is mostly used by the generated code. #[inline] pub fn required( &self, tab_revloc: WIPOffset<TableFinishedWIPOffset>, slot_byte_loc: VOffsetT, assert_msg_name: &'static str, ) { let idx = self.used_space() - tab_revloc.value() as usize; let tab = Table::new(&self.owned_buf[self.head..], idx); let o = tab.vtable().get(slot_byte_loc) as usize; assert!(o != 0, "missing required field {}", assert_msg_name); } /// Finalize the FlatBuffer by: aligning it, pushing an optional file /// identifier on to it, pushing a size prefix on to it, and marking the /// internal state of the FlatBufferBuilder as `finished`. Afterwards, /// users can call `finished_data` to get the resulting data. #[inline] pub fn finish_size_prefixed<T>(&mut self, root: WIPOffset<T>, file_identifier: Option<&str>) { self.finish_with_opts(root, file_identifier, true); } /// Finalize the FlatBuffer by: aligning it, pushing an optional file /// identifier on to it, and marking the internal state of the /// FlatBufferBuilder as `finished`. Afterwards, users can call /// `finished_data` to get the resulting data. #[inline] pub fn finish<T>(&mut self, root: WIPOffset<T>, file_identifier: Option<&str>) { self.finish_with_opts(root, file_identifier, false); } /// Finalize the FlatBuffer by: aligning it and marking the internal state /// of the FlatBufferBuilder as `finished`. Afterwards, users can call /// `finished_data` to get the resulting data. #[inline] pub fn finish_minimal<T>(&mut self, root: WIPOffset<T>) { self.finish_with_opts(root, None, false); } #[inline] fn used_space(&self) -> usize { self.owned_buf.len() - self.head as usize } #[inline] fn track_field(&mut self, slot_off: VOffsetT, off: UOffsetT) { let fl = FieldLoc { id: slot_off, off: off, }; self.field_locs.push(fl); } /// Write the VTable, if it is new. fn write_vtable( &mut self, table_tail_revloc: WIPOffset<TableUnfinishedWIPOffset>, ) -> WIPOffset<VTableWIPOffset> { self.assert_nested("write_vtable"); // Write the vtable offset, which is the start of any Table. // We fill its value later. let object_revloc_to_vtable: WIPOffset<VTableWIPOffset> = WIPOffset::new(self.push::<UOffsetT>(0xF0F0F0F0 as UOffsetT).value()); // Layout of the data this function will create when a new vtable is // needed. // -------------------------------------------------------------------- // vtable starts here // | x, x -- vtable len (bytes) [u16] // | x, x -- object inline len (bytes) [u16] // | x, x -- zero, or num bytes from start of object to field #0 [u16] // | ... // | x, x -- zero, or num bytes from start of object to field #n-1 [u16] // vtable ends here // table starts here // | x, x, x, x -- offset (negative direction) to the vtable [i32] // | aka "vtableoffset" // | -- table inline data begins here, we don't touch it -- // table ends here -- aka "table_start" // -------------------------------------------------------------------- // // Layout of the data this function will create when we re-use an // existing vtable. // // We always serialize this particular vtable, then compare it to the // other vtables we know about to see if there is a duplicate. If there // is, then we erase the serialized vtable we just made. // We serialize it first so that we are able to do byte-by-byte // comparisons with already-serialized vtables. This 1) saves // bookkeeping space (we only keep revlocs to existing vtables), 2) // allows us to convert to little-endian once, then do // fast memcmp comparisons, and 3) by ensuring we are comparing real // serialized vtables, we can be more assured that we are doing the // comparisons correctly. // // -------------------------------------------------------------------- // table starts here // | x, x, x, x -- offset (negative direction) to an existing vtable [i32] // | aka "vtableoffset" // | -- table inline data begins here, we don't touch it -- // table starts here: aka "table_start" // -------------------------------------------------------------------- // fill the WIP vtable with zeros: let vtable_byte_len = get_vtable_byte_len(&self.field_locs); self.make_space(vtable_byte_len); // compute the length of the table (not vtable!) in bytes: let table_object_size = object_revloc_to_vtable.value() - table_tail_revloc.value(); debug_assert!(table_object_size < 0x10000); // vTable use 16bit offsets. // Write the VTable (we may delete it afterwards, if it is a duplicate): let vt_start_pos = self.head; let vt_end_pos = self.head + vtable_byte_len; { // write the vtable header: let vtfw = &mut VTableWriter::init(&mut self.owned_buf[vt_start_pos..vt_end_pos]); vtfw.write_vtable_byte_length(vtable_byte_len as VOffsetT); vtfw.write_object_inline_size(table_object_size as VOffsetT); // serialize every FieldLoc to the vtable: for &fl in self.field_locs.iter() { let pos: VOffsetT = (object_revloc_to_vtable.value() - fl.off) as VOffsetT; debug_assert_eq!( vtfw.get_field_offset(fl.id), 0, "tried to write a vtable field multiple times" ); vtfw.write_field_offset(fl.id, pos); } } let dup_vt_use = { let this_vt = VTable::init(&self.owned_buf[..], self.head); self.find_duplicate_stored_vtable_revloc(this_vt) }; let vt_use = match dup_vt_use { Some(n) => { VTableWriter::init(&mut self.owned_buf[vt_start_pos..vt_end_pos]).clear(); self.head += vtable_byte_len; n } None => { let new_vt_use = self.used_space() as UOffsetT; self.written_vtable_revpos.push(new_vt_use); new_vt_use } }; { let n = self.head + self.used_space() - object_revloc_to_vtable.value() as usize; let saw = read_scalar_at::<UOffsetT>(&self.owned_buf, n); debug_assert_eq!(saw, 0xF0F0F0F0); emplace_scalar::<SOffsetT>( &mut self.owned_buf[n..n + SIZE_SOFFSET], vt_use as SOffsetT - object_revloc_to_vtable.value() as SOffsetT, ); } self.field_locs.clear(); object_revloc_to_vtable } #[inline] fn find_duplicate_stored_vtable_revloc(&self, needle: VTable) -> Option<UOffsetT> { for &revloc in self.written_vtable_revpos.iter().rev() { let o = VTable::init( &self.owned_buf[..], self.head + self.used_space() - revloc as usize, ); if needle == o { return Some(revloc); } } None } // Only call this when you know it is safe to double the size of the buffer. #[inline] fn grow_owned_buf(&mut self) { let old_len = self.owned_buf.len(); let new_len = max(1, old_len * 2); let starting_active_size = self.used_space(); let diff = new_len - old_len; self.owned_buf.resize(new_len, 0); self.head += diff; let ending_active_size = self.used_space(); debug_assert_eq!(starting_active_size, ending_active_size); if new_len == 1 { return; } // calculate the midpoint, and safely copy the old end data to the new // end position: let middle = new_len / 2; { let (left, right) = &mut self.owned_buf[..].split_at_mut(middle); right.copy_from_slice(left); } // finally, zero out the old end data. { let ptr = (&mut self.owned_buf[..middle]).as_mut_ptr(); unsafe { write_bytes(ptr, 0, middle); } } } // with or without a size prefix changes how we load the data, so finish* // functions are split along those lines. fn finish_with_opts<T>( &mut self, root: WIPOffset<T>, file_identifier: Option<&str>, size_prefixed: bool, ) { self.assert_not_finished("buffer cannot be finished when it is already finished"); self.assert_not_nested( "buffer cannot be finished when a table or vector is under construction", ); self.written_vtable_revpos.clear(); let to_align = { // for the root offset: let a = SIZE_UOFFSET; // for the size prefix: let b = if size_prefixed { SIZE_UOFFSET } else { 0 }; // for the file identifier (a string that is not zero-terminated): let c = if file_identifier.is_some() { FILE_IDENTIFIER_LENGTH } else { 0 }; a + b + c }; { let ma = PushAlignment::new(self.min_align); self.align(to_align, ma); } if let Some(ident) = file_identifier { debug_assert_eq!(ident.len(), FILE_IDENTIFIER_LENGTH); self.push_bytes_unprefixed(ident.as_bytes()); } self.push(root); if size_prefixed { let sz = self.used_space() as UOffsetT; self.push::<UOffsetT>(sz); } self.finished = true; } #[inline] fn align(&mut self, len: usize, alignment: PushAlignment) { self.track_min_align(alignment.value()); let s = self.used_space() as usize; self.make_space(padding_bytes(s + len, alignment.value())); } #[inline] fn track_min_align(&mut self, alignment: usize) { self.min_align = max(self.min_align, alignment); } #[inline] fn push_bytes_unprefixed(&mut self, x: &[u8]) -> UOffsetT { let n = self.make_space(x.len()); &mut self.owned_buf[n..n + x.len()].copy_from_slice(x); n as UOffsetT } #[inline] fn make_space(&mut self, want: usize) -> usize { self.ensure_capacity(want); self.head -= want; self.head } #[inline] fn ensure_capacity(&mut self, want: usize) -> usize { if self.unused_ready_space() >= want { return want; } assert!( want <= FLATBUFFERS_MAX_BUFFER_SIZE, "cannot grow buffer beyond 2 gigabytes" ); while self.unused_ready_space() < want { self.grow_owned_buf(); } want } #[inline] fn unused_ready_space(&self) -> usize { self.head } #[inline] fn assert_nested(&self, fn_name: &'static str) { // we don't assert that self.field_locs.len() >0 because the vtable // could be empty (e.g. for empty tables, or for all-default values). debug_assert!( self.nested, format!( "incorrect FlatBufferBuilder usage: {} must be called while in a nested state", fn_name ) ); } #[inline] fn assert_not_nested(&self, msg: &'static str) { debug_assert!(!self.nested, msg); } #[inline] fn assert_finished(&self, msg: &'static str) { debug_assert!(self.finished, msg); } #[inline] fn assert_not_finished(&self, msg: &'static str) { debug_assert!(!self.finished, msg); } } /// Compute the length of the vtable needed to represent the provided FieldLocs. /// If there are no FieldLocs, then provide the minimum number of bytes /// required: enough to write the VTable header. #[inline] fn get_vtable_byte_len(field_locs: &[FieldLoc]) -> usize { let max_voffset = field_locs.iter().map(|fl| fl.id).max(); match max_voffset { None => field_index_to_field_offset(0) as usize, Some(mv) => mv as usize + SIZE_VOFFSET, } } #[inline] fn padding_bytes(buf_size: usize, scalar_size: usize) -> usize { // ((!buf_size) + 1) & (scalar_size - 1) (!buf_size).wrapping_add(1) & (scalar_size.wrapping_sub(1)) } impl<'fbb> Default for FlatBufferBuilder<'fbb> { fn default() -> Self { Self::new_with_capacity(0) } }
bjtaylor1/osrm-backend
third_party/flatbuffers/rust/flatbuffers/src/builder.rs
Rust
bsd-2-clause
25,110
import FragmentFactory from '../../fragment/factory' import { FOR } from '../priorities' import { withoutConversion } from '../../observer/index' import { getPath } from '../../parsers/path' import { isObject, warn, createAnchor, replace, before, after, remove, hasOwn, inDoc, defineReactive, def, cancellable, isArray, isPlainObject } from '../../util/index' let uid = 0 const vFor = { priority: FOR, terminal: true, params: [ 'track-by', 'stagger', 'enter-stagger', 'leave-stagger' ], bind () { // support "item in/of items" syntax var inMatch = this.expression.match(/(.*) (?:in|of) (.*)/) if (inMatch) { var itMatch = inMatch[1].match(/\((.*),(.*)\)/) if (itMatch) { this.iterator = itMatch[1].trim() this.alias = itMatch[2].trim() } else { this.alias = inMatch[1].trim() } this.expression = inMatch[2] } if (!this.alias) { process.env.NODE_ENV !== 'production' && warn( 'Invalid v-for expression "' + this.descriptor.raw + '": ' + 'alias is required.', this.vm ) return } // uid as a cache identifier this.id = '__v-for__' + (++uid) // check if this is an option list, // so that we know if we need to update the <select>'s // v-model when the option list has changed. // because v-model has a lower priority than v-for, // the v-model is not bound here yet, so we have to // retrive it in the actual updateModel() function. var tag = this.el.tagName this.isOption = (tag === 'OPTION' || tag === 'OPTGROUP') && this.el.parentNode.tagName === 'SELECT' // setup anchor nodes this.start = createAnchor('v-for-start') this.end = createAnchor('v-for-end') replace(this.el, this.end) before(this.start, this.end) // cache this.cache = Object.create(null) // fragment factory this.factory = new FragmentFactory(this.vm, this.el) }, update (data) { this.diff(data) this.updateRef() this.updateModel() }, /** * Diff, based on new data and old data, determine the * minimum amount of DOM manipulations needed to make the * DOM reflect the new data Array. * * The algorithm diffs the new data Array by storing a * hidden reference to an owner vm instance on previously * seen data. This allows us to achieve O(n) which is * better than a levenshtein distance based algorithm, * which is O(m * n). * * @param {Array} data */ diff (data) { // check if the Array was converted from an Object var item = data[0] var convertedFromObject = this.fromObject = isObject(item) && hasOwn(item, '$key') && hasOwn(item, '$value') var trackByKey = this.params.trackBy var oldFrags = this.frags var frags = this.frags = new Array(data.length) var alias = this.alias var iterator = this.iterator var start = this.start var end = this.end var inDocument = inDoc(start) var init = !oldFrags var i, l, frag, key, value, primitive // First pass, go through the new Array and fill up // the new frags array. If a piece of data has a cached // instance for it, we reuse it. Otherwise build a new // instance. for (i = 0, l = data.length; i < l; i++) { item = data[i] key = convertedFromObject ? item.$key : null value = convertedFromObject ? item.$value : item primitive = !isObject(value) frag = !init && this.getCachedFrag(value, i, key) if (frag) { // reusable fragment frag.reused = true // update $index frag.scope.$index = i // update $key if (key) { frag.scope.$key = key } // update iterator if (iterator) { frag.scope[iterator] = key !== null ? key : i } // update data for track-by, object repeat & // primitive values. if (trackByKey || convertedFromObject || primitive) { withoutConversion(() => { frag.scope[alias] = value }) } } else { // new isntance frag = this.create(value, alias, i, key) frag.fresh = !init } frags[i] = frag if (init) { frag.before(end) } } // we're done for the initial render. if (init) { return } // Second pass, go through the old fragments and // destroy those who are not reused (and remove them // from cache) var removalIndex = 0 var totalRemoved = oldFrags.length - frags.length // when removing a large number of fragments, watcher removal // turns out to be a perf bottleneck, so we batch the watcher // removals into a single filter call! this.vm._vForRemoving = true for (i = 0, l = oldFrags.length; i < l; i++) { frag = oldFrags[i] if (!frag.reused) { this.deleteCachedFrag(frag) this.remove(frag, removalIndex++, totalRemoved, inDocument) } } this.vm._vForRemoving = false if (removalIndex) { this.vm._watchers = this.vm._watchers.filter(w => w.active) } // Final pass, move/insert new fragments into the // right place. var targetPrev, prevEl, currentPrev var insertionIndex = 0 for (i = 0, l = frags.length; i < l; i++) { frag = frags[i] // this is the frag that we should be after targetPrev = frags[i - 1] prevEl = targetPrev ? targetPrev.staggerCb ? targetPrev.staggerAnchor : targetPrev.end || targetPrev.node : start if (frag.reused && !frag.staggerCb) { currentPrev = findPrevFrag(frag, start, this.id) if ( currentPrev !== targetPrev && ( !currentPrev || // optimization for moving a single item. // thanks to suggestions by @livoras in #1807 findPrevFrag(currentPrev, start, this.id) !== targetPrev ) ) { this.move(frag, prevEl) } } else { // new instance, or still in stagger. // insert with updated stagger index. this.insert(frag, insertionIndex++, prevEl, inDocument) } frag.reused = frag.fresh = false } }, /** * Create a new fragment instance. * * @param {*} value * @param {String} alias * @param {Number} index * @param {String} [key] * @return {Fragment} */ create (value, alias, index, key) { var host = this._host // create iteration scope var parentScope = this._scope || this.vm var scope = Object.create(parentScope) // ref holder for the scope scope.$refs = Object.create(parentScope.$refs) scope.$els = Object.create(parentScope.$els) // make sure point $parent to parent scope scope.$parent = parentScope // for two-way binding on alias scope.$forContext = this // define scope properties // important: define the scope alias without forced conversion // so that frozen data structures remain non-reactive. withoutConversion(() => { defineReactive(scope, alias, value) }) defineReactive(scope, '$index', index) if (key) { defineReactive(scope, '$key', key) } else if (scope.$key) { // avoid accidental fallback def(scope, '$key', null) } if (this.iterator) { defineReactive(scope, this.iterator, key !== null ? key : index) } var frag = this.factory.create(host, scope, this._frag) frag.forId = this.id this.cacheFrag(value, frag, index, key) return frag }, /** * Update the v-ref on owner vm. */ updateRef () { var ref = this.descriptor.ref if (!ref) return var hash = (this._scope || this.vm).$refs var refs if (!this.fromObject) { refs = this.frags.map(findVmFromFrag) } else { refs = {} this.frags.forEach(function (frag) { refs[frag.scope.$key] = findVmFromFrag(frag) }) } hash[ref] = refs }, /** * For option lists, update the containing v-model on * parent <select>. */ updateModel () { if (this.isOption) { var parent = this.start.parentNode var model = parent && parent.__v_model if (model) { model.forceUpdate() } } }, /** * Insert a fragment. Handles staggering. * * @param {Fragment} frag * @param {Number} index * @param {Node} prevEl * @param {Boolean} inDocument */ insert (frag, index, prevEl, inDocument) { if (frag.staggerCb) { frag.staggerCb.cancel() frag.staggerCb = null } var staggerAmount = this.getStagger(frag, index, null, 'enter') if (inDocument && staggerAmount) { // create an anchor and insert it synchronously, // so that we can resolve the correct order without // worrying about some elements not inserted yet var anchor = frag.staggerAnchor if (!anchor) { anchor = frag.staggerAnchor = createAnchor('stagger-anchor') anchor.__v_frag = frag } after(anchor, prevEl) var op = frag.staggerCb = cancellable(function () { frag.staggerCb = null frag.before(anchor) remove(anchor) }) setTimeout(op, staggerAmount) } else { var target = prevEl.nextSibling /* istanbul ignore if */ if (!target) { // reset end anchor position in case the position was messed up // by an external drag-n-drop library. after(this.end, prevEl) target = this.end } frag.before(target) } }, /** * Remove a fragment. Handles staggering. * * @param {Fragment} frag * @param {Number} index * @param {Number} total * @param {Boolean} inDocument */ remove (frag, index, total, inDocument) { if (frag.staggerCb) { frag.staggerCb.cancel() frag.staggerCb = null // it's not possible for the same frag to be removed // twice, so if we have a pending stagger callback, // it means this frag is queued for enter but removed // before its transition started. Since it is already // destroyed, we can just leave it in detached state. return } var staggerAmount = this.getStagger(frag, index, total, 'leave') if (inDocument && staggerAmount) { var op = frag.staggerCb = cancellable(function () { frag.staggerCb = null frag.remove() }) setTimeout(op, staggerAmount) } else { frag.remove() } }, /** * Move a fragment to a new position. * Force no transition. * * @param {Fragment} frag * @param {Node} prevEl */ move (frag, prevEl) { // fix a common issue with Sortable: // if prevEl doesn't have nextSibling, this means it's // been dragged after the end anchor. Just re-position // the end anchor to the end of the container. /* istanbul ignore if */ if (!prevEl.nextSibling) { this.end.parentNode.appendChild(this.end) } frag.before(prevEl.nextSibling, false) }, /** * Cache a fragment using track-by or the object key. * * @param {*} value * @param {Fragment} frag * @param {Number} index * @param {String} [key] */ cacheFrag (value, frag, index, key) { var trackByKey = this.params.trackBy var cache = this.cache var primitive = !isObject(value) var id if (key || trackByKey || primitive) { id = getTrackByKey(index, key, value, trackByKey) if (!cache[id]) { cache[id] = frag } else if (trackByKey !== '$index') { process.env.NODE_ENV !== 'production' && this.warnDuplicate(value) } } else { id = this.id if (hasOwn(value, id)) { if (value[id] === null) { value[id] = frag } else { process.env.NODE_ENV !== 'production' && this.warnDuplicate(value) } } else if (Object.isExtensible(value)) { def(value, id, frag) } else if (process.env.NODE_ENV !== 'production') { warn( 'Frozen v-for objects cannot be automatically tracked, make sure to ' + 'provide a track-by key.' ) } } frag.raw = value }, /** * Get a cached fragment from the value/index/key * * @param {*} value * @param {Number} index * @param {String} key * @return {Fragment} */ getCachedFrag (value, index, key) { var trackByKey = this.params.trackBy var primitive = !isObject(value) var frag if (key || trackByKey || primitive) { var id = getTrackByKey(index, key, value, trackByKey) frag = this.cache[id] } else { frag = value[this.id] } if (frag && (frag.reused || frag.fresh)) { process.env.NODE_ENV !== 'production' && this.warnDuplicate(value) } return frag }, /** * Delete a fragment from cache. * * @param {Fragment} frag */ deleteCachedFrag (frag) { var value = frag.raw var trackByKey = this.params.trackBy var scope = frag.scope var index = scope.$index // fix #948: avoid accidentally fall through to // a parent repeater which happens to have $key. var key = hasOwn(scope, '$key') && scope.$key var primitive = !isObject(value) if (trackByKey || key || primitive) { var id = getTrackByKey(index, key, value, trackByKey) this.cache[id] = null } else { value[this.id] = null frag.raw = null } }, /** * Get the stagger amount for an insertion/removal. * * @param {Fragment} frag * @param {Number} index * @param {Number} total * @param {String} type */ getStagger (frag, index, total, type) { type = type + 'Stagger' var trans = frag.node.__v_trans var hooks = trans && trans.hooks var hook = hooks && (hooks[type] || hooks.stagger) return hook ? hook.call(frag, index, total) : index * parseInt(this.params[type] || this.params.stagger, 10) }, /** * Pre-process the value before piping it through the * filters. This is passed to and called by the watcher. */ _preProcess (value) { // regardless of type, store the un-filtered raw value. this.rawValue = value return value }, /** * Post-process the value after it has been piped through * the filters. This is passed to and called by the watcher. * * It is necessary for this to be called during the * wathcer's dependency collection phase because we want * the v-for to update when the source Object is mutated. */ _postProcess (value) { if (isArray(value)) { return value } else if (isPlainObject(value)) { // convert plain object to array. var keys = Object.keys(value) var i = keys.length var res = new Array(i) var key while (i--) { key = keys[i] res[i] = { $key: key, $value: value[key] } } return res } else { if (typeof value === 'number' && !isNaN(value)) { value = range(value) } return value || [] } }, unbind () { if (this.descriptor.ref) { (this._scope || this.vm).$refs[this.descriptor.ref] = null } if (this.frags) { var i = this.frags.length var frag while (i--) { frag = this.frags[i] this.deleteCachedFrag(frag) frag.destroy() } } } } /** * Helper to find the previous element that is a fragment * anchor. This is necessary because a destroyed frag's * element could still be lingering in the DOM before its * leaving transition finishes, but its inserted flag * should have been set to false so we can skip them. * * If this is a block repeat, we want to make sure we only * return frag that is bound to this v-for. (see #929) * * @param {Fragment} frag * @param {Comment|Text} anchor * @param {String} id * @return {Fragment} */ function findPrevFrag (frag, anchor, id) { var el = frag.node.previousSibling /* istanbul ignore if */ if (!el) return frag = el.__v_frag while ( (!frag || frag.forId !== id || !frag.inserted) && el !== anchor ) { el = el.previousSibling /* istanbul ignore if */ if (!el) return frag = el.__v_frag } return frag } /** * Find a vm from a fragment. * * @param {Fragment} frag * @return {Vue|undefined} */ function findVmFromFrag (frag) { let node = frag.node // handle multi-node frag if (frag.end) { while (!node.__vue__ && node !== frag.end && node.nextSibling) { node = node.nextSibling } } return node.__vue__ } /** * Create a range array from given number. * * @param {Number} n * @return {Array} */ function range (n) { var i = -1 var ret = new Array(Math.floor(n)) while (++i < n) { ret[i] = i } return ret } /** * Get the track by key for an item. * * @param {Number} index * @param {String} key * @param {*} value * @param {String} [trackByKey] */ function getTrackByKey (index, key, value, trackByKey) { return trackByKey ? trackByKey === '$index' ? index : trackByKey.charAt(0).match(/\w/) ? getPath(value, trackByKey) : value[trackByKey] : (key || value) } if (process.env.NODE_ENV !== 'production') { vFor.warnDuplicate = function (value) { warn( 'Duplicate value found in v-for="' + this.descriptor.raw + '": ' + JSON.stringify(value) + '. Use track-by="$index" if ' + 'you are expecting duplicate values.', this.vm ) } } export default vFor
insionng/yougam
public/libs/vue-1.0.24/src/directives/public/for.js
JavaScript
bsd-2-clause
17,583
class Kyua < Formula desc "Testing framework for infrastructure software" homepage "https://github.com/jmmv/kyua" url "https://github.com/jmmv/kyua/releases/download/kyua-0.13/kyua-0.13.tar.gz" sha256 "db6e5d341d5cf7e49e50aa361243e19087a00ba33742b0855d2685c0b8e721d6" license "BSD-3-Clause" revision 2 bottle do sha256 arm64_monterey: "8e53cdb607af1f2aded06f7c2348f976f02cc413167bf7d9c84ed8df28022764" sha256 arm64_big_sur: "0de5560c3fe849a4d1739c041b4b70a235929ac1323a9e7f1a1769c69ae6b363" sha256 monterey: "333cca57c2a7eab8dfc5f42e026a1c646a50a33e4722553cfa9772311c32b89d" sha256 big_sur: "33c93cc065968275bdee21b772ada29ebe3776f7c1dacb297e6c3cb2804fcb20" sha256 catalina: "5fba6da95b5e79c1fda0d118b0d67a4c74629a28e348ae4fab0dee1b770dccd4" sha256 mojave: "b0d437da5f3f873795d6157dcc545a3ca72fef19d5288369a95b58ba5c8f4cc5" end depends_on "pkg-config" => :build depends_on "atf" depends_on "lua" depends_on "lutok" depends_on "sqlite" def install ENV.append "CPPFLAGS", "-I#{Formula["lua"].opt_include}/lua" system "./configure", "--disable-dependency-tracking", "--disable-silent-rules", "--prefix=#{prefix}" system "make" ENV.deparallelize system "make", "install" end end
filcab/homebrew-core
Formula/kyua.rb
Ruby
bsd-2-clause
1,333
<?php /** * 用户相关 **/ namespace remote; use Flight; use common\Curl; use common\Config; class PkgUser extends Curl { CONST TIMEOUT = 120; private $token; private function setToken() { $this->token = Flight::get('token'); } private function unsetToken() { $this->token = null; } public function request($path, array $query = null, array $data = null, $method = 'GET') { $url = Config::get('pkg.api_url') . 'user/' . $path; $host = Config::get('pkg.api_host'); $timeout = self::TIMEOUT; $header = array(); // 请求头中加入 `token` if ($this->token) { $header[] = 'Tars-Token: ' . $this->token; }/* else { $header[] = 'Tars-Token: no'; }*/ // GET 参数 if ($query) { $url .= '?' . http_build_query($query); } $options = compact('url', 'method', 'host', 'timeout'); // 请求主体 if ($data) { $header[] = 'Content-Type: application/json'; $options['data'] = json_encode($data); } $options['header'] = $header; return $this->curl($options); } public function get($path, array $query = null) { return $this->request($path, $query); } public function post($path, array $data = null, array $query = null) { return $this->request($path, $query, $data, 'POST'); } public function put($path, array $data = null, array $query = null) { return $this->request($path, $query, $data, 'PUT'); } public function delete($path, array $query = null) { return $this->request($path, $query, null, 'DELETE'); } public function storeUsers(array $users) { $this->setToken(); return $this->post('users', $users); } public function signin($username, $password) { $this->unsetToken(); return $this->post('session', compact('username', 'password')); } public function getUser() { $this->setToken(); return $this->get('user'); } public function listUsers() { $this->setToken(); return $this->get('alluser'); } public function updateUser($username, array $options) { $this->setToken(); $data = compact('username'); $data += $options; return $this->put('user', $data); } }
matyhtf/tars
console/src/remote/PkgUser.php
PHP
bsd-2-clause
2,422
class Tbox < Formula desc "Glib-like multi-platform c library" homepage "https://tboox.org/" url "https://github.com/waruqi/tbox/archive/v1.6.3.tar.gz" sha256 "1ea225195ad6d41a29389137683fee7a853fa42f3292226ddcb6d6d862f5b33c" head "https://github.com/waruqi/tbox.git" bottle do cellar :any_skip_relocation sha256 "63a75febf95f9f60e187e2100e6d64f772f3ef59d3e2e5603a1fdb7cbe77b992" => :mojave sha256 "2f34f5d60397588aff11eefc308a6d23f3a23fe451d118094b04b00024877832" => :high_sierra sha256 "956ff755fecde9ad86e5920b9ecd01cf1de767354b60f68476d61a4583c04c81" => :sierra sha256 "7b238a754afed5af34b0ccc0caa47b2997791c34ad24b3a403334711e2ec71d4" => :el_capitan end depends_on "xmake" => :build def install system "xmake", "config", "--charset=y", "--demo=n", "--small=y", "--xml=y" system "xmake", "install", "-o", prefix end test do (testpath/"test.c").write <<~EOS #include <tbox/tbox.h> int main() { if (tb_init(tb_null, tb_null)) { tb_trace_i("hello tbox!"); tb_exit(); } return 0; } EOS system ENV.cc, "test.c", "-L#{lib}", "-ltbox", "-I#{include}", "-o", "test" system "./test" end end
bcg62/homebrew-core
Formula/tbox.rb
Ruby
bsd-2-clause
1,234
cask "powerphotos" do if MacOS.version <= :yosemite version "1.0.6" sha256 "927c1095858d259b9469c86d20ce39cf0bfc350ad0b64ae8ba0ca0557b632305" url "https://www.fatcatsoftware.com/powerphotos/PowerPhotos_#{version.no_dots}.zip" elsif MacOS.version <= :el_capitan version "1.2.3" sha256 "b07eb9f8801fb397d55e3dd7e0569dbef5d3265debaf3ee68247062901d93fcb" url "https://www.fatcatsoftware.com/powerphotos/PowerPhotos_#{version.no_dots}.zip" elsif MacOS.version <= :sierra version "1.4.2" sha256 "ed9be64f4cb5a3d3848ad5177947bd8cd33e36846ea36266ef9d4d7b46813538" url "https://www.fatcatsoftware.com/powerphotos/PowerPhotos_#{version.no_dots}.zip" elsif MacOS.version <= :high_sierra version "1.6.4" sha256 "e7c7d5970b734827a5f112029491d2d97f9a6bb318f457893905718bea6b595a" url "https://www.fatcatsoftware.com/powerphotos/PowerPhotos_#{version.no_dots}.zip" else version "1.9.10,1789" sha256 :no_check url "https://www.fatcatsoftware.com/powerphotos/PowerPhotos.zip" end name "PowerPhotos" desc "Tool to organize photo libraries" homepage "https://www.fatcatsoftware.com/powerphotos/" livecheck do url "https://www.fatcatsoftware.com/powerphotos/powerphotos_appcast.xml" strategy :sparkle end auto_updates true depends_on macos: ">= :yosemite" app "PowerPhotos.app" end
adrianchia/homebrew-cask
Casks/powerphotos.rb
Ruby
bsd-2-clause
1,362
def tied_rank(x): """ Computes the tied rank of elements in x. This function computes the tied rank of elements in x. Parameters ---------- x : list of numbers, numpy array Returns ------- score : list of numbers The tied rank f each element in x """ sorted_x = sorted(zip(x,range(len(x)))) r = [0 for k in x] cur_val = sorted_x[0][0] last_rank = 0 for i in range(len(sorted_x)): if cur_val != sorted_x[i][0]: cur_val = sorted_x[i][0] for j in range(last_rank, i): r[sorted_x[j][1]] = float(last_rank+1+i)/2.0 last_rank = i if i==len(sorted_x)-1: for j in range(last_rank, i+1): r[sorted_x[j][1]] = float(last_rank+i+2)/2.0 return r def auc(actual, posterior): """ Computes the area under the receiver-operater characteristic (AUC) This function computes the AUC error metric for binary classification. Parameters ---------- actual : list of binary numbers, numpy array The ground truth value posterior : same type as actual Defines a ranking on the binary numbers, from most likely to be positive to least likely to be positive. Returns ------- score : double The mean squared error between actual and posterior """ r = tied_rank(posterior) num_positive = len([0 for x in actual if x==1]) num_negative = len(actual)-num_positive sum_positive = sum([r[i] for i in range(len(r)) if actual[i]==1]) auc = ((sum_positive - num_positive*(num_positive+1)/2.0) / (num_negative*num_positive)) return auc
ujjwalkarn/Metrics
Python/ml_metrics/auc.py
Python
bsd-2-clause
1,715
class Ccze < Formula desc "Robust and modular log colorizer" homepage "https://packages.debian.org/wheezy/ccze" url "https://mirrors.ocf.berkeley.edu/debian/pool/main/c/ccze/ccze_0.2.1.orig.tar.gz" mirror "https://mirrorservice.org/sites/ftp.debian.org/debian/pool/main/c/ccze/ccze_0.2.1.orig.tar.gz" sha256 "8263a11183fd356a033b6572958d5a6bb56bfd2dba801ed0bff276cfae528aa3" revision 1 bottle do sha256 "7f1d8fb98c7ca95eb938ff2bae748ad081772542234bbd25151cc37e0f097461" => :sierra sha256 "795fc9b842f53197ec45774d909fb14efd463a64215fbec799ad870bb78a6834" => :el_capitan sha256 "11c34c8ad4df9993b7f465c7c7a7fdb2588e3c75d678f3b22f36166ca1c04520" => :yosemite sha256 "40b61bc0353350f43c97f611d26c0826e4e4ce5df0284b1f544e89460af25722" => :mavericks end depends_on "pcre" def install # https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=823334 inreplace "src/ccze-compat.c", "#if HAVE_SUBOPTARg", "#if HAVE_SUBOPTARG" # Allegedly from Debian & fixes compiler errors on old OS X releases. # https://github.com/Homebrew/legacy-homebrew/pull/20636 inreplace "src/Makefile.in", "-Wreturn-type -Wswitch -Wmulticharacter", "-Wreturn-type -Wswitch" system "./configure", "--prefix=#{prefix}", "--with-builtins=all" system "make", "install" # Strange but true: using --mandir above causes the build to fail! share.install prefix/"man" end test do system "#{bin}/ccze", "--help" end end
j-bennet/homebrew-core
Formula/ccze.rb
Ruby
bsd-2-clause
1,518
/* Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Text; using NUnit.Framework; using XenAdmin; using XenAdmin.Plugins; using System.Windows.Forms; using System.IO; using XenAdmin.Plugins.UI; using XenAdminTests.DialogTests; using XenAdminTests.DialogTests.PluginDialogTests; using XenAdmin.Core; namespace XenAdminTests.PluginTests { [TestFixture, Ignore] public class PluginTest_PowerShell : MainWindowLauncher_TestFixture { [TestFixtureSetUp] public void SetUp_PowerShellPlugin() { MW(delegate() { List<string> enabled_plugins = new List<string>(Settings.EnabledPluginsList()); enabled_plugins.Add("UnitTest::PowerShellPlugin"); Settings.UpdateEnabledPluginsList(enabled_plugins.ToArray()); Manager.ProcessPlugin(Path.Combine(Program.AssemblyDir, "TestResources\\PluginResources\\PowerShellPlugin.xcplugin.xml"), "PowerShellPlugin", "UnitTest"); }); } // causes System.ArgumentException : Delegate to an instance method cannot have null 'this' //[Test] //public void Test_PluginDialog() //{ // new PluginDialogTest().RunDialogTests(); //} [Test] public void Test_File_PowerShell() { if (Registry.IsPowerShellInstalled()) ClickMenuItem("File", "file_PowerShellTest1"); else CheckMenuItemMissing("File", "file_PowerShellTest1"); } [Test] public void Test_View_PowerShell() { if (Registry.IsPowerShellInstalled()) ClickMenuItem("View", "view_PowerShellTest1"); else CheckMenuItemMissing("View", "view_PowerShellTest1"); } [Test] public void Test_Pool_PowerShell() { if (Registry.IsPowerShellInstalled()) ClickMenuItem("Pool", "pool_PowerShellTest1"); else CheckMenuItemMissing("Pool", "pool_PowerShellTest1"); } [Test] public void Test_Server_PowerShell() { if (Registry.IsPowerShellInstalled()) ClickMenuItem("Server", "server_PowerShellTest1"); else CheckMenuItemMissing("Server", "server_PowerShellTest1"); } [Test] public void Test_VM_PowerShell() { if (Registry.IsPowerShellInstalled()) ClickMenuItem("VM", "vm_PowerShellTest1"); else CheckMenuItemMissing("VM", "vm_PowerShellTest1"); } [Test] public void Test_Storage_PowerShell() { if (Registry.IsPowerShellInstalled()) ClickMenuItem("Storage", "storage_PowerShellTest1"); else CheckMenuItemMissing("Storage", "storage_PowerShellTest1"); } [Test] public void Test_Templates_PowerShell() { if (Registry.IsPowerShellInstalled()) ClickMenuItem("Templates", "templates_PowerShellTest1"); else CheckMenuItemMissing("Templates", "templates_PowerShellTest1"); } [Test] public void Test_Tools_PowerShell() { if (Registry.IsPowerShellInstalled()) ClickMenuItem("Tools", "tools_PowerShellTest1"); else CheckMenuItemMissing("Tools", "tools_PowerShellTest1"); } [Test] public void Test_Window_PowerShell() { if (Registry.IsPowerShellInstalled()) ClickMenuItem("Window", "window_PowerShellTest1"); else CheckMenuItemMissing("Window", "window_PowerShellTest1"); } [Test] public void Test_Help_PowerShell() { if (Registry.IsPowerShellInstalled()) ClickMenuItem("Help", "help_PowerShellTest1"); else CheckMenuItemMissing("Help", "help_PowerShellTest1"); } [TestFixtureTearDown] public void TearDown_PowerShellPlugin() { MW(delegate() { Descriptor plugin = Manager.Plugins.Find(new Predicate<Descriptor>(delegate(Descriptor d) { return d.Name == "PowerShellPlugin"; })); plugin.Dispose(); Manager.Plugins.Remove(plugin); List<string> enabled_plugins = new List<string>(Settings.EnabledPluginsList()); enabled_plugins.Remove("UnitTest::PowerShellPlugin"); Settings.UpdateEnabledPluginsList(enabled_plugins.ToArray()); }); } } }
ushamandya/xenadmin
XenAdminTests/PluginTests/PluginTest_PowerShell.cs
C#
bsd-2-clause
6,397
cask 'airtool' do version '1.3.1' sha256 '93506b2d02650d91174669a389d27c4ec7f458e990d72c5fb3a3f542b66c32d6' # amazonaws.com/adriangranados was verified as official when first introduced to the cask url "https://s3.amazonaws.com/adriangranados/airtool_#{version}.pkg" appcast 'https://www.adriangranados.com/appcasts/airtoolcast.xml', checkpoint: '717a2856bb3d239314cd11958feae648b5175fe46879c9e146694355f1dd7718' name 'Airtool' homepage 'http://www.adriangranados.com/apps/airtool' license :gratis pkg "airtool_#{version}.pkg" uninstall pkgutil: [ 'com.adriangranados.airtool.airtool-bpf.*', 'com.adriangranados.airtool.Airtool.pkg', ], launchctl: 'com.adriangranados.airtool.airtool-bpf.pkg', login_item: 'Airtool' zap delete: [ '/Library/Application Support/Airtool', '~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/com.adriangranados.airtool.sfl', ] end
markhuber/homebrew-cask
Casks/airtool.rb
Ruby
bsd-2-clause
1,105
namespace XenAdmin.Dialogs { partial class ResolvingSubjectsDialog { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ResolvingSubjectsDialog)); this.tableLayoutPanelAddUsers = new System.Windows.Forms.TableLayoutPanel(); this.label1 = new System.Windows.Forms.Label(); this.textBoxNames = new System.Windows.Forms.TextBox(); this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel(); this.ButtonCancel = new System.Windows.Forms.Button(); this.buttonGrantAccess = new System.Windows.Forms.Button(); this.entryListView = new System.Windows.Forms.ListView(); this.ColumnName = new System.Windows.Forms.ColumnHeader(); this.ColumnResolveStatus = new System.Windows.Forms.ColumnHeader(); this.ColumnGrantAccess = new System.Windows.Forms.ColumnHeader(); this.progressBar1 = new System.Windows.Forms.ProgressBar(); this.LabelStatus = new System.Windows.Forms.Label(); this.labelTopBlurb = new System.Windows.Forms.Label(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.textBoxUserNames = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.tableLayoutPanelAddUsers.SuspendLayout(); this.flowLayoutPanel1.SuspendLayout(); this.tableLayoutPanel1.SuspendLayout(); this.SuspendLayout(); // // tableLayoutPanelAddUsers // resources.ApplyResources(this.tableLayoutPanelAddUsers, "tableLayoutPanelAddUsers"); this.tableLayoutPanelAddUsers.Controls.Add(this.label1, 0, 0); this.tableLayoutPanelAddUsers.Name = "tableLayoutPanelAddUsers"; // // label1 // resources.ApplyResources(this.label1, "label1"); this.tableLayoutPanelAddUsers.SetColumnSpan(this.label1, 3); this.label1.Name = "label1"; // // textBoxNames // resources.ApplyResources(this.textBoxNames, "textBoxNames"); this.textBoxNames.Name = "textBoxNames"; // // flowLayoutPanel1 // resources.ApplyResources(this.flowLayoutPanel1, "flowLayoutPanel1"); this.tableLayoutPanel1.SetColumnSpan(this.flowLayoutPanel1, 2); this.flowLayoutPanel1.Controls.Add(this.ButtonCancel); this.flowLayoutPanel1.Controls.Add(this.buttonGrantAccess); this.flowLayoutPanel1.Name = "flowLayoutPanel1"; // // ButtonCancel // this.ButtonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; resources.ApplyResources(this.ButtonCancel, "ButtonCancel"); this.ButtonCancel.Name = "ButtonCancel"; this.ButtonCancel.UseVisualStyleBackColor = true; // // buttonGrantAccess // resources.ApplyResources(this.buttonGrantAccess, "buttonGrantAccess"); this.buttonGrantAccess.Name = "buttonGrantAccess"; this.buttonGrantAccess.UseVisualStyleBackColor = true; this.buttonGrantAccess.Click += new System.EventHandler(this.buttonGrantAccess_Click); // // entryListView // this.entryListView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.ColumnName, this.ColumnResolveStatus, this.ColumnGrantAccess}); this.tableLayoutPanel1.SetColumnSpan(this.entryListView, 2); resources.ApplyResources(this.entryListView, "entryListView"); this.entryListView.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable; this.entryListView.Name = "entryListView"; this.entryListView.UseCompatibleStateImageBehavior = false; this.entryListView.View = System.Windows.Forms.View.Details; // // ColumnName // resources.ApplyResources(this.ColumnName, "ColumnName"); // // ColumnResolveStatus // resources.ApplyResources(this.ColumnResolveStatus, "ColumnResolveStatus"); // // ColumnGrantAccess // resources.ApplyResources(this.ColumnGrantAccess, "ColumnGrantAccess"); // // progressBar1 // this.tableLayoutPanel1.SetColumnSpan(this.progressBar1, 2); resources.ApplyResources(this.progressBar1, "progressBar1"); this.progressBar1.Name = "progressBar1"; // // LabelStatus // resources.ApplyResources(this.LabelStatus, "LabelStatus"); this.tableLayoutPanel1.SetColumnSpan(this.LabelStatus, 2); this.LabelStatus.Name = "LabelStatus"; // // labelTopBlurb // resources.ApplyResources(this.labelTopBlurb, "labelTopBlurb"); this.tableLayoutPanel1.SetColumnSpan(this.labelTopBlurb, 2); this.labelTopBlurb.MaximumSize = new System.Drawing.Size(631, 80); this.labelTopBlurb.Name = "labelTopBlurb"; // // tableLayoutPanel1 // resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1"); this.tableLayoutPanel1.Controls.Add(this.textBoxUserNames, 1, 2); this.tableLayoutPanel1.Controls.Add(this.labelTopBlurb, 0, 0); this.tableLayoutPanel1.Controls.Add(this.LabelStatus, 0, 5); this.tableLayoutPanel1.Controls.Add(this.progressBar1, 0, 4); this.tableLayoutPanel1.Controls.Add(this.entryListView, 0, 3); this.tableLayoutPanel1.Controls.Add(this.flowLayoutPanel1, 0, 6); this.tableLayoutPanel1.Controls.Add(this.label2, 0, 2); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; // // textBoxUserNames // resources.ApplyResources(this.textBoxUserNames, "textBoxUserNames"); this.textBoxUserNames.Name = "textBoxUserNames"; this.textBoxUserNames.TextChanged += new System.EventHandler(this.textBoxUserNames_TextChanged); this.textBoxUserNames.KeyUp += new System.Windows.Forms.KeyEventHandler(this.textBoxUserNames_KeyUp); // // label2 // resources.ApplyResources(this.label2, "label2"); this.label2.Name = "label2"; // // ResolvingSubjectsDialog // this.AcceptButton = this.buttonGrantAccess; resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.CancelButton = this.ButtonCancel; this.Controls.Add(this.tableLayoutPanel1); this.Name = "ResolvingSubjectsDialog"; this.tableLayoutPanelAddUsers.ResumeLayout(false); this.tableLayoutPanelAddUsers.PerformLayout(); this.flowLayoutPanel1.ResumeLayout(false); this.tableLayoutPanel1.ResumeLayout(false); this.tableLayoutPanel1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TableLayoutPanel tableLayoutPanelAddUsers; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox textBoxNames; private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1; private System.Windows.Forms.ListView entryListView; private System.Windows.Forms.ColumnHeader ColumnName; private System.Windows.Forms.ColumnHeader ColumnResolveStatus; private System.Windows.Forms.ColumnHeader ColumnGrantAccess; private System.Windows.Forms.ProgressBar progressBar1; private System.Windows.Forms.Label LabelStatus; private System.Windows.Forms.Label labelTopBlurb; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; private System.Windows.Forms.TextBox textBoxUserNames; private System.Windows.Forms.Label label2; private System.Windows.Forms.Button buttonGrantAccess; private System.Windows.Forms.Button ButtonCancel; } }
stephen-turner/xenadmin
XenAdmin/Dialogs/ResolvingSubjectsDialog.Designer.cs
C#
bsd-2-clause
9,627
/// Copyright (c) 2012 Ecma International. All rights reserved. /** * @path ch15/15.2/15.2.3/15.2.3.7/15.2.3.7-6-a-286.js * @description Object.defineProperties - 'O' is an Arguments object, 'P' is own accessor property of 'O' which is also defined in [[ParameterMap]] of 'O', test TypeError is thrown when updating the [[Get]] attribute value of 'P' which is defined as non-configurable (10.6 [[DefineOwnProperty]] step 4) */ function testcase() { var arg; (function fun(a, b, c) { arg = arguments; } (0, 1, 2)); function get_func1() { return 0; } Object.defineProperty(arg, "0", { get: get_func1, enumerable: false, configurable: false }); function get_func2() { return 10; } try { Object.defineProperties(arg, { "0": { get: get_func2 } }); return false; } catch (e) { var desc = Object.getOwnPropertyDescriptor(arg, "0"); return e instanceof TypeError && desc.get === get_func1 && typeof desc.set === "undefined" && desc.enumerable === false && desc.configurable === false; } } runTestCase(testcase);
mgentile/jint
Jint.Tests.Ecma/TestCases/ch15/15.2/15.2.3/15.2.3.7/15.2.3.7-6-a-286.js
JavaScript
bsd-2-clause
1,317
""" Tools for Sphinx to build docs and/or websites. """ import os import os.path as op import sys import shutil if sys.version_info[0] < 3: input = raw_input # noqa def sh(cmd): """Execute command in a subshell, return status code.""" return subprocess.check_call(cmd, shell=True) def sh2(cmd): """Execute command in a subshell, return stdout. Stderr is unbuffered from the subshell.""" p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True) out = p.communicate()[0] retcode = p.returncode if retcode: raise subprocess.CalledProcessError(retcode, cmd) else: return out.rstrip().decode('utf-8', 'ignore') def sphinx_clean(build_dir): if op.isdir(build_dir): shutil.rmtree(build_dir) os.mkdir(build_dir) print('Cleared build directory.') def sphinx_build(src_dir, build_dir): import sphinx try: ret = 0 ret = sphinx.main(['sphinx-build', # Dummy '-b', 'html', '-d', op.join(build_dir, 'doctrees'), src_dir, # Source op.join(build_dir, 'html'), # Dest ]) except SystemExit: pass if ret != 0: raise RuntimeError('Sphinx error: %s' % ret) print("Build finished. The HTML pages are in %s/html." % build_dir) def sphinx_show(html_dir): index_html = op.join(html_dir, 'index.html') if not op.isfile(index_html): sys.exit('Cannot show pages, build the html first.') import webbrowser webbrowser.open_new_tab(index_html) def sphinx_copy_pages(html_dir, pages_dir, pages_repo): print('COPYING PAGES') # Create the pages repo if needed if not op.isdir(pages_dir): os.chdir(ROOT_DIR) sh("git clone %s %s" % (pages_repo, pages_dir)) # Ensure that its up to date os.chdir(pages_dir) sh('git checkout master -q') sh('git pull -q') os.chdir('..') # This is pretty unforgiving: we unconditionally nuke the destination # directory, and then copy the html tree in there tmp_git_dir = op.join(ROOT_DIR, pages_dir + '_git') shutil.move(op.join(pages_dir, '.git'), tmp_git_dir) try: shutil.rmtree(pages_dir) shutil.copytree(html_dir, pages_dir) shutil.move(tmp_git_dir, op.join(pages_dir, '.git')) finally: if op.isdir(tmp_git_dir): shutil.rmtree(tmp_git_dir) # Copy individual files open(op.join(pages_dir, 'README.md'), 'wb').write( 'Autogenerated website - do not edit\n'.encode('utf-8')) for fname in ['CNAME', '.nojekyll']: # nojekyll or website wont work if op.isfile(op.join(WEBSITE_DIR, fname)): shutil.copyfile(op.join(WEBSITE_DIR, fname), op.join(pages_dir, fname)) # Messages os.chdir(pages_dir) sh('git status') print() print("Website copied to _gh-pages. Above you can see its status:") print(" Run 'make website show' to view.") print(" Run 'make website upload' to commit and push.") def sphinx_upload(repo_dir): # Check head os.chdir(repo_dir) status = sh2('git status | head -1') branch = re.match('On branch (.*)$', status).group(1) if branch != 'master': e = 'On %r, git branch is %r, MUST be "master"' % (repo_dir, branch) raise RuntimeError(e) # Show repo and ask confirmation print() print('You are about to commit to:') sh('git config --get remote.origin.url') print() print('Most recent 3 commits:') sys.stdout.flush() sh('git --no-pager log --oneline -n 3') ok = input('Are you sure you want to commit and push? (y/[n]): ') ok = ok or 'n' # If ok, add, commit, push if ok.lower() == 'y': sh('git add .') sh('git commit -am"Update (automated commit)"') print() sh('git push')
thezawad/flexx
make/_sphinx.py
Python
bsd-2-clause
3,982
<?php abstract class RequestsTest_Transport_Base extends PHPUnit_Framework_TestCase { public function setUp() { $callback = array($this->transport, 'test'); $supported = call_user_func($callback); if (!$supported) { $this->markTestSkipped($this->transport . ' is not available'); return; } $ssl_supported = call_user_func($callback, array('ssl' => true)); if (!$ssl_supported) { $this->skip_https = true; } } protected $skip_https = false; protected function getOptions($other = array()) { $options = array( 'transport' => $this->transport ); $options = array_merge($options, $other); return $options; } public function testSimpleGET() { $request = Requests::get(httpbin('/get'), array(), $this->getOptions()); $this->assertEquals(200, $request->status_code); $result = json_decode($request->body, true); $this->assertEquals(httpbin('/get'), $result['url']); $this->assertEmpty($result['args']); } public function testGETWithArgs() { $request = Requests::get(httpbin('/get?test=true&test2=test'), array(), $this->getOptions()); $this->assertEquals(200, $request->status_code); $result = json_decode($request->body, true); $this->assertEquals(httpbin('/get?test=true&test2=test'), $result['url']); $this->assertEquals(array('test' => 'true', 'test2' => 'test'), $result['args']); } public function testGETWithData() { $data = array( 'test' => 'true', 'test2' => 'test', ); $request = Requests::request(httpbin('/get'), array(), $data, Requests::GET, $this->getOptions()); $this->assertEquals(200, $request->status_code); $result = json_decode($request->body, true); $this->assertEquals(httpbin('/get?test=true&test2=test'), $result['url']); $this->assertEquals(array('test' => 'true', 'test2' => 'test'), $result['args']); } public function testGETWithNestedData() { $data = array( 'test' => 'true', 'test2' => array( 'test3' => 'test', 'test4' => 'test-too', ), ); $request = Requests::request(httpbin('/get'), array(), $data, Requests::GET, $this->getOptions()); $this->assertEquals(200, $request->status_code); $result = json_decode($request->body, true); $this->assertEquals(httpbin('/get?test=true&test2%5Btest3%5D=test&test2%5Btest4%5D=test-too'), $result['url']); $this->assertEquals(array('test' => 'true', 'test2[test3]' => 'test', 'test2[test4]' => 'test-too'), $result['args']); } public function testGETWithDataAndQuery() { $data = array( 'test2' => 'test', ); $request = Requests::request(httpbin('/get?test=true'), array(), $data, Requests::GET, $this->getOptions()); $this->assertEquals(200, $request->status_code); $result = json_decode($request->body, true); $this->assertEquals(httpbin('/get?test=true&test2=test'), $result['url']); $this->assertEquals(array('test' => 'true', 'test2' => 'test'), $result['args']); } public function testGETWithHeaders() { $headers = array( 'Requested-At' => time(), ); $request = Requests::get(httpbin('/get'), $headers, $this->getOptions()); $this->assertEquals(200, $request->status_code); $result = json_decode($request->body, true); $this->assertEquals($headers['Requested-At'], $result['headers']['Requested-At']); } public function testChunked() { $request = Requests::get(httpbin('/stream/1'), array(), $this->getOptions()); $this->assertEquals(200, $request->status_code); $result = json_decode($request->body, true); $this->assertEquals(httpbin('/stream/1'), $result['url']); $this->assertEmpty($result['args']); } public function testHEAD() { $request = Requests::head(httpbin('/get'), array(), $this->getOptions()); $this->assertEquals(200, $request->status_code); $this->assertEquals('', $request->body); } public function testRawPOST() { $data = 'test'; $request = Requests::post(httpbin('/post'), array(), $data, $this->getOptions()); $this->assertEquals(200, $request->status_code); $result = json_decode($request->body, true); $this->assertEquals('test', $result['data']); } public function testFormPost() { $data = 'test=true&test2=test'; $request = Requests::post(httpbin('/post'), array(), $data, $this->getOptions()); $this->assertEquals(200, $request->status_code); $result = json_decode($request->body, true); $this->assertEquals(array('test' => 'true', 'test2' => 'test'), $result['form']); } public function testPOSTWithArray() { $data = array( 'test' => 'true', 'test2' => 'test', ); $request = Requests::post(httpbin('/post'), array(), $data, $this->getOptions()); $this->assertEquals(200, $request->status_code); $result = json_decode($request->body, true); $this->assertEquals(array('test' => 'true', 'test2' => 'test'), $result['form']); } public function testPOSTWithNestedData() { $data = array( 'test' => 'true', 'test2' => array( 'test3' => 'test', 'test4' => 'test-too', ), ); $request = Requests::post(httpbin('/post'), array(), $data, $this->getOptions()); $this->assertEquals(200, $request->status_code); $result = json_decode($request->body, true); $this->assertEquals(array('test' => 'true', 'test2[test3]' => 'test', 'test2[test4]' => 'test-too'), $result['form']); } public function testRawPUT() { $data = 'test'; $request = Requests::put(httpbin('/put'), array(), $data, $this->getOptions()); $this->assertEquals(200, $request->status_code); $result = json_decode($request->body, true); $this->assertEquals('test', $result['data']); } public function testFormPUT() { $data = 'test=true&test2=test'; $request = Requests::put(httpbin('/put'), array(), $data, $this->getOptions()); $this->assertEquals(200, $request->status_code); $result = json_decode($request->body, true); $this->assertEquals(array('test' => 'true', 'test2' => 'test'), $result['form']); } public function testPUTWithArray() { $data = array( 'test' => 'true', 'test2' => 'test', ); $request = Requests::put(httpbin('/put'), array(), $data, $this->getOptions()); $this->assertEquals(200, $request->status_code); $result = json_decode($request->body, true); $this->assertEquals(array('test' => 'true', 'test2' => 'test'), $result['form']); } public function testRawPATCH() { $data = 'test'; $request = Requests::patch(httpbin('/patch'), array(), $data, $this->getOptions()); $this->assertEquals(200, $request->status_code); $result = json_decode($request->body, true); $this->assertEquals('test', $result['data']); } public function testFormPATCH() { $data = 'test=true&test2=test'; $request = Requests::patch(httpbin('/patch'), array(), $data, $this->getOptions()); $this->assertEquals(200, $request->status_code, $request->body); $result = json_decode($request->body, true); $this->assertEquals(array('test' => 'true', 'test2' => 'test'), $result['form']); } public function testPATCHWithArray() { $data = array( 'test' => 'true', 'test2' => 'test', ); $request = Requests::patch(httpbin('/patch'), array(), $data, $this->getOptions()); $this->assertEquals(200, $request->status_code); $result = json_decode($request->body, true); $this->assertEquals(array('test' => 'true', 'test2' => 'test'), $result['form']); } public function testDELETE() { $request = Requests::delete(httpbin('/delete'), array(), $this->getOptions()); $this->assertEquals(200, $request->status_code); $result = json_decode($request->body, true); $this->assertEquals(httpbin('/delete'), $result['url']); $this->assertEmpty($result['args']); } public function testDELETEWithData() { $data = array( 'test' => 'true', 'test2' => 'test', ); $request = Requests::request(httpbin('/delete'), array(), $data, Requests::DELETE, $this->getOptions()); $this->assertEquals(200, $request->status_code); $result = json_decode($request->body, true); $this->assertEquals(httpbin('/delete?test=true&test2=test'), $result['url']); $this->assertEquals(array('test' => 'true', 'test2' => 'test'), $result['args']); } public function testRedirects() { $request = Requests::get(httpbin('/redirect/6'), array(), $this->getOptions()); $this->assertEquals(200, $request->status_code); $this->assertEquals(6, $request->redirects); } public function testRelativeRedirects() { $request = Requests::get(httpbin('/relative-redirect/6'), array(), $this->getOptions()); $this->assertEquals(200, $request->status_code); $this->assertEquals(6, $request->redirects); } /** * @expectedException Requests_Exception * @todo This should also check that the type is "toomanyredirects" */ public function testTooManyRedirects() { $options = array( 'redirects' => 10, // default, but force just in case ); $request = Requests::get(httpbin('/redirect/11'), array(), $this->getOptions($options)); } public static function statusCodeSuccessProvider() { return array( array(200, true), array(201, true), array(202, true), array(203, true), array(204, true), array(205, true), array(206, true), array(300, false), array(301, false), array(302, false), array(303, false), array(304, false), array(305, false), array(306, false), array(307, false), array(400, false), array(401, false), array(402, false), array(403, false), array(404, false), array(405, false), array(406, false), array(407, false), array(408, false), array(409, false), array(410, false), array(411, false), array(412, false), array(413, false), array(414, false), array(415, false), array(416, false), array(417, false), array(418, false), // RFC 2324 array(428, false), // RFC 6585 array(429, false), // RFC 6585 array(431, false), // RFC 6585 array(500, false), array(501, false), array(502, false), array(503, false), array(504, false), array(505, false), array(511, false), // RFC 6585 ); } /** * @dataProvider statusCodeSuccessProvider */ public function testStatusCode($code, $success) { $url = sprintf(httpbin('/status/%d'), $code); $options = array( 'follow_redirects' => false, ); $request = Requests::get($url, array(), $this->getOptions($options)); $this->assertEquals($code, $request->status_code); $this->assertEquals($success, $request->success); } /** * @dataProvider statusCodeSuccessProvider */ public function testStatusCodeThrow($code, $success) { $url = sprintf(httpbin('/status/%d'), $code); $options = array( 'follow_redirects' => false, ); if (!$success) { if ($code >= 400) { $this->setExpectedException('Requests_Exception_HTTP_' . $code, $code); } elseif ($code >= 300 && $code < 400) { $this->setExpectedException('Requests_Exception'); } } $request = Requests::get($url, array(), $this->getOptions($options)); $request->throw_for_status(false); } /** * @dataProvider statusCodeSuccessProvider */ public function testStatusCodeThrowAllowRedirects($code, $success) { $url = sprintf(httpbin('/status/%d'), $code); $options = array( 'follow_redirects' => false, ); if (!$success) { if ($code >= 400) { $this->setExpectedException('Requests_Exception_HTTP_' . $code, $code); } } $request = Requests::get($url, array(), $this->getOptions($options)); $request->throw_for_status(true); } public function testStatusCodeUnknown(){ $request = Requests::get(httpbin('/status/599'), array(), $this->getOptions()); $this->assertEquals(599, $request->status_code); $this->assertEquals(false, $request->success); } /** * @expectedException Requests_Exception_HTTP_Unknown */ public function testStatusCodeThrowUnknown(){ $request = Requests::get(httpbin('/status/599'), array(), $this->getOptions()); $request->throw_for_status(true); } public function testGzipped() { $request = Requests::get(httpbin('/gzip'), array(), $this->getOptions()); $this->assertEquals(200, $request->status_code); $result = json_decode($request->body); $this->assertEquals(true, $result->gzipped); } public function testStreamToFile() { $options = array( 'filename' => tempnam(sys_get_temp_dir(), 'RLT') // RequestsLibraryTest ); $request = Requests::get(httpbin('/get'), array(), $this->getOptions($options)); $this->assertEquals(200, $request->status_code); $this->assertEmpty($request->body); $contents = file_get_contents($options['filename']); $result = json_decode($contents, true); $this->assertEquals(httpbin('/get'), $result['url']); $this->assertEmpty($result['args']); unlink($options['filename']); } public function testNonblocking() { $options = array( 'blocking' => false ); $request = Requests::get(httpbin('/get'), array(), $this->getOptions($options)); $empty = new Requests_Response(); $this->assertEquals($empty, $request); } /** * @expectedException Requests_Exception */ public function testBadIP() { $request = Requests::get('http://256.256.256.0/', array(), $this->getOptions()); } public function testHTTPS() { if ($this->skip_https) { $this->markTestSkipped('SSL support is not available.'); return; } $request = Requests::get(httpbin('/get', true), array(), $this->getOptions()); $this->assertEquals(200, $request->status_code); $result = json_decode($request->body, true); // Disable, since httpbin always returns http // $this->assertEquals(httpbin('/get', true), $result['url']); $this->assertEmpty($result['args']); } /** * @expectedException Requests_Exception */ public function testExpiredHTTPS() { if ($this->skip_https) { $this->markTestSkipped('SSL support is not available.'); return; } $request = Requests::get('https://testssl-expire.disig.sk/index.en.html', array(), $this->getOptions()); } /** * @expectedException Requests_Exception */ public function testRevokedHTTPS() { if ($this->skip_https) { $this->markTestSkipped('SSL support is not available.'); return; } $request = Requests::get('https://testssl-revoked.disig.sk/index.en.html', array(), $this->getOptions()); } /** * Test that SSL fails with a bad certificate * * This is defined as invalid by * https://onlinessl.netlock.hu/en/test-center/invalid-ssl-certificate.html * and is used in testing in PhantomJS. That said, expect this to break. * * @expectedException Requests_Exception */ public function testBadDomain() { if ($this->skip_https) { $this->markTestSkipped('SSL support is not available.'); return; } $request = Requests::get('https://tv.eurosport.com/', array(), $this->getOptions()); } /** * Test that the transport supports Server Name Indication with HTTPS * * sni.velox.ch is used for SNI testing, and the common name is set to * `*.sni.velox.ch` as such. Without alternate name support, this will fail * as `sni.velox.ch` is only in the alternate name */ public function testAlternateNameSupport() { if ($this->skip_https) { $this->markTestSkipped('SSL support is not available.'); return; } $request = Requests::get('https://sni.velox.ch/', array(), $this->getOptions()); $this->assertEquals(200, $request->status_code); } /** * Test that the transport supports Server Name Indication with HTTPS * * sni.velox.ch is used for SNI testing, and the common name is set to * `*.sni.velox.ch` as such. Without SNI support, this will fail. Also tests * our wildcard support. */ public function testSNISupport() { if ($this->skip_https) { $this->markTestSkipped('SSL support is not available.'); return; } $request = Requests::get('https://abc.sni.velox.ch/', array(), $this->getOptions()); $this->assertEquals(200, $request->status_code); } /** * @expectedException Requests_Exception */ public function testTimeout() { $options = array( 'timeout' => 1, ); $request = Requests::get(httpbin('/delay/10'), array(), $this->getOptions($options)); var_dump($request); } public function testMultiple() { $requests = array( 'test1' => array( 'url' => httpbin('/get') ), 'test2' => array( 'url' => httpbin('/get') ), ); $responses = Requests::request_multiple($requests, $this->getOptions()); // test1 $this->assertNotEmpty($responses['test1']); $this->assertInstanceOf('Requests_Response', $responses['test1']); $this->assertEquals(200, $responses['test1']->status_code); $result = json_decode($responses['test1']->body, true); $this->assertEquals(httpbin('/get'), $result['url']); $this->assertEmpty($result['args']); // test2 $this->assertNotEmpty($responses['test2']); $this->assertInstanceOf('Requests_Response', $responses['test2']); $this->assertEquals(200, $responses['test2']->status_code); $result = json_decode($responses['test2']->body, true); $this->assertEquals(httpbin('/get'), $result['url']); $this->assertEmpty($result['args']); } public function testMultipleWithDifferingMethods() { $requests = array( 'get' => array( 'url' => httpbin('/get'), ), 'post' => array( 'url' => httpbin('/post'), 'type' => Requests::POST, 'data' => 'test', ), ); $responses = Requests::request_multiple($requests, $this->getOptions()); // get $this->assertEquals(200, $responses['get']->status_code); // post $this->assertEquals(200, $responses['post']->status_code); $result = json_decode($responses['post']->body, true); $this->assertEquals('test', $result['data']); } /** * @depends testTimeout */ public function testMultipleWithFailure() { $requests = array( 'success' => array( 'url' => httpbin('/get'), ), 'timeout' => array( 'url' => httpbin('/delay/10'), 'options' => array( 'timeout' => 1, ), ), ); $responses = Requests::request_multiple($requests, $this->getOptions()); $this->assertEquals(200, $responses['success']->status_code); $this->assertInstanceOf('Requests_Exception', $responses['timeout']); } public function testMultipleUsingCallback() { $requests = array( 'get' => array( 'url' => httpbin('/get'), ), 'post' => array( 'url' => httpbin('/post'), 'type' => Requests::POST, 'data' => 'test', ), ); $this->completed = array(); $options = array( 'complete' => array($this, 'completeCallback'), ); $responses = Requests::request_multiple($requests, $this->getOptions($options)); $this->assertEquals($this->completed, $responses); $this->completed = array(); } public function testMultipleUsingCallbackAndFailure() { $requests = array( 'success' => array( 'url' => httpbin('/get'), ), 'timeout' => array( 'url' => httpbin('/delay/10'), 'options' => array( 'timeout' => 1, ), ), ); $this->completed = array(); $options = array( 'complete' => array($this, 'completeCallback'), ); $responses = Requests::request_multiple($requests, $this->getOptions($options)); $this->assertEquals($this->completed, $responses); $this->completed = array(); } public function completeCallback($response, $key) { $this->completed[$key] = $response; } public function testMultipleToFile() { $requests = array( 'get' => array( 'url' => httpbin('/get'), 'options' => array( 'filename' => tempnam(sys_get_temp_dir(), 'RLT') // RequestsLibraryTest ), ), 'post' => array( 'url' => httpbin('/post'), 'type' => Requests::POST, 'data' => 'test', 'options' => array( 'filename' => tempnam(sys_get_temp_dir(), 'RLT') // RequestsLibraryTest ), ), ); $responses = Requests::request_multiple($requests, $this->getOptions()); // GET request $contents = file_get_contents($requests['get']['options']['filename']); $result = json_decode($contents, true); $this->assertEquals(httpbin('/get'), $result['url']); $this->assertEmpty($result['args']); unlink($requests['get']['options']['filename']); // POST request $contents = file_get_contents($requests['post']['options']['filename']); $result = json_decode($contents, true); $this->assertEquals(httpbin('/post'), $result['url']); $this->assertEquals('test', $result['data']); unlink($requests['post']['options']['filename']); } public function testHostHeader() { $request = Requests::get('http://portquiz.positon.org:8080/', array(), $this->getOptions()); $responseDoc = new DOMDocument; $responseDoc->loadHTML($request->body); $portXpath = new DOMXPath($responseDoc); $portXpathMatches = $portXpath->query('//p/b'); $this->assertEquals(8080, $portXpathMatches->item(0)->nodeValue); } }
No3x/sticky-notes
vendor/rmccue/requests/tests/Transport/Base.php
PHP
bsd-2-clause
20,610
require "language/go" class Influxdb < Formula desc "Time series, events, and metrics database" homepage "https://influxdb.com" stable do url "https://github.com/influxdb/influxdb/archive/v0.9.1.tar.gz" sha256 "a37d5ebda1b31f912390fe4e1d46e085326f91397671e2bd418f5d515004e5be" end bottle do cellar :any sha256 "f4244b8a3a9d71372cc822547ba97809e37731c95483ce89d9c4e21b171a366b" => :yosemite sha256 "c5a1f8fe170a6f2a5c9a6f5568600711d8d98eb28e74f5a37a54e906ba15c134" => :mavericks sha256 "5bbf255e5facc8d9060f1de5e25840e3c415dd37b9c2b9f20320a8d264b533e9" => :mountain_lion end devel do url "https://github.com/influxdb/influxdb/archive/v0.9.2-rc1.tar.gz" sha256 "1c90462fcacb1b14b17602c06fa6deb4161b3d9bff1c1d318c743bb1982062c9" version "0.9.2-rc1" end head do url "https://github.com/influxdb/influxdb.git" end depends_on "go" => :build go_resource "github.com/BurntSushi/toml" do url "https://github.com/BurntSushi/toml.git", :revision => "056c9bc7be7190eaa7715723883caffa5f8fa3e4" end go_resource "github.com/armon/go-metrics" do url "https://github.com/armon/go-metrics.git", :revision => "b2d95e5291cdbc26997d1301a5e467ecbb240e25" end go_resource "github.com/bmizerany/pat" do url "https://github.com/bmizerany/pat.git", :revision => "b8a35001b773c267eb260a691f4e5499a3531600" end go_resource "github.com/boltdb/bolt" do url "https://github.com/boltdb/bolt.git", :revision => "abb4088170cfac644ed5f4648a5cdc566cdb1da2" end go_resource "github.com/gogo/protobuf" do url "https://github.com/gogo/protobuf.git", :revision => "499788908625f4d83de42a204d1350fde8588e4f" end go_resource "github.com/golang/protobuf" do url "https://github.com/golang/protobuf.git", :revision => "34a5f244f1c01cdfee8e60324258cfbb97a42aec" end go_resource "github.com/hashicorp/go-msgpack" do url "https://github.com/hashicorp/go-msgpack.git", :revision => "fa3f63826f7c23912c15263591e65d54d080b458" end go_resource "github.com/hashicorp/raft" do url "https://github.com/hashicorp/raft.git", :revision => "379e28eb5a538707eae7a97ecc60846821217f27" end go_resource "github.com/hashicorp/raft-boltdb" do url "https://github.com/hashicorp/raft-boltdb.git", :revision => "d1e82c1ec3f15ee991f7cc7ffd5b67ff6f5bbaee" end go_resource "github.com/kimor79/gollectd" do url "https://github.com/kimor79/gollectd.git", :revision => "cf6dec97343244b5d8a5485463675d42f574aa2d" end go_resource "github.com/peterh/liner" do url "https://github.com/peterh/liner.git", :revision => "1bb0d1c1a25ed393d8feb09bab039b2b1b1fbced" end go_resource "github.com/rakyll/statik" do url "https://github.com/rakyll/statik.git", :revision => "274df120e9065bdd08eb1120e0375e3dc1ae8465" end go_resource "golang.org/x/crypto" do url "https://go.googlesource.com/crypto.git", :revision => "1e856cbfdf9bc25eefca75f83f25d55e35ae72e0" end go_resource "gopkg.in/fatih/pool.v2" do url "https://github.com/fatih/pool.git", :revision => "cba550ebf9bce999a02e963296d4bc7a486cb715" end go_resource "collectd.org" do url "https://github.com/collectd/go-collectd.git", :revision => "27f4f77337ae0b2de0d3267f6278d62aff8b52fb" end def install ENV["GOPATH"] = buildpath influxdb_path = buildpath/"src/github.com/influxdb/influxdb" influxdb_path.install Dir["*"] Language::Go.stage_deps resources, buildpath/"src" cd influxdb_path do if build.head? system "go", "install", "-ldflags", "-X main.version 0.9.3-HEAD -X main.commit #{`git rev-parse HEAD`.strip}", "./..." elsif build.devel? system "go", "install", "-ldflags", "-X main.version 0.9.2-rc1 -X main.commit f404a8ac31360c380e0ebcf1f1481411cda02fc1", "./..." else system "go", "install", "-ldflags", "-X main.version 0.9.1 -X main.commit 8b3219e74fcc3843a6f4901bdf00e905642b6bd6", "./..." end end inreplace influxdb_path/"etc/config.sample.toml" do |s| s.gsub! "/var/opt/influxdb/data", "#{var}/influxdb/data" s.gsub! "/var/opt/influxdb/meta", "#{var}/influxdb/meta" s.gsub! "/var/opt/influxdb/hh", "#{var}/influxdb/hh" end bin.install buildpath/"bin/influxd" bin.install buildpath/"bin/influx" etc.install influxdb_path/"etc/config.sample.toml" => "influxdb.conf" (var/"influxdb/data").mkpath (var/"influxdb/meta").mkpath (var/"influxdb/hh").mkpath end plist_options :manual => "influxd -config #{HOMEBREW_PREFIX}/etc/influxdb.conf" def plist; <<-EOS.undent <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>KeepAlive</key> <dict> <key>SuccessfulExit</key> <false/> </dict> <key>Label</key> <string>#{plist_name}</string> <key>ProgramArguments</key> <array> <string>#{opt_bin}/influxd</string> <string>-config</string> <string>#{HOMEBREW_PREFIX}/etc/influxdb.conf</string> </array> <key>RunAtLoad</key> <true/> <key>WorkingDirectory</key> <string>#{var}</string> <key>StandardErrorPath</key> <string>#{var}/log/influxdb.log</string> <key>StandardOutPath</key> <string>#{var}/log/influxdb.log</string> </dict> </plist> EOS end def caveats; <<-EOS.undent Config files from old InfluxDB versions are incompatible with version 0.9. If upgrading from a pre-0.9 version, the new configuration file will be named: #{etc}/influxdb.conf.default To generate a new config file: influxd config > influxdb.conf.generated EOS end end
klazuka/homebrew
Library/Formula/influxdb.rb
Ruby
bsd-2-clause
5,819
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <title>RakNet: RakNet::Friends_GetFriends Struct Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">RakNet &#160;<span id="projectnumber">4.0</span> </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.2 --> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li><a href="modules.html"><span>Modules</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="namespaceRakNet.html">RakNet</a></li><li class="navelem"><a class="el" href="structRakNet_1_1Friends__GetFriends.html">Friends_GetFriends</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="summary"> <a href="#pub-methods">Public Member Functions</a> &#124; <a href="structRakNet_1_1Friends__GetFriends-members.html">List of all members</a> </div> <div class="headertitle"> <div class="title">RakNet::Friends_GetFriends Struct Reference<div class="ingroups"><a class="el" href="group__LOBBY__2__COMMANDS.html">Lobby2Commands</a></div></div> </div> </div><!--header--> <div class="contents"> <p>Gets all friends to this user. <a href="structRakNet_1_1Friends__GetFriends.html#details">More...</a></p> <p><code>#include &lt;Lobby2Message.h&gt;</code></p> <div class="dynheader"> Inheritance diagram for RakNet::Friends_GetFriends:</div> <div class="dyncontent"> <div class="center"> <img src="structRakNet_1_1Friends__GetFriends.png" usemap="#RakNet::Friends_GetFriends_map" alt=""/> <map id="RakNet::Friends_GetFriends_map" name="RakNet::Friends_GetFriends_map"> <area href="structRakNet_1_1Lobby2Message.html" title="A Lobby2Message encapsulates a networked function call from the client." alt="RakNet::Lobby2Message" shape="rect" coords="0,0,170,24"/> </map> </div></div> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-methods"></a> Public Member Functions</h2></td></tr> <tr class="memitem:acb16ae107cce089a48d660aa4682ce90"><td class="memItemLeft" align="right" valign="top">virtual bool&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="structRakNet_1_1Friends__GetFriends.html#acb16ae107cce089a48d660aa4682ce90">RequiresAdmin</a> (void) const </td></tr> <tr class="separator:acb16ae107cce089a48d660aa4682ce90"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:accf6f9d2c879e8ee04ae01d34ffa1aa3"><td class="memItemLeft" align="right" valign="top">virtual bool&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="structRakNet_1_1Friends__GetFriends.html#accf6f9d2c879e8ee04ae01d34ffa1aa3">RequiresRankingPermission</a> (void) const </td></tr> <tr class="separator:accf6f9d2c879e8ee04ae01d34ffa1aa3"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a7a5aa0b074a0faea29ff41fea372c197"><td class="memItemLeft" align="right" valign="top">virtual bool&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="structRakNet_1_1Friends__GetFriends.html#a7a5aa0b074a0faea29ff41fea372c197">CancelOnDisconnect</a> (void) const </td></tr> <tr class="separator:a7a5aa0b074a0faea29ff41fea372c197"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a23828e205733865e40e14e73f423c220"><td class="memItemLeft" align="right" valign="top">virtual bool&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="structRakNet_1_1Friends__GetFriends.html#a23828e205733865e40e14e73f423c220">RequiresLogin</a> (void) const </td></tr> <tr class="separator:a23828e205733865e40e14e73f423c220"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:aab059f44e897ac7ffdb048779a2b4708"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="aab059f44e897ac7ffdb048779a2b4708"></a> virtual void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="structRakNet_1_1Friends__GetFriends.html#aab059f44e897ac7ffdb048779a2b4708">Serialize</a> (bool writeToBitstream, bool serializeOutput, <a class="el" href="classRakNet_1_1BitStream.html">RakNet::BitStream</a> *bitStream)</td></tr> <tr class="memdesc:aab059f44e897ac7ffdb048779a2b4708"><td class="mdescLeft">&#160;</td><td class="mdescRight">Overridable serialization of the contents of this message. Defaults to SerializeBase() <br/></td></tr> <tr class="separator:aab059f44e897ac7ffdb048779a2b4708"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="inherit_header pub_methods_structRakNet_1_1Lobby2Message"><td colspan="2" onclick="javascript:toggleInherit('pub_methods_structRakNet_1_1Lobby2Message')"><img src="closed.png" alt="-"/>&#160;Public Member Functions inherited from <a class="el" href="structRakNet_1_1Lobby2Message.html">RakNet::Lobby2Message</a></td></tr> <tr class="memitem:a92248c1609297987f41dbfcfd75806f9 inherit pub_methods_structRakNet_1_1Lobby2Message"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a92248c1609297987f41dbfcfd75806f9"></a> virtual <a class="el" href="group__LOBBY__2__COMMANDS.html#gaf20aff5b3604dbaad834c046a03d8299">Lobby2MessageID</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="structRakNet_1_1Lobby2Message.html#a92248c1609297987f41dbfcfd75806f9">GetID</a> (void) const =0</td></tr> <tr class="memdesc:a92248c1609297987f41dbfcfd75806f9 inherit pub_methods_structRakNet_1_1Lobby2Message"><td class="mdescLeft">&#160;</td><td class="mdescRight">Every message has an ID identifying it across the network. <br/></td></tr> <tr class="separator:a92248c1609297987f41dbfcfd75806f9 inherit pub_methods_structRakNet_1_1Lobby2Message"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a419b02230facc25fe97e364ee914e996 inherit pub_methods_structRakNet_1_1Lobby2Message"><td class="memItemLeft" align="right" valign="top">virtual bool&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="structRakNet_1_1Lobby2Message.html#a419b02230facc25fe97e364ee914e996">PrevalidateInput</a> (void)</td></tr> <tr class="separator:a419b02230facc25fe97e364ee914e996 inherit pub_methods_structRakNet_1_1Lobby2Message"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a73681a9a5bcfe6d7344cb7500c1bae72 inherit pub_methods_structRakNet_1_1Lobby2Message"><td class="memItemLeft" align="right" valign="top">virtual bool&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="structRakNet_1_1Lobby2Message.html#a73681a9a5bcfe6d7344cb7500c1bae72">ClientImpl</a> (<a class="el" href="classRakNet_1_1Lobby2Plugin.html">RakNet::Lobby2Plugin</a> *client)</td></tr> <tr class="separator:a73681a9a5bcfe6d7344cb7500c1bae72 inherit pub_methods_structRakNet_1_1Lobby2Message"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a7d2c66bbb0ffbcda05e83e936976c41a inherit pub_methods_structRakNet_1_1Lobby2Message"><td class="memItemLeft" align="right" valign="top">virtual void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="structRakNet_1_1Lobby2Message.html#a7d2c66bbb0ffbcda05e83e936976c41a">CallCallback</a> (<a class="el" href="structRakNet_1_1Lobby2Callbacks.html">Lobby2Callbacks</a> *cb)=0</td></tr> <tr class="separator:a7d2c66bbb0ffbcda05e83e936976c41a inherit pub_methods_structRakNet_1_1Lobby2Message"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a5213270ccd16a7bc6afc8df001b623e7 inherit pub_methods_structRakNet_1_1Lobby2Message"><td class="memItemLeft" align="right" valign="top">virtual bool&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="structRakNet_1_1Lobby2Message.html#a5213270ccd16a7bc6afc8df001b623e7">ServerPreDBMemoryImpl</a> (<a class="el" href="classRakNet_1_1Lobby2Server.html">Lobby2Server</a> *server, <a class="el" href="classRakNet_1_1RakString.html">RakString</a> userHandle)</td></tr> <tr class="separator:a5213270ccd16a7bc6afc8df001b623e7 inherit pub_methods_structRakNet_1_1Lobby2Message"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a62cc92ba3fb0e6562cf77d929d231a35 inherit pub_methods_structRakNet_1_1Lobby2Message"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a62cc92ba3fb0e6562cf77d929d231a35"></a> virtual void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="structRakNet_1_1Lobby2Message.html#a62cc92ba3fb0e6562cf77d929d231a35">ServerPostDBMemoryImpl</a> (<a class="el" href="classRakNet_1_1Lobby2Server.html">Lobby2Server</a> *server, <a class="el" href="classRakNet_1_1RakString.html">RakString</a> userHandle)</td></tr> <tr class="memdesc:a62cc92ba3fb0e6562cf77d929d231a35 inherit pub_methods_structRakNet_1_1Lobby2Message"><td class="mdescLeft">&#160;</td><td class="mdescRight">Do any <a class="el" href="classRakNet_1_1Lobby2Server.html" title="The base class for the lobby server, without database specific functionality.">Lobby2Server</a> functionality after the message has been processed by the database, in the server thread. <br/></td></tr> <tr class="separator:a62cc92ba3fb0e6562cf77d929d231a35 inherit pub_methods_structRakNet_1_1Lobby2Message"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a39a885f1a8d8b636e5c7bbeb13d4f822 inherit pub_methods_structRakNet_1_1Lobby2Message"><td class="memItemLeft" align="right" valign="top">virtual bool&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="structRakNet_1_1Lobby2Message.html#a39a885f1a8d8b636e5c7bbeb13d4f822">ServerDBImpl</a> (<a class="el" href="structRakNet_1_1Lobby2ServerCommand.html">Lobby2ServerCommand</a> *command, void *databaseInterface)</td></tr> <tr class="separator:a39a885f1a8d8b636e5c7bbeb13d4f822 inherit pub_methods_structRakNet_1_1Lobby2Message"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a6a85caa9e47c7d9fec7f156c5e7c723a inherit pub_methods_structRakNet_1_1Lobby2Message"><td class="memItemLeft" align="right" valign="top">bool&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="structRakNet_1_1Lobby2Message.html#a6a85caa9e47c7d9fec7f156c5e7c723a">ValidateHandle</a> (<a class="el" href="classRakNet_1_1RakString.html">RakNet::RakString</a> *handle)</td></tr> <tr class="separator:a6a85caa9e47c7d9fec7f156c5e7c723a inherit pub_methods_structRakNet_1_1Lobby2Message"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:af510ed0df868969f12118ea32027334b inherit pub_methods_structRakNet_1_1Lobby2Message"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="af510ed0df868969f12118ea32027334b"></a> bool&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="structRakNet_1_1Lobby2Message.html#af510ed0df868969f12118ea32027334b">ValidateBinary</a> (RakNetSmartPtr&lt; BinaryDataBlock &gt;binaryDataBlock)</td></tr> <tr class="memdesc:af510ed0df868969f12118ea32027334b inherit pub_methods_structRakNet_1_1Lobby2Message"><td class="mdescLeft">&#160;</td><td class="mdescRight">Binary data cannot be longer than L2_MAX_BINARY_DATA_LENGTH. <br/></td></tr> <tr class="separator:af510ed0df868969f12118ea32027334b inherit pub_methods_structRakNet_1_1Lobby2Message"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ada4ddbe1b8d880b6beb3cec2d107c3cf inherit pub_methods_structRakNet_1_1Lobby2Message"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ada4ddbe1b8d880b6beb3cec2d107c3cf"></a> bool&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="structRakNet_1_1Lobby2Message.html#ada4ddbe1b8d880b6beb3cec2d107c3cf">ValidateRequiredText</a> (<a class="el" href="classRakNet_1_1RakString.html">RakNet::RakString</a> *text)</td></tr> <tr class="memdesc:ada4ddbe1b8d880b6beb3cec2d107c3cf inherit pub_methods_structRakNet_1_1Lobby2Message"><td class="mdescLeft">&#160;</td><td class="mdescRight">Required text cannot be empty. <br/></td></tr> <tr class="separator:ada4ddbe1b8d880b6beb3cec2d107c3cf inherit pub_methods_structRakNet_1_1Lobby2Message"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a4cf58429201d0c452d354b6add784712 inherit pub_methods_structRakNet_1_1Lobby2Message"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a4cf58429201d0c452d354b6add784712"></a> bool&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="structRakNet_1_1Lobby2Message.html#a4cf58429201d0c452d354b6add784712">ValidatePassword</a> (<a class="el" href="classRakNet_1_1RakString.html">RakNet::RakString</a> *text)</td></tr> <tr class="memdesc:a4cf58429201d0c452d354b6add784712 inherit pub_methods_structRakNet_1_1Lobby2Message"><td class="mdescLeft">&#160;</td><td class="mdescRight">Passwords must contain at least 5 characters. <br/></td></tr> <tr class="separator:a4cf58429201d0c452d354b6add784712 inherit pub_methods_structRakNet_1_1Lobby2Message"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:aec0eeb9161acabd01464f4b875abed31 inherit pub_methods_structRakNet_1_1Lobby2Message"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="aec0eeb9161acabd01464f4b875abed31"></a> bool&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="structRakNet_1_1Lobby2Message.html#aec0eeb9161acabd01464f4b875abed31">ValidateEmailAddress</a> (<a class="el" href="classRakNet_1_1RakString.html">RakNet::RakString</a> *text)</td></tr> <tr class="memdesc:aec0eeb9161acabd01464f4b875abed31 inherit pub_methods_structRakNet_1_1Lobby2Message"><td class="mdescLeft">&#160;</td><td class="mdescRight">Check email address format. <br/></td></tr> <tr class="separator:aec0eeb9161acabd01464f4b875abed31 inherit pub_methods_structRakNet_1_1Lobby2Message"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ae417f773c4d48bc1cce69c656f2952fd inherit pub_methods_structRakNet_1_1Lobby2Message"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ae417f773c4d48bc1cce69c656f2952fd"></a> virtual const char *&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="structRakNet_1_1Lobby2Message.html#ae417f773c4d48bc1cce69c656f2952fd">GetName</a> (void) const =0</td></tr> <tr class="memdesc:ae417f773c4d48bc1cce69c656f2952fd inherit pub_methods_structRakNet_1_1Lobby2Message"><td class="mdescLeft">&#160;</td><td class="mdescRight">Convert the enumeration representing this message to a string, and return it. Done automatically by macros. <br/></td></tr> <tr class="separator:ae417f773c4d48bc1cce69c656f2952fd inherit pub_methods_structRakNet_1_1Lobby2Message"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ad48d6053a9d086c29dc3108e7de557dc inherit pub_methods_structRakNet_1_1Lobby2Message"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ad48d6053a9d086c29dc3108e7de557dc"></a> virtual void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="structRakNet_1_1Lobby2Message.html#ad48d6053a9d086c29dc3108e7de557dc">DebugMsg</a> (<a class="el" href="classRakNet_1_1RakString.html">RakNet::RakString</a> &amp;out) const =0</td></tr> <tr class="memdesc:ad48d6053a9d086c29dc3108e7de557dc inherit pub_methods_structRakNet_1_1Lobby2Message"><td class="mdescLeft">&#160;</td><td class="mdescRight">Write the result of this message to out(). Done automatically by macros. <br/></td></tr> <tr class="separator:ad48d6053a9d086c29dc3108e7de557dc inherit pub_methods_structRakNet_1_1Lobby2Message"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:accf4946d351e9bb17ad197fc21b0b473 inherit pub_methods_structRakNet_1_1Lobby2Message"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="accf4946d351e9bb17ad197fc21b0b473"></a> virtual void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="structRakNet_1_1Lobby2Message.html#accf4946d351e9bb17ad197fc21b0b473">DebugPrintf</a> (void) const </td></tr> <tr class="memdesc:accf4946d351e9bb17ad197fc21b0b473 inherit pub_methods_structRakNet_1_1Lobby2Message"><td class="mdescLeft">&#160;</td><td class="mdescRight">Print the result of DebugMsg. <br/></td></tr> <tr class="separator:accf4946d351e9bb17ad197fc21b0b473 inherit pub_methods_structRakNet_1_1Lobby2Message"><td class="memSeparator" colspan="2">&#160;</td></tr> </table><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="inherited"></a> Additional Inherited Members</h2></td></tr> <tr class="inherit_header pub_attribs_structRakNet_1_1Lobby2Message"><td colspan="2" onclick="javascript:toggleInherit('pub_attribs_structRakNet_1_1Lobby2Message')"><img src="closed.png" alt="-"/>&#160;Public Attributes inherited from <a class="el" href="structRakNet_1_1Lobby2Message.html">RakNet::Lobby2Message</a></td></tr> <tr class="memitem:a750b6a5d792d6f6c2532bfc7e3f74c99 inherit pub_attribs_structRakNet_1_1Lobby2Message"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a750b6a5d792d6f6c2532bfc7e3f74c99"></a> RakNet::Lobby2ResultCode&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="structRakNet_1_1Lobby2Message.html#a750b6a5d792d6f6c2532bfc7e3f74c99">resultCode</a></td></tr> <tr class="memdesc:a750b6a5d792d6f6c2532bfc7e3f74c99 inherit pub_attribs_structRakNet_1_1Lobby2Message"><td class="mdescLeft">&#160;</td><td class="mdescRight">Result of the operation. L2RC_SUCCESS means the result completed. Anything else means an error. <br/></td></tr> <tr class="separator:a750b6a5d792d6f6c2532bfc7e3f74c99 inherit pub_attribs_structRakNet_1_1Lobby2Message"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a6e29d665abe3559b60e9fadfb2fa1b40 inherit pub_attribs_structRakNet_1_1Lobby2Message"><td class="memItemLeft" align="right" valign="top">uint32_t&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="structRakNet_1_1Lobby2Message.html#a6e29d665abe3559b60e9fadfb2fa1b40">callbackId</a></td></tr> <tr class="separator:a6e29d665abe3559b60e9fadfb2fa1b40 inherit pub_attribs_structRakNet_1_1Lobby2Message"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a5046c82fcca8bac36babe863c55ec9eb inherit pub_attribs_structRakNet_1_1Lobby2Message"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a5046c82fcca8bac36babe863c55ec9eb"></a> int&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="structRakNet_1_1Lobby2Message.html#a5046c82fcca8bac36babe863c55ec9eb">extendedResultCode</a></td></tr> <tr class="memdesc:a5046c82fcca8bac36babe863c55ec9eb inherit pub_attribs_structRakNet_1_1Lobby2Message"><td class="mdescLeft">&#160;</td><td class="mdescRight">Used for consoles. <br/></td></tr> <tr class="separator:a5046c82fcca8bac36babe863c55ec9eb inherit pub_attribs_structRakNet_1_1Lobby2Message"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a49c6460be7043aa3dd8f69955a4fb426 inherit pub_attribs_structRakNet_1_1Lobby2Message"><td class="memItemLeft" align="right" valign="top">uint64_t&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="structRakNet_1_1Lobby2Message.html#a49c6460be7043aa3dd8f69955a4fb426">requestId</a></td></tr> <tr class="separator:a49c6460be7043aa3dd8f69955a4fb426 inherit pub_attribs_structRakNet_1_1Lobby2Message"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> <a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2> <div class="textblock"><p>Gets all friends to this user. </p> </div><h2 class="groupheader">Member Function Documentation</h2> <a class="anchor" id="a7a5aa0b074a0faea29ff41fea372c197"></a> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">virtual bool RakNet::Friends_GetFriends::CancelOnDisconnect </td> <td>(</td> <td class="paramtype">void&#160;</td> <td class="paramname"></td><td>)</td> <td> const</td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">inline</span><span class="mlabel">virtual</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>Should this message not be processed on the server if the requesting user disconnects before it completes? This should be true for functions that only return data. False for functions that affect other users, or change the database </p> <p>Implements <a class="el" href="structRakNet_1_1Lobby2Message.html#aeab0f7b852042f9d664cb7ee0b8b0458">RakNet::Lobby2Message</a>.</p> </div> </div> <a class="anchor" id="acb16ae107cce089a48d660aa4682ce90"></a> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">virtual bool RakNet::Friends_GetFriends::RequiresAdmin </td> <td>(</td> <td class="paramtype">void&#160;</td> <td class="paramname"></td><td>)</td> <td> const</td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">inline</span><span class="mlabel">virtual</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>Is this message something that should only be run by a system with admin privileges? Set admin privileges with <a class="el" href="classRakNet_1_1Lobby2Server.html#a499cbfd420d6a6caecd62a8143a641da" title="If Lobby2Message::RequiresAdmin() returns true, the message can only be processed from a remote syste...">Lobby2Server::AddAdminAddress()</a> </p> <p>Implements <a class="el" href="structRakNet_1_1Lobby2Message.html#a79cbb400e4521af2c353fbd640fed0f7">RakNet::Lobby2Message</a>.</p> </div> </div> <a class="anchor" id="a23828e205733865e40e14e73f423c220"></a> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">virtual bool RakNet::Friends_GetFriends::RequiresLogin </td> <td>(</td> <td class="paramtype">void&#160;</td> <td class="paramname"></td><td>)</td> <td> const</td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">inline</span><span class="mlabel">virtual</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>Does this function require logging into the server before it can be executed? If true, the user id and user handle will be automatically inferred by the last login by looking up the sender's system address. If false, the message should include the username so the database query can lookup which user is performing this operation. </p> <p>Implements <a class="el" href="structRakNet_1_1Lobby2Message.html#a575e23419cd160aca576b56ee7476227">RakNet::Lobby2Message</a>.</p> </div> </div> <a class="anchor" id="accf6f9d2c879e8ee04ae01d34ffa1aa3"></a> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">virtual bool RakNet::Friends_GetFriends::RequiresRankingPermission </td> <td>(</td> <td class="paramtype">void&#160;</td> <td class="paramname"></td><td>)</td> <td> const</td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">inline</span><span class="mlabel">virtual</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>Is this message something that should only be run by a system with ranking upload priviledges? Set ranking privileges with <a class="el" href="classRakNet_1_1Lobby2Server.html#a16a9ef14b0c08f5c01745908666064d5" title="If Lobby2Message::RequiresRankingPermission() returns true, then the system that sent the command mus...">Lobby2Server::AddRankingAddress()</a> </p> <p>Implements <a class="el" href="structRakNet_1_1Lobby2Message.html#a3eab67e30f491cd3410b9d850ffcecea">RakNet::Lobby2Message</a>.</p> </div> </div> <hr/>The documentation for this struct was generated from the following file:<ul> <li>D:/temp/RakNet_PC/DependentExtensions/Lobby2/Lobby2Message.h</li> </ul> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Mon Jun 2 2014 20:10:30 for RakNet by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.2 </small></address> </body> </html>
tamtam-im/RakNet
Help/Doxygen/html/structRakNet_1_1Friends__GetFriends.html
HTML
bsd-2-clause
26,068
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <title>RakNet: Member List</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">RakNet &#160;<span id="projectnumber">4.0</span> </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.2 --> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li><a href="modules.html"><span>Modules</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="namespaceRakNet.html">RakNet</a></li><li class="navelem"><a class="el" href="structRakNet_1_1Lobby2Message.html">Lobby2Message</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">RakNet::Lobby2Message Member List</div> </div> </div><!--header--> <div class="contents"> <p>This is the complete list of members for <a class="el" href="structRakNet_1_1Lobby2Message.html">RakNet::Lobby2Message</a>, including all inherited members.</p> <table class="directory"> <tr class="even"><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html#a6e29d665abe3559b60e9fadfb2fa1b40">callbackId</a></td><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html">RakNet::Lobby2Message</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html#a7d2c66bbb0ffbcda05e83e936976c41a">CallCallback</a>(Lobby2Callbacks *cb)=0</td><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html">RakNet::Lobby2Message</a></td><td class="entry"><span class="mlabel">pure virtual</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html#aeab0f7b852042f9d664cb7ee0b8b0458">CancelOnDisconnect</a>(void) const =0</td><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html">RakNet::Lobby2Message</a></td><td class="entry"><span class="mlabel">pure virtual</span></td></tr> <tr><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html#a73681a9a5bcfe6d7344cb7500c1bae72">ClientImpl</a>(RakNet::Lobby2Plugin *client)</td><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html">RakNet::Lobby2Message</a></td><td class="entry"><span class="mlabel">virtual</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html#ad48d6053a9d086c29dc3108e7de557dc">DebugMsg</a>(RakNet::RakString &amp;out) const =0</td><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html">RakNet::Lobby2Message</a></td><td class="entry"><span class="mlabel">pure virtual</span></td></tr> <tr><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html#accf4946d351e9bb17ad197fc21b0b473">DebugPrintf</a>(void) const </td><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html">RakNet::Lobby2Message</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">virtual</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html#a5046c82fcca8bac36babe863c55ec9eb">extendedResultCode</a></td><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html">RakNet::Lobby2Message</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html#a92248c1609297987f41dbfcfd75806f9">GetID</a>(void) const =0</td><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html">RakNet::Lobby2Message</a></td><td class="entry"><span class="mlabel">pure virtual</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html#ae417f773c4d48bc1cce69c656f2952fd">GetName</a>(void) const =0</td><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html">RakNet::Lobby2Message</a></td><td class="entry"><span class="mlabel">pure virtual</span></td></tr> <tr><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html#a419b02230facc25fe97e364ee914e996">PrevalidateInput</a>(void)</td><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html">RakNet::Lobby2Message</a></td><td class="entry"><span class="mlabel">virtual</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html#a49c6460be7043aa3dd8f69955a4fb426">requestId</a></td><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html">RakNet::Lobby2Message</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html#a79cbb400e4521af2c353fbd640fed0f7">RequiresAdmin</a>(void) const =0</td><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html">RakNet::Lobby2Message</a></td><td class="entry"><span class="mlabel">pure virtual</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html#a575e23419cd160aca576b56ee7476227">RequiresLogin</a>(void) const =0</td><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html">RakNet::Lobby2Message</a></td><td class="entry"><span class="mlabel">pure virtual</span></td></tr> <tr><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html#a3eab67e30f491cd3410b9d850ffcecea">RequiresRankingPermission</a>(void) const =0</td><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html">RakNet::Lobby2Message</a></td><td class="entry"><span class="mlabel">pure virtual</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html#a750b6a5d792d6f6c2532bfc7e3f74c99">resultCode</a></td><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html">RakNet::Lobby2Message</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html#a48a3b558797a8b8ac79fa94cdb70f087">Serialize</a>(bool writeToBitstream, bool serializeOutput, RakNet::BitStream *bitStream)</td><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html">RakNet::Lobby2Message</a></td><td class="entry"><span class="mlabel">virtual</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html#a39a885f1a8d8b636e5c7bbeb13d4f822">ServerDBImpl</a>(Lobby2ServerCommand *command, void *databaseInterface)</td><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html">RakNet::Lobby2Message</a></td><td class="entry"><span class="mlabel">virtual</span></td></tr> <tr><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html#a62cc92ba3fb0e6562cf77d929d231a35">ServerPostDBMemoryImpl</a>(Lobby2Server *server, RakString userHandle)</td><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html">RakNet::Lobby2Message</a></td><td class="entry"><span class="mlabel">virtual</span></td></tr> <tr class="even"><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html#a5213270ccd16a7bc6afc8df001b623e7">ServerPreDBMemoryImpl</a>(Lobby2Server *server, RakString userHandle)</td><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html">RakNet::Lobby2Message</a></td><td class="entry"><span class="mlabel">virtual</span></td></tr> <tr><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html#af510ed0df868969f12118ea32027334b">ValidateBinary</a>(RakNetSmartPtr&lt; BinaryDataBlock &gt;binaryDataBlock)</td><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html">RakNet::Lobby2Message</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html#aec0eeb9161acabd01464f4b875abed31">ValidateEmailAddress</a>(RakNet::RakString *text)</td><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html">RakNet::Lobby2Message</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html#a6a85caa9e47c7d9fec7f156c5e7c723a">ValidateHandle</a>(RakNet::RakString *handle)</td><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html">RakNet::Lobby2Message</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html#a4cf58429201d0c452d354b6add784712">ValidatePassword</a>(RakNet::RakString *text)</td><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html">RakNet::Lobby2Message</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html#ada4ddbe1b8d880b6beb3cec2d107c3cf">ValidateRequiredText</a>(RakNet::RakString *text)</td><td class="entry"><a class="el" href="structRakNet_1_1Lobby2Message.html">RakNet::Lobby2Message</a></td><td class="entry"></td></tr> </table></div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Mon Jun 2 2014 20:10:29 for RakNet by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.2 </small></address> </body> </html>
Hyrtwol/RakNet
Help/Doxygen/html/structRakNet_1_1Lobby2Message-members.html
HTML
bsd-2-clause
10,566
package encryption import ( "crypto/rand" "encoding/base64" "fmt" "io" "strings" "github.com/docker/swarmkit/api" "github.com/gogo/protobuf/proto" "github.com/pkg/errors" ) // This package defines the interfaces and encryption package const humanReadablePrefix = "SWMKEY-1-" // ErrCannotDecrypt is the type of error returned when some data cannot be decryptd as plaintext type ErrCannotDecrypt struct { msg string } func (e ErrCannotDecrypt) Error() string { return e.msg } // A Decrypter can decrypt an encrypted record type Decrypter interface { Decrypt(api.MaybeEncryptedRecord) ([]byte, error) } // A Encrypter can encrypt some bytes into an encrypted record type Encrypter interface { Encrypt(data []byte) (*api.MaybeEncryptedRecord, error) } type noopCrypter struct{} func (n noopCrypter) Decrypt(e api.MaybeEncryptedRecord) ([]byte, error) { if e.Algorithm != n.Algorithm() { return nil, fmt.Errorf("record is encrypted") } return e.Data, nil } func (n noopCrypter) Encrypt(data []byte) (*api.MaybeEncryptedRecord, error) { return &api.MaybeEncryptedRecord{ Algorithm: n.Algorithm(), Data: data, }, nil } func (n noopCrypter) Algorithm() api.MaybeEncryptedRecord_Algorithm { return api.MaybeEncryptedRecord_NotEncrypted } // NoopCrypter is just a pass-through crypter - it does not actually encrypt or // decrypt any data var NoopCrypter = noopCrypter{} // Decrypt turns a slice of bytes serialized as an MaybeEncryptedRecord into a slice of plaintext bytes func Decrypt(encryptd []byte, decrypter Decrypter) ([]byte, error) { if decrypter == nil { return nil, ErrCannotDecrypt{msg: "no decrypter specified"} } r := api.MaybeEncryptedRecord{} if err := proto.Unmarshal(encryptd, &r); err != nil { // nope, this wasn't marshalled as a MaybeEncryptedRecord return nil, ErrCannotDecrypt{msg: "unable to unmarshal as MaybeEncryptedRecord"} } plaintext, err := decrypter.Decrypt(r) if err != nil { return nil, ErrCannotDecrypt{msg: err.Error()} } return plaintext, nil } // Encrypt turns a slice of bytes into a serialized MaybeEncryptedRecord slice of bytes func Encrypt(plaintext []byte, encrypter Encrypter) ([]byte, error) { if encrypter == nil { return nil, fmt.Errorf("no encrypter specified") } encryptedRecord, err := encrypter.Encrypt(plaintext) if err != nil { return nil, errors.Wrap(err, "unable to encrypt data") } data, err := proto.Marshal(encryptedRecord) if err != nil { return nil, errors.Wrap(err, "unable to marshal as MaybeEncryptedRecord") } return data, nil } // Defaults returns a default encrypter and decrypter func Defaults(key []byte) (Encrypter, Decrypter) { n := NewNACLSecretbox(key) return n, n } // GenerateSecretKey generates a secret key that can be used for encrypting data // using this package func GenerateSecretKey() []byte { secretData := make([]byte, naclSecretboxKeySize) if _, err := io.ReadFull(rand.Reader, secretData); err != nil { // panic if we can't read random data panic(errors.Wrap(err, "failed to read random bytes")) } return secretData } // HumanReadableKey displays a secret key in a human readable way func HumanReadableKey(key []byte) string { // base64-encode the key return humanReadablePrefix + base64.RawStdEncoding.EncodeToString(key) } // ParseHumanReadableKey returns a key as bytes from recognized serializations of // said keys func ParseHumanReadableKey(key string) ([]byte, error) { if !strings.HasPrefix(key, humanReadablePrefix) { return nil, fmt.Errorf("invalid key string") } keyBytes, err := base64.RawStdEncoding.DecodeString(strings.TrimPrefix(key, humanReadablePrefix)) if err != nil { return nil, fmt.Errorf("invalid key string") } return keyBytes, nil }
teharrison/AWE
vendor/github.com/docker/docker/vendor/github.com/docker/swarmkit/manager/encryption/encryption.go
GO
bsd-2-clause
3,741
/* $Id: tif_predict.c,v 1.11.2.4 2010-06-08 18:50:42 bfriesen Exp $ */ /* * Copyright (c) 1988-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Sam Leffler and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Sam Leffler and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ /* * TIFF Library. * * Predictor Tag Support (used by multiple codecs). */ #include "tiffiop.h" #include "tif_predict.h" #define PredictorState(tif) ((TIFFPredictorState*) (tif)->tif_data) static void horAcc8(TIFF*, tidata_t, tsize_t); static void horAcc16(TIFF*, tidata_t, tsize_t); static void horAcc32(TIFF*, tidata_t, tsize_t); static void swabHorAcc16(TIFF*, tidata_t, tsize_t); static void swabHorAcc32(TIFF*, tidata_t, tsize_t); static void horDiff8(TIFF*, tidata_t, tsize_t); static void horDiff16(TIFF*, tidata_t, tsize_t); static void horDiff32(TIFF*, tidata_t, tsize_t); static void fpAcc(TIFF*, tidata_t, tsize_t); static void fpDiff(TIFF*, tidata_t, tsize_t); static int PredictorDecodeRow(TIFF*, tidata_t, tsize_t, tsample_t); static int PredictorDecodeTile(TIFF*, tidata_t, tsize_t, tsample_t); static int PredictorEncodeRow(TIFF*, tidata_t, tsize_t, tsample_t); static int PredictorEncodeTile(TIFF*, tidata_t, tsize_t, tsample_t); static int PredictorSetup(TIFF* tif) { static const char module[] = "PredictorSetup"; TIFFPredictorState* sp = PredictorState(tif); TIFFDirectory* td = &tif->tif_dir; switch (sp->predictor) /* no differencing */ { case PREDICTOR_NONE: return 1; case PREDICTOR_HORIZONTAL: if (td->td_bitspersample != 8 && td->td_bitspersample != 16 && td->td_bitspersample != 32) { TIFFErrorExt(tif->tif_clientdata, module, "Horizontal differencing \"Predictor\" not supported with %d-bit samples", td->td_bitspersample); return 0; } break; case PREDICTOR_FLOATINGPOINT: if (td->td_sampleformat != SAMPLEFORMAT_IEEEFP) { TIFFErrorExt(tif->tif_clientdata, module, "Floating point \"Predictor\" not supported with %d data format", td->td_sampleformat); return 0; } break; default: TIFFErrorExt(tif->tif_clientdata, module, "\"Predictor\" value %d not supported", sp->predictor); return 0; } sp->stride = (td->td_planarconfig == PLANARCONFIG_CONTIG ? td->td_samplesperpixel : 1); /* * Calculate the scanline/tile-width size in bytes. */ if (isTiled(tif)) sp->rowsize = TIFFTileRowSize(tif); else sp->rowsize = TIFFScanlineSize(tif); return 1; } static int PredictorSetupDecode(TIFF* tif) { TIFFPredictorState* sp = PredictorState(tif); TIFFDirectory* td = &tif->tif_dir; if (!(*sp->setupdecode)(tif) || !PredictorSetup(tif)) return 0; if (sp->predictor == 2) { switch (td->td_bitspersample) { case 8: sp->decodepfunc = horAcc8; break; case 16: sp->decodepfunc = horAcc16; break; case 32: sp->decodepfunc = horAcc32; break; } /* * Override default decoding method with one that does the * predictor stuff. */ if( tif->tif_decoderow != PredictorDecodeRow ) { sp->decoderow = tif->tif_decoderow; tif->tif_decoderow = PredictorDecodeRow; sp->decodestrip = tif->tif_decodestrip; tif->tif_decodestrip = PredictorDecodeTile; sp->decodetile = tif->tif_decodetile; tif->tif_decodetile = PredictorDecodeTile; } /* * If the data is horizontally differenced 16-bit data that * requires byte-swapping, then it must be byte swapped before * the accumulation step. We do this with a special-purpose * routine and override the normal post decoding logic that * the library setup when the directory was read. */ if (tif->tif_flags & TIFF_SWAB) { if (sp->decodepfunc == horAcc16) { sp->decodepfunc = swabHorAcc16; tif->tif_postdecode = _TIFFNoPostDecode; } else if (sp->decodepfunc == horAcc32) { sp->decodepfunc = swabHorAcc32; tif->tif_postdecode = _TIFFNoPostDecode; } } } else if (sp->predictor == 3) { sp->decodepfunc = fpAcc; /* * Override default decoding method with one that does the * predictor stuff. */ if( tif->tif_decoderow != PredictorDecodeRow ) { sp->decoderow = tif->tif_decoderow; tif->tif_decoderow = PredictorDecodeRow; sp->decodestrip = tif->tif_decodestrip; tif->tif_decodestrip = PredictorDecodeTile; sp->decodetile = tif->tif_decodetile; tif->tif_decodetile = PredictorDecodeTile; } /* * The data should not be swapped outside of the floating * point predictor, the accumulation routine should return * byres in the native order. */ if (tif->tif_flags & TIFF_SWAB) { tif->tif_postdecode = _TIFFNoPostDecode; } /* * Allocate buffer to keep the decoded bytes before * rearranging in the ight order */ } return 1; } static int PredictorSetupEncode(TIFF* tif) { TIFFPredictorState* sp = PredictorState(tif); TIFFDirectory* td = &tif->tif_dir; if (!(*sp->setupencode)(tif) || !PredictorSetup(tif)) return 0; if (sp->predictor == 2) { switch (td->td_bitspersample) { case 8: sp->encodepfunc = horDiff8; break; case 16: sp->encodepfunc = horDiff16; break; case 32: sp->encodepfunc = horDiff32; break; } /* * Override default encoding method with one that does the * predictor stuff. */ if( tif->tif_encoderow != PredictorEncodeRow ) { sp->encoderow = tif->tif_encoderow; tif->tif_encoderow = PredictorEncodeRow; sp->encodestrip = tif->tif_encodestrip; tif->tif_encodestrip = PredictorEncodeTile; sp->encodetile = tif->tif_encodetile; tif->tif_encodetile = PredictorEncodeTile; } } else if (sp->predictor == 3) { sp->encodepfunc = fpDiff; /* * Override default encoding method with one that does the * predictor stuff. */ if( tif->tif_encoderow != PredictorEncodeRow ) { sp->encoderow = tif->tif_encoderow; tif->tif_encoderow = PredictorEncodeRow; sp->encodestrip = tif->tif_encodestrip; tif->tif_encodestrip = PredictorEncodeTile; sp->encodetile = tif->tif_encodetile; tif->tif_encodetile = PredictorEncodeTile; } } return 1; } #define REPEAT4(n, op) \ switch (n) { \ default: { int i; for (i = n-4; i > 0; i--) { op; } } \ case 4: op; \ case 3: op; \ case 2: op; \ case 1: op; \ case 0: ; \ } static void horAcc8(TIFF* tif, tidata_t cp0, tsize_t cc) { tsize_t stride = PredictorState(tif)->stride; char* cp = (char*) cp0; if (cc > stride) { cc -= stride; /* * Pipeline the most common cases. */ if (stride == 3) { unsigned int cr = cp[0]; unsigned int cg = cp[1]; unsigned int cb = cp[2]; do { cc -= 3, cp += 3; cp[0] = (char) (cr += cp[0]); cp[1] = (char) (cg += cp[1]); cp[2] = (char) (cb += cp[2]); } while ((int32) cc > 0); } else if (stride == 4) { unsigned int cr = cp[0]; unsigned int cg = cp[1]; unsigned int cb = cp[2]; unsigned int ca = cp[3]; do { cc -= 4, cp += 4; cp[0] = (char) (cr += cp[0]); cp[1] = (char) (cg += cp[1]); cp[2] = (char) (cb += cp[2]); cp[3] = (char) (ca += cp[3]); } while ((int32) cc > 0); } else { do { REPEAT4(stride, cp[stride] = (char) (cp[stride] + *cp); cp++) cc -= stride; } while ((int32) cc > 0); } } } static void swabHorAcc16(TIFF* tif, tidata_t cp0, tsize_t cc) { tsize_t stride = PredictorState(tif)->stride; uint16* wp = (uint16*) cp0; tsize_t wc = cc / 2; if (wc > stride) { TIFFSwabArrayOfShort(wp, wc); wc -= stride; do { REPEAT4(stride, wp[stride] += wp[0]; wp++) wc -= stride; } while ((int32) wc > 0); } } static void horAcc16(TIFF* tif, tidata_t cp0, tsize_t cc) { tsize_t stride = PredictorState(tif)->stride; uint16* wp = (uint16*) cp0; tsize_t wc = cc / 2; if (wc > stride) { wc -= stride; do { REPEAT4(stride, wp[stride] += wp[0]; wp++) wc -= stride; } while ((int32) wc > 0); } } static void swabHorAcc32(TIFF* tif, tidata_t cp0, tsize_t cc) { tsize_t stride = PredictorState(tif)->stride; uint32* wp = (uint32*) cp0; tsize_t wc = cc / 4; if (wc > stride) { TIFFSwabArrayOfLong(wp, wc); wc -= stride; do { REPEAT4(stride, wp[stride] += wp[0]; wp++) wc -= stride; } while ((int32) wc > 0); } } static void horAcc32(TIFF* tif, tidata_t cp0, tsize_t cc) { tsize_t stride = PredictorState(tif)->stride; uint32* wp = (uint32*) cp0; tsize_t wc = cc / 4; if (wc > stride) { wc -= stride; do { REPEAT4(stride, wp[stride] += wp[0]; wp++) wc -= stride; } while ((int32) wc > 0); } } /* * Floating point predictor accumulation routine. */ static void fpAcc(TIFF* tif, tidata_t cp0, tsize_t cc) { tsize_t stride = PredictorState(tif)->stride; uint32 bps = tif->tif_dir.td_bitspersample / 8; tsize_t wc = cc / bps; tsize_t count = cc; uint8 *cp = (uint8 *) cp0; uint8 *tmp = (uint8 *)_TIFFmalloc(cc); if (!tmp) return; while (count > stride) { REPEAT4(stride, cp[stride] += cp[0]; cp++) count -= stride; } _TIFFmemcpy(tmp, cp0, cc); cp = (uint8 *) cp0; for (count = 0; count < wc; count++) { uint32 byte; for (byte = 0; byte < bps; byte++) { #if WORDS_BIGENDIAN cp[bps * count + byte] = tmp[byte * wc + count]; #else cp[bps * count + byte] = tmp[(bps - byte - 1) * wc + count]; #endif } } _TIFFfree(tmp); } /* * Decode a scanline and apply the predictor routine. */ static int PredictorDecodeRow(TIFF* tif, tidata_t op0, tsize_t occ0, tsample_t s) { TIFFPredictorState *sp = PredictorState(tif); assert(sp != NULL); assert(sp->decoderow != NULL); assert(sp->decodepfunc != NULL); if ((*sp->decoderow)(tif, op0, occ0, s)) { (*sp->decodepfunc)(tif, op0, occ0); return 1; } else return 0; } /* * Decode a tile/strip and apply the predictor routine. * Note that horizontal differencing must be done on a * row-by-row basis. The width of a "row" has already * been calculated at pre-decode time according to the * strip/tile dimensions. */ static int PredictorDecodeTile(TIFF* tif, tidata_t op0, tsize_t occ0, tsample_t s) { TIFFPredictorState *sp = PredictorState(tif); assert(sp != NULL); assert(sp->decodetile != NULL); if ((*sp->decodetile)(tif, op0, occ0, s)) { tsize_t rowsize = sp->rowsize; assert(rowsize > 0); assert(sp->decodepfunc != NULL); while ((long)occ0 > 0) { (*sp->decodepfunc)(tif, op0, (tsize_t) rowsize); occ0 -= rowsize; op0 += rowsize; } return 1; } else return 0; } static void horDiff8(TIFF* tif, tidata_t cp0, tsize_t cc) { TIFFPredictorState* sp = PredictorState(tif); tsize_t stride = sp->stride; char* cp = (char*) cp0; if (cc > stride) { cc -= stride; /* * Pipeline the most common cases. */ if (stride == 3) { int r1, g1, b1; int r2 = cp[0]; int g2 = cp[1]; int b2 = cp[2]; do { r1 = cp[3]; cp[3] = r1-r2; r2 = r1; g1 = cp[4]; cp[4] = g1-g2; g2 = g1; b1 = cp[5]; cp[5] = b1-b2; b2 = b1; cp += 3; } while ((int32)(cc -= 3) > 0); } else if (stride == 4) { int r1, g1, b1, a1; int r2 = cp[0]; int g2 = cp[1]; int b2 = cp[2]; int a2 = cp[3]; do { r1 = cp[4]; cp[4] = r1-r2; r2 = r1; g1 = cp[5]; cp[5] = g1-g2; g2 = g1; b1 = cp[6]; cp[6] = b1-b2; b2 = b1; a1 = cp[7]; cp[7] = a1-a2; a2 = a1; cp += 4; } while ((int32)(cc -= 4) > 0); } else { cp += cc - 1; do { REPEAT4(stride, cp[stride] -= cp[0]; cp--) } while ((int32)(cc -= stride) > 0); } } } static void horDiff16(TIFF* tif, tidata_t cp0, tsize_t cc) { TIFFPredictorState* sp = PredictorState(tif); tsize_t stride = sp->stride; int16 *wp = (int16*) cp0; tsize_t wc = cc/2; if (wc > stride) { wc -= stride; wp += wc - 1; do { REPEAT4(stride, wp[stride] -= wp[0]; wp--) wc -= stride; } while ((int32) wc > 0); } } static void horDiff32(TIFF* tif, tidata_t cp0, tsize_t cc) { TIFFPredictorState* sp = PredictorState(tif); tsize_t stride = sp->stride; int32 *wp = (int32*) cp0; tsize_t wc = cc/4; if (wc > stride) { wc -= stride; wp += wc - 1; do { REPEAT4(stride, wp[stride] -= wp[0]; wp--) wc -= stride; } while ((int32) wc > 0); } } /* * Floating point predictor differencing routine. */ static void fpDiff(TIFF* tif, tidata_t cp0, tsize_t cc) { tsize_t stride = PredictorState(tif)->stride; uint32 bps = tif->tif_dir.td_bitspersample / 8; tsize_t wc = cc / bps; tsize_t count; uint8 *cp = (uint8 *) cp0; uint8 *tmp = (uint8 *)_TIFFmalloc(cc); if (!tmp) return; _TIFFmemcpy(tmp, cp0, cc); for (count = 0; count < wc; count++) { uint32 byte; for (byte = 0; byte < bps; byte++) { #if WORDS_BIGENDIAN cp[byte * wc + count] = tmp[bps * count + byte]; #else cp[(bps - byte - 1) * wc + count] = tmp[bps * count + byte]; #endif } } _TIFFfree(tmp); cp = (uint8 *) cp0; cp += cc - stride - 1; for (count = cc; count > stride; count -= stride) REPEAT4(stride, cp[stride] -= cp[0]; cp--) } static int PredictorEncodeRow(TIFF* tif, tidata_t bp, tsize_t cc, tsample_t s) { TIFFPredictorState *sp = PredictorState(tif); assert(sp != NULL); assert(sp->encodepfunc != NULL); assert(sp->encoderow != NULL); /* XXX horizontal differencing alters user's data XXX */ (*sp->encodepfunc)(tif, bp, cc); return (*sp->encoderow)(tif, bp, cc, s); } static int PredictorEncodeTile(TIFF* tif, tidata_t bp0, tsize_t cc0, tsample_t s) { static const char module[] = "PredictorEncodeTile"; TIFFPredictorState *sp = PredictorState(tif); uint8 *working_copy; tsize_t cc = cc0, rowsize; unsigned char* bp; int result_code; assert(sp != NULL); assert(sp->encodepfunc != NULL); assert(sp->encodetile != NULL); /* * Do predictor manipulation in a working buffer to avoid altering * the callers buffer. http://trac.osgeo.org/gdal/ticket/1965 */ working_copy = (uint8*) _TIFFmalloc(cc0); if( working_copy == NULL ) { TIFFErrorExt(tif->tif_clientdata, module, "Out of memory allocating %d byte temp buffer.", cc0 ); return 0; } memcpy( working_copy, bp0, cc0 ); bp = working_copy; rowsize = sp->rowsize; assert(rowsize > 0); assert((cc0%rowsize)==0); while (cc > 0) { (*sp->encodepfunc)(tif, bp, rowsize); cc -= rowsize; bp += rowsize; } result_code = (*sp->encodetile)(tif, working_copy, cc0, s); _TIFFfree( working_copy ); return result_code; } #define FIELD_PREDICTOR (FIELD_CODEC+0) /* XXX */ static const TIFFFieldInfo predictFieldInfo[] = { { TIFFTAG_PREDICTOR, 1, 1, TIFF_SHORT, FIELD_PREDICTOR, FALSE, FALSE, "Predictor" }, }; static int PredictorVSetField(TIFF* tif, ttag_t tag, va_list ap) { TIFFPredictorState *sp = PredictorState(tif); assert(sp != NULL); assert(sp->vsetparent != NULL); switch (tag) { case TIFFTAG_PREDICTOR: sp->predictor = (uint16) va_arg(ap, int); TIFFSetFieldBit(tif, FIELD_PREDICTOR); break; default: return (*sp->vsetparent)(tif, tag, ap); } tif->tif_flags |= TIFF_DIRTYDIRECT; return 1; } static int PredictorVGetField(TIFF* tif, ttag_t tag, va_list ap) { TIFFPredictorState *sp = PredictorState(tif); assert(sp != NULL); assert(sp->vgetparent != NULL); switch (tag) { case TIFFTAG_PREDICTOR: *va_arg(ap, uint16*) = sp->predictor; break; default: return (*sp->vgetparent)(tif, tag, ap); } return 1; } static void PredictorPrintDir(TIFF* tif, FILE* fd, long flags) { TIFFPredictorState* sp = PredictorState(tif); (void) flags; if (TIFFFieldSet(tif,FIELD_PREDICTOR)) { fprintf(fd, " Predictor: "); switch (sp->predictor) { case 1: fprintf(fd, "none "); break; case 2: fprintf(fd, "horizontal differencing "); break; case 3: fprintf(fd, "floating point predictor "); break; } fprintf(fd, "%u (0x%x)\n", sp->predictor, sp->predictor); } if (sp->printdir) (*sp->printdir)(tif, fd, flags); } int TIFFPredictorInit(TIFF* tif) { TIFFPredictorState* sp = PredictorState(tif); assert(sp != 0); /* * Merge codec-specific tag information. */ if (!_TIFFMergeFieldInfo(tif, predictFieldInfo, TIFFArrayCount(predictFieldInfo))) { TIFFErrorExt(tif->tif_clientdata, "TIFFPredictorInit", "Merging Predictor codec-specific tags failed"); return 0; } /* * Override parent get/set field methods. */ sp->vgetparent = tif->tif_tagmethods.vgetfield; tif->tif_tagmethods.vgetfield = PredictorVGetField;/* hook for predictor tag */ sp->vsetparent = tif->tif_tagmethods.vsetfield; tif->tif_tagmethods.vsetfield = PredictorVSetField;/* hook for predictor tag */ sp->printdir = tif->tif_tagmethods.printdir; tif->tif_tagmethods.printdir = PredictorPrintDir; /* hook for predictor tag */ sp->setupdecode = tif->tif_setupdecode; tif->tif_setupdecode = PredictorSetupDecode; sp->setupencode = tif->tif_setupencode; tif->tif_setupencode = PredictorSetupEncode; sp->predictor = 1; /* default value */ sp->encodepfunc = NULL; /* no predictor routine */ sp->decodepfunc = NULL; /* no predictor routine */ return 1; } int TIFFPredictorCleanup(TIFF* tif) { TIFFPredictorState* sp = PredictorState(tif); assert(sp != 0); tif->tif_tagmethods.vgetfield = sp->vgetparent; tif->tif_tagmethods.vsetfield = sp->vsetparent; tif->tif_tagmethods.printdir = sp->printdir; tif->tif_setupdecode = sp->setupdecode; tif->tif_setupencode = sp->setupencode; return 1; } /* vim: set ts=8 sts=8 sw=8 noet: */ /* * Local Variables: * mode: c * c-basic-offset: 8 * fill-column: 78 * End: */
benos-9k/pbrt-v2-cmake
src/3rdparty/tiff-3.9.4/tif_predict.c
C
bsd-2-clause
19,106
/*! * parseurl * Copyright(c) 2014 Jonathan Ong * Copyright(c) 2014 Douglas Christopher Wilson * MIT Licensed */ /** * Module dependencies. */ var url = require('url') var parse = url.parse var Url = url.Url /** * Pattern for a simple path case. * See: https://github.com/joyent/node/pull/7878 */ var simplePathRegExp = /^(\/\/?(?!\/)[^\?#\s]*)(\?[^#\s]*)?$/ /** * Exports. */ module.exports = parseurl module.exports.original = originalurl /** * Parse the `req` url with memoization. * * @param {ServerRequest} req * @return {Object} * @api public */ function parseurl(req) { var url = req.url if (url === undefined) { // URL is undefined return undefined } var parsed = req._parsedUrl if (fresh(url, parsed)) { // Return cached URL parse return parsed } // Parse the URL parsed = fastparse(url) parsed._raw = url return req._parsedUrl = parsed }; /** * Parse the `req` original url with fallback and memoization. * * @param {ServerRequest} req * @return {Object} * @api public */ function originalurl(req) { var url = req.originalUrl if (typeof url !== 'string') { // Fallback return parseurl(req) } var parsed = req._parsedOriginalUrl if (fresh(url, parsed)) { // Return cached URL parse return parsed } // Parse the URL parsed = fastparse(url) parsed._raw = url return req._parsedOriginalUrl = parsed }; /** * Parse the `str` url with fast-path short-cut. * * @param {string} str * @return {Object} * @api private */ function fastparse(str) { // Try fast path regexp // See: https://github.com/joyent/node/pull/7878 var simplePath = typeof str === 'string' && simplePathRegExp.exec(str) // Construct simple URL if (simplePath) { var pathname = simplePath[1] var search = simplePath[2] || null var url = Url !== undefined ? new Url() : {} url.path = str url.href = str url.pathname = pathname url.search = search url.query = search && search.substr(1) return url } return parse(str) } /** * Determine if parsed is still fresh for url. * * @param {string} url * @param {object} parsedUrl * @return {boolean} * @api private */ function fresh(url, parsedUrl) { return typeof parsedUrl === 'object' && parsedUrl !== null && (Url === undefined || parsedUrl instanceof Url) && parsedUrl._raw === url }
jcoppieters/cody-samples
codyweb/node_modules/express-session/node_modules/parseurl/index.js
JavaScript
bsd-2-clause
2,411
<!doctype html> <title>CodeMirror: Scala mode</title> <meta charset="utf-8"/> <link rel=stylesheet href="../../doc/docs.css"> <link rel="stylesheet" href="../../lib/codemirror.css"> <link rel="stylesheet" href="../../theme/ambiance.css"> <script src="../../lib/codemirror.js"></script> <script src="../../addon/edit/matchbrackets.js"></script> <script src="clike.js"></script> <div id=nav> <a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png"></a> <ul> <li><a href="../../index.html">Home</a> <li><a href="../../doc/manual.html">Manual</a> <li><a href="https://github.com/codemirror/codemirror">Code</a> </ul> <ul> <li><a href="../index.html">Language modes</a> <li><a class=active href="#">Scala</a> </ul> </div> <article> <h2>Scala mode</h2> <form> <textarea id="code" name="code"> /* __ *\ ** ________ ___ / / ___ Scala API ** ** / __/ __// _ | / / / _ | (c) 2003-2011, LAMP/EPFL ** ** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** ** /____/\___/_/ |_/____/_/ | | ** ** |/ ** \* */ package scala.collection import generic._ import mutable.{ Builder, ListBuffer } import annotation.{tailrec, migration, bridge} import annotation.unchecked.{ uncheckedVariance => uV } import parallel.ParIterable /** A template trait for traversable collections of type `Traversable[A]`. * * $traversableInfo * @define mutability * @define traversableInfo * This is a base trait of all kinds of $mutability Scala collections. It * implements the behavior common to all collections, in terms of a method * `foreach` with signature: * {{{ * def foreach[U](f: Elem => U): Unit * }}} * Collection classes mixing in this trait provide a concrete * `foreach` method which traverses all the * elements contained in the collection, applying a given function to each. * They also need to provide a method `newBuilder` * which creates a builder for collections of the same kind. * * A traversable class might or might not have two properties: strictness * and orderedness. Neither is represented as a type. * * The instances of a strict collection class have all their elements * computed before they can be used as values. By contrast, instances of * a non-strict collection class may defer computation of some of their * elements until after the instance is available as a value. * A typical example of a non-strict collection class is a * <a href="../immutable/Stream.html" target="ContentFrame"> * `scala.collection.immutable.Stream`</a>. * A more general class of examples are `TraversableViews`. * * If a collection is an instance of an ordered collection class, traversing * its elements with `foreach` will always visit elements in the * same order, even for different runs of the program. If the class is not * ordered, `foreach` can visit elements in different orders for * different runs (but it will keep the same order in the same run).' * * A typical example of a collection class which is not ordered is a * `HashMap` of objects. The traversal order for hash maps will * depend on the hash codes of its elements, and these hash codes might * differ from one run to the next. By contrast, a `LinkedHashMap` * is ordered because it's `foreach` method visits elements in the * order they were inserted into the `HashMap`. * * @author Martin Odersky * @version 2.8 * @since 2.8 * @tparam A the element type of the collection * @tparam Repr the type of the actual collection containing the elements. * * @define Coll Traversable * @define coll traversable collection */ trait TraversableLike[+A, +Repr] extends HasNewBuilder[A, Repr] with FilterMonadic[A, Repr] with TraversableOnce[A] with GenTraversableLike[A, Repr] with Parallelizable[A, ParIterable[A]] { self => import Traversable.breaks._ /** The type implementing this traversable */ protected type Self = Repr /** The collection of type $coll underlying this `TraversableLike` object. * By default this is implemented as the `TraversableLike` object itself, * but this can be overridden. */ def repr: Repr = this.asInstanceOf[Repr] /** The underlying collection seen as an instance of `$Coll`. * By default this is implemented as the current collection object itself, * but this can be overridden. */ protected[this] def thisCollection: Traversable[A] = this.asInstanceOf[Traversable[A]] /** A conversion from collections of type `Repr` to `$Coll` objects. * By default this is implemented as just a cast, but this can be overridden. */ protected[this] def toCollection(repr: Repr): Traversable[A] = repr.asInstanceOf[Traversable[A]] /** Creates a new builder for this collection type. */ protected[this] def newBuilder: Builder[A, Repr] protected[this] def parCombiner = ParIterable.newCombiner[A] /** Applies a function `f` to all elements of this $coll. * * Note: this method underlies the implementation of most other bulk operations. * It's important to implement this method in an efficient way. * * * @param f the function that is applied for its side-effect to every element. * The result of function `f` is discarded. * * @tparam U the type parameter describing the result of function `f`. * This result will always be ignored. Typically `U` is `Unit`, * but this is not necessary. * * @usecase def foreach(f: A => Unit): Unit */ def foreach[U](f: A => U): Unit /** Tests whether this $coll is empty. * * @return `true` if the $coll contain no elements, `false` otherwise. */ def isEmpty: Boolean = { var result = true breakable { for (x <- this) { result = false break } } result } /** Tests whether this $coll is known to have a finite size. * All strict collections are known to have finite size. For a non-strict collection * such as `Stream`, the predicate returns `true` if all elements have been computed. * It returns `false` if the stream is not yet evaluated to the end. * * Note: many collection methods will not work on collections of infinite sizes. * * @return `true` if this collection is known to have finite size, `false` otherwise. */ def hasDefiniteSize = true def ++[B >: A, That](that: GenTraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = { val b = bf(repr) if (that.isInstanceOf[IndexedSeqLike[_, _]]) b.sizeHint(this, that.seq.size) b ++= thisCollection b ++= that.seq b.result } @bridge def ++[B >: A, That](that: TraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = ++(that: GenTraversableOnce[B])(bf) /** Concatenates this $coll with the elements of a traversable collection. * It differs from ++ in that the right operand determines the type of the * resulting collection rather than the left one. * * @param that the traversable to append. * @tparam B the element type of the returned collection. * @tparam That $thatinfo * @param bf $bfinfo * @return a new collection of type `That` which contains all elements * of this $coll followed by all elements of `that`. * * @usecase def ++:[B](that: TraversableOnce[B]): $Coll[B] * * @return a new $coll which contains all elements of this $coll * followed by all elements of `that`. */ def ++:[B >: A, That](that: TraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = { val b = bf(repr) if (that.isInstanceOf[IndexedSeqLike[_, _]]) b.sizeHint(this, that.size) b ++= that b ++= thisCollection b.result } /** This overload exists because: for the implementation of ++: we should reuse * that of ++ because many collections override it with more efficient versions. * Since TraversableOnce has no '++' method, we have to implement that directly, * but Traversable and down can use the overload. */ def ++:[B >: A, That](that: Traversable[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = (that ++ seq)(breakOut) def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = { val b = bf(repr) b.sizeHint(this) for (x <- this) b += f(x) b.result } def flatMap[B, That](f: A => GenTraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = { val b = bf(repr) for (x <- this) b ++= f(x).seq b.result } /** Selects all elements of this $coll which satisfy a predicate. * * @param p the predicate used to test elements. * @return a new $coll consisting of all elements of this $coll that satisfy the given * predicate `p`. The order of the elements is preserved. */ def filter(p: A => Boolean): Repr = { val b = newBuilder for (x <- this) if (p(x)) b += x b.result } /** Selects all elements of this $coll which do not satisfy a predicate. * * @param p the predicate used to test elements. * @return a new $coll consisting of all elements of this $coll that do not satisfy the given * predicate `p`. The order of the elements is preserved. */ def filterNot(p: A => Boolean): Repr = filter(!p(_)) def collect[B, That](pf: PartialFunction[A, B])(implicit bf: CanBuildFrom[Repr, B, That]): That = { val b = bf(repr) for (x <- this) if (pf.isDefinedAt(x)) b += pf(x) b.result } /** Builds a new collection by applying an option-valued function to all * elements of this $coll on which the function is defined. * * @param f the option-valued function which filters and maps the $coll. * @tparam B the element type of the returned collection. * @tparam That $thatinfo * @param bf $bfinfo * @return a new collection of type `That` resulting from applying the option-valued function * `f` to each element and collecting all defined results. * The order of the elements is preserved. * * @usecase def filterMap[B](f: A => Option[B]): $Coll[B] * * @param pf the partial function which filters and maps the $coll. * @return a new $coll resulting from applying the given option-valued function * `f` to each element and collecting all defined results. * The order of the elements is preserved. def filterMap[B, That](f: A => Option[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = { val b = bf(repr) for (x <- this) f(x) match { case Some(y) => b += y case _ => } b.result } */ /** Partitions this $coll in two ${coll}s according to a predicate. * * @param p the predicate on which to partition. * @return a pair of ${coll}s: the first $coll consists of all elements that * satisfy the predicate `p` and the second $coll consists of all elements * that don't. The relative order of the elements in the resulting ${coll}s * is the same as in the original $coll. */ def partition(p: A => Boolean): (Repr, Repr) = { val l, r = newBuilder for (x <- this) (if (p(x)) l else r) += x (l.result, r.result) } def groupBy[K](f: A => K): immutable.Map[K, Repr] = { val m = mutable.Map.empty[K, Builder[A, Repr]] for (elem <- this) { val key = f(elem) val bldr = m.getOrElseUpdate(key, newBuilder) bldr += elem } val b = immutable.Map.newBuilder[K, Repr] for ((k, v) <- m) b += ((k, v.result)) b.result } /** Tests whether a predicate holds for all elements of this $coll. * * $mayNotTerminateInf * * @param p the predicate used to test elements. * @return `true` if the given predicate `p` holds for all elements * of this $coll, otherwise `false`. */ def forall(p: A => Boolean): Boolean = { var result = true breakable { for (x <- this) if (!p(x)) { result = false; break } } result } /** Tests whether a predicate holds for some of the elements of this $coll. * * $mayNotTerminateInf * * @param p the predicate used to test elements. * @return `true` if the given predicate `p` holds for some of the * elements of this $coll, otherwise `false`. */ def exists(p: A => Boolean): Boolean = { var result = false breakable { for (x <- this) if (p(x)) { result = true; break } } result } /** Finds the first element of the $coll satisfying a predicate, if any. * * $mayNotTerminateInf * $orderDependent * * @param p the predicate used to test elements. * @return an option value containing the first element in the $coll * that satisfies `p`, or `None` if none exists. */ def find(p: A => Boolean): Option[A] = { var result: Option[A] = None breakable { for (x <- this) if (p(x)) { result = Some(x); break } } result } def scan[B >: A, That](z: B)(op: (B, B) => B)(implicit cbf: CanBuildFrom[Repr, B, That]): That = scanLeft(z)(op) def scanLeft[B, That](z: B)(op: (B, A) => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = { val b = bf(repr) b.sizeHint(this, 1) var acc = z b += acc for (x <- this) { acc = op(acc, x); b += acc } b.result } @migration(2, 9, "This scanRight definition has changed in 2.9.\n" + "The previous behavior can be reproduced with scanRight.reverse." ) def scanRight[B, That](z: B)(op: (A, B) => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = { var scanned = List(z) var acc = z for (x <- reversed) { acc = op(x, acc) scanned ::= acc } val b = bf(repr) for (elem <- scanned) b += elem b.result } /** Selects the first element of this $coll. * $orderDependent * @return the first element of this $coll. * @throws `NoSuchElementException` if the $coll is empty. */ def head: A = { var result: () => A = () => throw new NoSuchElementException breakable { for (x <- this) { result = () => x break } } result() } /** Optionally selects the first element. * $orderDependent * @return the first element of this $coll if it is nonempty, `None` if it is empty. */ def headOption: Option[A] = if (isEmpty) None else Some(head) /** Selects all elements except the first. * $orderDependent * @return a $coll consisting of all elements of this $coll * except the first one. * @throws `UnsupportedOperationException` if the $coll is empty. */ override def tail: Repr = { if (isEmpty) throw new UnsupportedOperationException("empty.tail") drop(1) } /** Selects the last element. * $orderDependent * @return The last element of this $coll. * @throws NoSuchElementException If the $coll is empty. */ def last: A = { var lst = head for (x <- this) lst = x lst } /** Optionally selects the last element. * $orderDependent * @return the last element of this $coll$ if it is nonempty, `None` if it is empty. */ def lastOption: Option[A] = if (isEmpty) None else Some(last) /** Selects all elements except the last. * $orderDependent * @return a $coll consisting of all elements of this $coll * except the last one. * @throws `UnsupportedOperationException` if the $coll is empty. */ def init: Repr = { if (isEmpty) throw new UnsupportedOperationException("empty.init") var lst = head var follow = false val b = newBuilder b.sizeHint(this, -1) for (x <- this.seq) { if (follow) b += lst else follow = true lst = x } b.result } def take(n: Int): Repr = slice(0, n) def drop(n: Int): Repr = if (n <= 0) { val b = newBuilder b.sizeHint(this) b ++= thisCollection result } else sliceWithKnownDelta(n, Int.MaxValue, -n) def slice(from: Int, until: Int): Repr = sliceWithKnownBound(math.max(from, 0), until) // Precondition: from >= 0, until > 0, builder already configured for building. private[this] def sliceInternal(from: Int, until: Int, b: Builder[A, Repr]): Repr = { var i = 0 breakable { for (x <- this.seq) { if (i >= from) b += x i += 1 if (i >= until) break } } b.result } // Precondition: from >= 0 private[scala] def sliceWithKnownDelta(from: Int, until: Int, delta: Int): Repr = { val b = newBuilder if (until <= from) b.result else { b.sizeHint(this, delta) sliceInternal(from, until, b) } } // Precondition: from >= 0 private[scala] def sliceWithKnownBound(from: Int, until: Int): Repr = { val b = newBuilder if (until <= from) b.result else { b.sizeHintBounded(until - from, this) sliceInternal(from, until, b) } } def takeWhile(p: A => Boolean): Repr = { val b = newBuilder breakable { for (x <- this) { if (!p(x)) break b += x } } b.result } def dropWhile(p: A => Boolean): Repr = { val b = newBuilder var go = false for (x <- this) { if (!p(x)) go = true if (go) b += x } b.result } def span(p: A => Boolean): (Repr, Repr) = { val l, r = newBuilder var toLeft = true for (x <- this) { toLeft = toLeft && p(x) (if (toLeft) l else r) += x } (l.result, r.result) } def splitAt(n: Int): (Repr, Repr) = { val l, r = newBuilder l.sizeHintBounded(n, this) if (n >= 0) r.sizeHint(this, -n) var i = 0 for (x <- this) { (if (i < n) l else r) += x i += 1 } (l.result, r.result) } /** Iterates over the tails of this $coll. The first value will be this * $coll and the final one will be an empty $coll, with the intervening * values the results of successive applications of `tail`. * * @return an iterator over all the tails of this $coll * @example `List(1,2,3).tails = Iterator(List(1,2,3), List(2,3), List(3), Nil)` */ def tails: Iterator[Repr] = iterateUntilEmpty(_.tail) /** Iterates over the inits of this $coll. The first value will be this * $coll and the final one will be an empty $coll, with the intervening * values the results of successive applications of `init`. * * @return an iterator over all the inits of this $coll * @example `List(1,2,3).inits = Iterator(List(1,2,3), List(1,2), List(1), Nil)` */ def inits: Iterator[Repr] = iterateUntilEmpty(_.init) /** Copies elements of this $coll to an array. * Fills the given array `xs` with at most `len` elements of * this $coll, starting at position `start`. * Copying will stop once either the end of the current $coll is reached, * or the end of the array is reached, or `len` elements have been copied. * * $willNotTerminateInf * * @param xs the array to fill. * @param start the starting index. * @param len the maximal number of elements to copy. * @tparam B the type of the elements of the array. * * * @usecase def copyToArray(xs: Array[A], start: Int, len: Int): Unit */ def copyToArray[B >: A](xs: Array[B], start: Int, len: Int) { var i = start val end = (start + len) min xs.length breakable { for (x <- this) { if (i >= end) break xs(i) = x i += 1 } } } def toTraversable: Traversable[A] = thisCollection def toIterator: Iterator[A] = toStream.iterator def toStream: Stream[A] = toBuffer.toStream /** Converts this $coll to a string. * * @return a string representation of this collection. By default this * string consists of the `stringPrefix` of this $coll, * followed by all elements separated by commas and enclosed in parentheses. */ override def toString = mkString(stringPrefix + "(", ", ", ")") /** Defines the prefix of this object's `toString` representation. * * @return a string representation which starts the result of `toString` * applied to this $coll. By default the string prefix is the * simple name of the collection class $coll. */ def stringPrefix : String = { var string = repr.asInstanceOf[AnyRef].getClass.getName val idx1 = string.lastIndexOf('.' : Int) if (idx1 != -1) string = string.substring(idx1 + 1) val idx2 = string.indexOf('$') if (idx2 != -1) string = string.substring(0, idx2) string } /** Creates a non-strict view of this $coll. * * @return a non-strict view of this $coll. */ def view = new TraversableView[A, Repr] { protected lazy val underlying = self.repr override def foreach[U](f: A => U) = self foreach f } /** Creates a non-strict view of a slice of this $coll. * * Note: the difference between `view` and `slice` is that `view` produces * a view of the current $coll, whereas `slice` produces a new $coll. * * Note: `view(from, to)` is equivalent to `view.slice(from, to)` * $orderDependent * * @param from the index of the first element of the view * @param until the index of the element following the view * @return a non-strict view of a slice of this $coll, starting at index `from` * and extending up to (but not including) index `until`. */ def view(from: Int, until: Int): TraversableView[A, Repr] = view.slice(from, until) /** Creates a non-strict filter of this $coll. * * Note: the difference between `c filter p` and `c withFilter p` is that * the former creates a new collection, whereas the latter only * restricts the domain of subsequent `map`, `flatMap`, `foreach`, * and `withFilter` operations. * $orderDependent * * @param p the predicate used to test elements. * @return an object of class `WithFilter`, which supports * `map`, `flatMap`, `foreach`, and `withFilter` operations. * All these operations apply to those elements of this $coll which * satisfy the predicate `p`. */ def withFilter(p: A => Boolean): FilterMonadic[A, Repr] = new WithFilter(p) /** A class supporting filtered operations. Instances of this class are * returned by method `withFilter`. */ class WithFilter(p: A => Boolean) extends FilterMonadic[A, Repr] { /** Builds a new collection by applying a function to all elements of the * outer $coll containing this `WithFilter` instance that satisfy predicate `p`. * * @param f the function to apply to each element. * @tparam B the element type of the returned collection. * @tparam That $thatinfo * @param bf $bfinfo * @return a new collection of type `That` resulting from applying * the given function `f` to each element of the outer $coll * that satisfies predicate `p` and collecting the results. * * @usecase def map[B](f: A => B): $Coll[B] * * @return a new $coll resulting from applying the given function * `f` to each element of the outer $coll that satisfies * predicate `p` and collecting the results. */ def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = { val b = bf(repr) for (x <- self) if (p(x)) b += f(x) b.result } /** Builds a new collection by applying a function to all elements of the * outer $coll containing this `WithFilter` instance that satisfy * predicate `p` and concatenating the results. * * @param f the function to apply to each element. * @tparam B the element type of the returned collection. * @tparam That $thatinfo * @param bf $bfinfo * @return a new collection of type `That` resulting from applying * the given collection-valued function `f` to each element * of the outer $coll that satisfies predicate `p` and * concatenating the results. * * @usecase def flatMap[B](f: A => TraversableOnce[B]): $Coll[B] * * @return a new $coll resulting from applying the given collection-valued function * `f` to each element of the outer $coll that satisfies predicate `p` and concatenating the results. */ def flatMap[B, That](f: A => GenTraversableOnce[B])(implicit bf: CanBuildFrom[Repr, B, That]): That = { val b = bf(repr) for (x <- self) if (p(x)) b ++= f(x).seq b.result } /** Applies a function `f` to all elements of the outer $coll containing * this `WithFilter` instance that satisfy predicate `p`. * * @param f the function that is applied for its side-effect to every element. * The result of function `f` is discarded. * * @tparam U the type parameter describing the result of function `f`. * This result will always be ignored. Typically `U` is `Unit`, * but this is not necessary. * * @usecase def foreach(f: A => Unit): Unit */ def foreach[U](f: A => U): Unit = for (x <- self) if (p(x)) f(x) /** Further refines the filter for this $coll. * * @param q the predicate used to test elements. * @return an object of class `WithFilter`, which supports * `map`, `flatMap`, `foreach`, and `withFilter` operations. * All these operations apply to those elements of this $coll which * satisfy the predicate `q` in addition to the predicate `p`. */ def withFilter(q: A => Boolean): WithFilter = new WithFilter(x => p(x) && q(x)) } // A helper for tails and inits. private def iterateUntilEmpty(f: Traversable[A @uV] => Traversable[A @uV]): Iterator[Repr] = { val it = Iterator.iterate(thisCollection)(f) takeWhile (x => !x.isEmpty) it ++ Iterator(Nil) map (newBuilder ++= _ result) } } </textarea> </form> <script> var editor = CodeMirror.fromTextArea(document.getElementById("code"), { lineNumbers: true, matchBrackets: true, theme: "ambiance", mode: "text/x-scala" }); </script> </article>
tyrchen/blog
static/js/editor/codemirror-4.8/mode/clike/scala.html
HTML
bsd-2-clause
28,518
/** ******************************************************************************* * Copyright (C) 2001-2012, International Business Machines Corporation. * All Rights Reserved. ******************************************************************************* */ #include "unicode/utypes.h" #if !UCONFIG_NO_SERVICE #include "serv.h" #include "umutex.h" #undef SERVICE_REFCOUNT // in case we use the refcount stuff U_NAMESPACE_BEGIN /* ****************************************************************** */ const UChar ICUServiceKey::PREFIX_DELIMITER = 0x002F; /* '/' */ ICUServiceKey::ICUServiceKey(const UnicodeString& id) : _id(id) { } ICUServiceKey::~ICUServiceKey() { } const UnicodeString& ICUServiceKey::getID() const { return _id; } UnicodeString& ICUServiceKey::canonicalID(UnicodeString& result) const { return result.append(_id); } UnicodeString& ICUServiceKey::currentID(UnicodeString& result) const { return canonicalID(result); } UnicodeString& ICUServiceKey::currentDescriptor(UnicodeString& result) const { prefix(result); result.append(PREFIX_DELIMITER); return currentID(result); } UBool ICUServiceKey::fallback() { return FALSE; } UBool ICUServiceKey::isFallbackOf(const UnicodeString& id) const { return id == _id; } UnicodeString& ICUServiceKey::prefix(UnicodeString& result) const { return result; } UnicodeString& ICUServiceKey::parsePrefix(UnicodeString& result) { int32_t n = result.indexOf(PREFIX_DELIMITER); if (n < 0) { n = 0; } result.remove(n); return result; } UnicodeString& ICUServiceKey::parseSuffix(UnicodeString& result) { int32_t n = result.indexOf(PREFIX_DELIMITER); if (n >= 0) { result.remove(0, n+1); } return result; } #ifdef SERVICE_DEBUG UnicodeString& ICUServiceKey::debug(UnicodeString& result) const { debugClass(result); result.append(" id: "); result.append(_id); return result; } UnicodeString& ICUServiceKey::debugClass(UnicodeString& result) const { return result.append("ICUServiceKey"); } #endif UOBJECT_DEFINE_RTTI_IMPLEMENTATION(ICUServiceKey) /* ****************************************************************** */ ICUServiceFactory::~ICUServiceFactory() {} SimpleFactory::SimpleFactory(UObject* instanceToAdopt, const UnicodeString& id, UBool visible) : _instance(instanceToAdopt), _id(id), _visible(visible) { } SimpleFactory::~SimpleFactory() { delete _instance; } UObject* SimpleFactory::create(const ICUServiceKey& key, const ICUService* service, UErrorCode& status) const { if (U_SUCCESS(status)) { UnicodeString temp; if (_id == key.currentID(temp)) { return service->cloneInstance(_instance); } } return NULL; } void SimpleFactory::updateVisibleIDs(Hashtable& result, UErrorCode& status) const { if (_visible) { result.put(_id, (void*)this, status); // cast away const } else { result.remove(_id); } } UnicodeString& SimpleFactory::getDisplayName(const UnicodeString& id, const Locale& /* locale */, UnicodeString& result) const { if (_visible && _id == id) { result = _id; } else { result.setToBogus(); } return result; } #ifdef SERVICE_DEBUG UnicodeString& SimpleFactory::debug(UnicodeString& toAppendTo) const { debugClass(toAppendTo); toAppendTo.append(" id: "); toAppendTo.append(_id); toAppendTo.append(", visible: "); toAppendTo.append(_visible ? "T" : "F"); return toAppendTo; } UnicodeString& SimpleFactory::debugClass(UnicodeString& toAppendTo) const { return toAppendTo.append("SimpleFactory"); } #endif UOBJECT_DEFINE_RTTI_IMPLEMENTATION(SimpleFactory) /* ****************************************************************** */ ServiceListener::~ServiceListener() {} UOBJECT_DEFINE_RTTI_IMPLEMENTATION(ServiceListener) /* ****************************************************************** */ // Record the actual id for this service in the cache, so we can return it // even if we succeed later with a different id. class CacheEntry : public UMemory { private: int32_t refcount; public: UnicodeString actualDescriptor; UObject* service; /** * Releases a reference to the shared resource. */ ~CacheEntry() { delete service; } CacheEntry(const UnicodeString& _actualDescriptor, UObject* _service) : refcount(1), actualDescriptor(_actualDescriptor), service(_service) { } /** * Instantiation creates an initial reference, so don't call this * unless you're creating a new pointer to this. Management of * that pointer will have to know how to deal with refcounts. * Return true if the resource has not already been released. */ CacheEntry* ref() { ++refcount; return this; } /** * Destructions removes a reference, so don't call this unless * you're removing pointer to this somewhere. Management of that * pointer will have to know how to deal with refcounts. Once * the refcount drops to zero, the resource is released. Return * false if the resouce has been released. */ CacheEntry* unref() { if ((--refcount) == 0) { delete this; return NULL; } return this; } /** * Return TRUE if there is at least one reference to this and the * resource has not been released. */ UBool isShared() const { return refcount > 1; } }; // UObjectDeleter for serviceCache U_CDECL_BEGIN static void U_CALLCONV cacheDeleter(void* obj) { U_NAMESPACE_USE ((CacheEntry*)obj)->unref(); } /** * Deleter for UObjects */ static void U_CALLCONV deleteUObject(void *obj) { U_NAMESPACE_USE delete (UObject*) obj; } U_CDECL_END /* ****************************************************************** */ class DNCache : public UMemory { public: Hashtable cache; const Locale locale; DNCache(const Locale& _locale) : cache(), locale(_locale) { // cache.setKeyDeleter(uprv_deleteUObject); } }; /* ****************************************************************** */ StringPair* StringPair::create(const UnicodeString& displayName, const UnicodeString& id, UErrorCode& status) { if (U_SUCCESS(status)) { StringPair* sp = new StringPair(displayName, id); if (sp == NULL || sp->isBogus()) { status = U_MEMORY_ALLOCATION_ERROR; delete sp; return NULL; } return sp; } return NULL; } UBool StringPair::isBogus() const { return displayName.isBogus() || id.isBogus(); } StringPair::StringPair(const UnicodeString& _displayName, const UnicodeString& _id) : displayName(_displayName) , id(_id) { } U_CDECL_BEGIN static void U_CALLCONV userv_deleteStringPair(void *obj) { U_NAMESPACE_USE delete (StringPair*) obj; } U_CDECL_END /* ****************************************************************** */ static UMutex lock = U_MUTEX_INITIALIZER; ICUService::ICUService() : name() , timestamp(0) , factories(NULL) , serviceCache(NULL) , idCache(NULL) , dnCache(NULL) { } ICUService::ICUService(const UnicodeString& newName) : name(newName) , timestamp(0) , factories(NULL) , serviceCache(NULL) , idCache(NULL) , dnCache(NULL) { } ICUService::~ICUService() { { Mutex mutex(&lock); clearCaches(); delete factories; factories = NULL; } } UObject* ICUService::get(const UnicodeString& descriptor, UErrorCode& status) const { return get(descriptor, NULL, status); } UObject* ICUService::get(const UnicodeString& descriptor, UnicodeString* actualReturn, UErrorCode& status) const { UObject* result = NULL; ICUServiceKey* key = createKey(&descriptor, status); if (key) { result = getKey(*key, actualReturn, status); delete key; } return result; } UObject* ICUService::getKey(ICUServiceKey& key, UErrorCode& status) const { return getKey(key, NULL, status); } // this is a vector that subclasses of ICUService can override to further customize the result object // before returning it. All other public get functions should call this one. UObject* ICUService::getKey(ICUServiceKey& key, UnicodeString* actualReturn, UErrorCode& status) const { return getKey(key, actualReturn, NULL, status); } // make it possible to call reentrantly on systems that don't have reentrant mutexes. // we can use this simple approach since we know the situation where we're calling // reentrantly even without knowing the thread. class XMutex : public UMemory { public: inline XMutex(UMutex *mutex, UBool reentering) : fMutex(mutex) , fActive(!reentering) { if (fActive) umtx_lock(fMutex); } inline ~XMutex() { if (fActive) umtx_unlock(fMutex); } private: UMutex *fMutex; UBool fActive; }; struct UVectorDeleter { UVector* _obj; UVectorDeleter() : _obj(NULL) {} ~UVectorDeleter() { delete _obj; } }; // called only by factories, treat as private UObject* ICUService::getKey(ICUServiceKey& key, UnicodeString* actualReturn, const ICUServiceFactory* factory, UErrorCode& status) const { if (U_FAILURE(status)) { return NULL; } if (isDefault()) { return handleDefault(key, actualReturn, status); } ICUService* ncthis = (ICUService*)this; // cast away semantic const CacheEntry* result = NULL; { // The factory list can't be modified until we're done, // otherwise we might update the cache with an invalid result. // The cache has to stay in synch with the factory list. // ICU doesn't have monitors so we can't use rw locks, so // we single-thread everything using this service, for now. // if factory is not null, we're calling from within the mutex, // and since some unix machines don't have reentrant mutexes we // need to make sure not to try to lock it again. XMutex mutex(&lock, factory != NULL); if (serviceCache == NULL) { ncthis->serviceCache = new Hashtable(status); if (ncthis->serviceCache == NULL) { return NULL; } if (U_FAILURE(status)) { delete serviceCache; return NULL; } serviceCache->setValueDeleter(cacheDeleter); } UnicodeString currentDescriptor; UVectorDeleter cacheDescriptorList; UBool putInCache = FALSE; int32_t startIndex = 0; int32_t limit = factories->size(); UBool cacheResult = TRUE; if (factory != NULL) { for (int32_t i = 0; i < limit; ++i) { if (factory == (const ICUServiceFactory*)factories->elementAt(i)) { startIndex = i + 1; break; } } if (startIndex == 0) { // throw new InternalError("Factory " + factory + "not registered with service: " + this); status = U_ILLEGAL_ARGUMENT_ERROR; return NULL; } cacheResult = FALSE; } do { currentDescriptor.remove(); key.currentDescriptor(currentDescriptor); result = (CacheEntry*)serviceCache->get(currentDescriptor); if (result != NULL) { break; } // first test of cache failed, so we'll have to update // the cache if we eventually succeed-- that is, if we're // going to update the cache at all. putInCache = TRUE; int32_t index = startIndex; while (index < limit) { ICUServiceFactory* f = (ICUServiceFactory*)factories->elementAt(index++); UObject* service = f->create(key, this, status); if (U_FAILURE(status)) { delete service; return NULL; } if (service != NULL) { result = new CacheEntry(currentDescriptor, service); if (result == NULL) { delete service; status = U_MEMORY_ALLOCATION_ERROR; return NULL; } goto outerEnd; } } // prepare to load the cache with all additional ids that // will resolve to result, assuming we'll succeed. We // don't want to keep querying on an id that's going to // fallback to the one that succeeded, we want to hit the // cache the first time next goaround. if (cacheDescriptorList._obj == NULL) { cacheDescriptorList._obj = new UVector(uprv_deleteUObject, NULL, 5, status); if (U_FAILURE(status)) { return NULL; } } UnicodeString* idToCache = new UnicodeString(currentDescriptor); if (idToCache == NULL || idToCache->isBogus()) { status = U_MEMORY_ALLOCATION_ERROR; return NULL; } cacheDescriptorList._obj->addElement(idToCache, status); if (U_FAILURE(status)) { return NULL; } } while (key.fallback()); outerEnd: if (result != NULL) { if (putInCache && cacheResult) { serviceCache->put(result->actualDescriptor, result, status); if (U_FAILURE(status)) { delete result; return NULL; } if (cacheDescriptorList._obj != NULL) { for (int32_t i = cacheDescriptorList._obj->size(); --i >= 0;) { UnicodeString* desc = (UnicodeString*)cacheDescriptorList._obj->elementAt(i); serviceCache->put(*desc, result, status); if (U_FAILURE(status)) { delete result; return NULL; } result->ref(); cacheDescriptorList._obj->removeElementAt(i); } } } if (actualReturn != NULL) { // strip null prefix if (result->actualDescriptor.indexOf((UChar)0x2f) == 0) { // U+002f=slash (/) actualReturn->remove(); actualReturn->append(result->actualDescriptor, 1, result->actualDescriptor.length() - 1); } else { *actualReturn = result->actualDescriptor; } if (actualReturn->isBogus()) { status = U_MEMORY_ALLOCATION_ERROR; delete result; return NULL; } } UObject* service = cloneInstance(result->service); if (putInCache && !cacheResult) { delete result; } return service; } } return handleDefault(key, actualReturn, status); } UObject* ICUService::handleDefault(const ICUServiceKey& /* key */, UnicodeString* /* actualIDReturn */, UErrorCode& /* status */) const { return NULL; } UVector& ICUService::getVisibleIDs(UVector& result, UErrorCode& status) const { return getVisibleIDs(result, NULL, status); } UVector& ICUService::getVisibleIDs(UVector& result, const UnicodeString* matchID, UErrorCode& status) const { result.removeAllElements(); if (U_FAILURE(status)) { return result; } { Mutex mutex(&lock); const Hashtable* map = getVisibleIDMap(status); if (map != NULL) { ICUServiceKey* fallbackKey = createKey(matchID, status); for (int32_t pos = -1;;) { const UHashElement* e = map->nextElement(pos); if (e == NULL) { break; } const UnicodeString* id = (const UnicodeString*)e->key.pointer; if (fallbackKey != NULL) { if (!fallbackKey->isFallbackOf(*id)) { continue; } } UnicodeString* idClone = new UnicodeString(*id); if (idClone == NULL || idClone->isBogus()) { delete idClone; status = U_MEMORY_ALLOCATION_ERROR; break; } result.addElement(idClone, status); if (U_FAILURE(status)) { delete idClone; break; } } delete fallbackKey; } } if (U_FAILURE(status)) { result.removeAllElements(); } return result; } const Hashtable* ICUService::getVisibleIDMap(UErrorCode& status) const { if (U_FAILURE(status)) return NULL; // must only be called when lock is already held ICUService* ncthis = (ICUService*)this; // cast away semantic const if (idCache == NULL) { ncthis->idCache = new Hashtable(status); if (idCache == NULL) { status = U_MEMORY_ALLOCATION_ERROR; } else if (factories != NULL) { for (int32_t pos = factories->size(); --pos >= 0;) { ICUServiceFactory* f = (ICUServiceFactory*)factories->elementAt(pos); f->updateVisibleIDs(*idCache, status); } if (U_FAILURE(status)) { delete idCache; ncthis->idCache = NULL; } } } return idCache; } UnicodeString& ICUService::getDisplayName(const UnicodeString& id, UnicodeString& result) const { return getDisplayName(id, result, Locale::getDefault()); } UnicodeString& ICUService::getDisplayName(const UnicodeString& id, UnicodeString& result, const Locale& locale) const { { UErrorCode status = U_ZERO_ERROR; Mutex mutex(&lock); const Hashtable* map = getVisibleIDMap(status); if (map != NULL) { ICUServiceFactory* f = (ICUServiceFactory*)map->get(id); if (f != NULL) { f->getDisplayName(id, locale, result); return result; } // fallback UErrorCode status = U_ZERO_ERROR; ICUServiceKey* fallbackKey = createKey(&id, status); while (fallbackKey->fallback()) { UnicodeString us; fallbackKey->currentID(us); f = (ICUServiceFactory*)map->get(us); if (f != NULL) { f->getDisplayName(id, locale, result); delete fallbackKey; return result; } } delete fallbackKey; } } result.setToBogus(); return result; } UVector& ICUService::getDisplayNames(UVector& result, UErrorCode& status) const { return getDisplayNames(result, Locale::getDefault(), NULL, status); } UVector& ICUService::getDisplayNames(UVector& result, const Locale& locale, UErrorCode& status) const { return getDisplayNames(result, locale, NULL, status); } UVector& ICUService::getDisplayNames(UVector& result, const Locale& locale, const UnicodeString* matchID, UErrorCode& status) const { result.removeAllElements(); result.setDeleter(userv_deleteStringPair); if (U_SUCCESS(status)) { ICUService* ncthis = (ICUService*)this; // cast away semantic const Mutex mutex(&lock); if (dnCache != NULL && dnCache->locale != locale) { delete dnCache; ncthis->dnCache = NULL; } if (dnCache == NULL) { const Hashtable* m = getVisibleIDMap(status); if (U_FAILURE(status)) { return result; } ncthis->dnCache = new DNCache(locale); if (dnCache == NULL) { status = U_MEMORY_ALLOCATION_ERROR; return result; } int32_t pos = -1; const UHashElement* entry = NULL; while ((entry = m->nextElement(pos)) != NULL) { const UnicodeString* id = (const UnicodeString*)entry->key.pointer; ICUServiceFactory* f = (ICUServiceFactory*)entry->value.pointer; UnicodeString dname; f->getDisplayName(*id, locale, dname); if (dname.isBogus()) { status = U_MEMORY_ALLOCATION_ERROR; } else { dnCache->cache.put(dname, (void*)id, status); // share pointer with visibleIDMap if (U_SUCCESS(status)) { continue; } } delete dnCache; ncthis->dnCache = NULL; return result; } } } ICUServiceKey* matchKey = createKey(matchID, status); /* To ensure that all elements in the hashtable are iterated, set pos to -1. * nextElement(pos) will skip the position at pos and begin the iteration * at the next position, which in this case will be 0. */ int32_t pos = -1; const UHashElement *entry = NULL; while ((entry = dnCache->cache.nextElement(pos)) != NULL) { const UnicodeString* id = (const UnicodeString*)entry->value.pointer; if (matchKey != NULL && !matchKey->isFallbackOf(*id)) { continue; } const UnicodeString* dn = (const UnicodeString*)entry->key.pointer; StringPair* sp = StringPair::create(*id, *dn, status); result.addElement(sp, status); if (U_FAILURE(status)) { result.removeAllElements(); break; } } delete matchKey; return result; } URegistryKey ICUService::registerInstance(UObject* objToAdopt, const UnicodeString& id, UErrorCode& status) { return registerInstance(objToAdopt, id, TRUE, status); } URegistryKey ICUService::registerInstance(UObject* objToAdopt, const UnicodeString& id, UBool visible, UErrorCode& status) { ICUServiceKey* key = createKey(&id, status); if (key != NULL) { UnicodeString canonicalID; key->canonicalID(canonicalID); delete key; ICUServiceFactory* f = createSimpleFactory(objToAdopt, canonicalID, visible, status); if (f != NULL) { return registerFactory(f, status); } } delete objToAdopt; return NULL; } ICUServiceFactory* ICUService::createSimpleFactory(UObject* objToAdopt, const UnicodeString& id, UBool visible, UErrorCode& status) { if (U_SUCCESS(status)) { if ((objToAdopt != NULL) && (!id.isBogus())) { return new SimpleFactory(objToAdopt, id, visible); } status = U_ILLEGAL_ARGUMENT_ERROR; } return NULL; } URegistryKey ICUService::registerFactory(ICUServiceFactory* factoryToAdopt, UErrorCode& status) { if (U_SUCCESS(status) && factoryToAdopt != NULL) { Mutex mutex(&lock); if (factories == NULL) { factories = new UVector(deleteUObject, NULL, status); if (U_FAILURE(status)) { delete factories; return NULL; } } factories->insertElementAt(factoryToAdopt, 0, status); if (U_SUCCESS(status)) { clearCaches(); } else { delete factoryToAdopt; factoryToAdopt = NULL; } } if (factoryToAdopt != NULL) { notifyChanged(); } return (URegistryKey)factoryToAdopt; } UBool ICUService::unregister(URegistryKey rkey, UErrorCode& status) { ICUServiceFactory *factory = (ICUServiceFactory*)rkey; UBool result = FALSE; if (factory != NULL && factories != NULL) { Mutex mutex(&lock); if (factories->removeElement(factory)) { clearCaches(); result = TRUE; } else { status = U_ILLEGAL_ARGUMENT_ERROR; delete factory; } } if (result) { notifyChanged(); } return result; } void ICUService::reset() { { Mutex mutex(&lock); reInitializeFactories(); clearCaches(); } notifyChanged(); } void ICUService::reInitializeFactories() { if (factories != NULL) { factories->removeAllElements(); } } UBool ICUService::isDefault() const { return countFactories() == 0; } ICUServiceKey* ICUService::createKey(const UnicodeString* id, UErrorCode& status) const { return (U_FAILURE(status) || id == NULL) ? NULL : new ICUServiceKey(*id); } void ICUService::clearCaches() { // callers synchronize before use ++timestamp; delete dnCache; dnCache = NULL; delete idCache; idCache = NULL; delete serviceCache; serviceCache = NULL; } void ICUService::clearServiceCache() { // callers synchronize before use delete serviceCache; serviceCache = NULL; } UBool ICUService::acceptsListener(const EventListener& l) const { return dynamic_cast<const ServiceListener*>(&l) != NULL; } void ICUService::notifyListener(EventListener& l) const { ((ServiceListener&)l).serviceChanged(*this); } UnicodeString& ICUService::getName(UnicodeString& result) const { return result.append(name); } int32_t ICUService::countFactories() const { return factories == NULL ? 0 : factories->size(); } int32_t ICUService::getTimestamp() const { return timestamp; } U_NAMESPACE_END /* UCONFIG_NO_SERVICE */ #endif
PopCap/GameIdea
Engine/Source/ThirdParty/ICU/icu4c-53_1/source/common/serv.cpp
C++
bsd-2-clause
25,954
class ZshSyntaxHighlighting < Formula desc "Fish shell like syntax highlighting for zsh" homepage "https://github.com/zsh-users/zsh-syntax-highlighting" url "https://github.com/zsh-users/zsh-syntax-highlighting/archive/0.2.1.tar.gz" sha256 "3cdf47ee613ff748230e9666c0122eca22dc05352f266fe640019c982f3ef6db" head "https://github.com/zsh-users/zsh-syntax-highlighting.git" bottle :unneeded def install (share/"zsh-syntax-highlighting").install Dir["*"] end def caveats <<-EOS.undent To activate the syntax highlighting, add the following at the end of your .zshrc: source #{HOMEBREW_PREFIX}/share/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh You will also need to force reload of your .zshrc: source ~/.zshrc Additionally, if your receive "highlighters directory not found" error message, you may need to add the following to your .zshenv: export ZSH_HIGHLIGHT_HIGHLIGHTERS_DIR=#{HOMEBREW_PREFIX}/share/zsh-syntax-highlighting/highlighters EOS end test do system "#{share}/zsh-syntax-highlighting/tests/test-highlighting.zsh", "main" end end
kad/homebrew
Library/Formula/zsh-syntax-highlighting.rb
Ruby
bsd-2-clause
1,130
/* * Copyright (C) Igor Sysoev * Copyright (C) Nginx, Inc. */ #include <ngx_config.h> #include <ngx_core.h> #include <ngx_http.h> #include <zlib.h> typedef struct { ngx_flag_t enable; ngx_flag_t no_buffer; ngx_hash_t types; ngx_bufs_t bufs; size_t postpone_gzipping; ngx_int_t level; size_t wbits; size_t memlevel; ssize_t min_length; ngx_array_t *types_keys; } ngx_http_gzip_conf_t; typedef struct { ngx_chain_t *in; ngx_chain_t *free; ngx_chain_t *busy; ngx_chain_t *out; ngx_chain_t **last_out; ngx_chain_t *copied; ngx_chain_t *copy_buf; ngx_buf_t *in_buf; ngx_buf_t *out_buf; ngx_int_t bufs; void *preallocated; char *free_mem; ngx_uint_t allocated; int wbits; int memlevel; unsigned flush:4; unsigned redo:1; unsigned done:1; unsigned nomem:1; unsigned gzheader:1; unsigned buffering:1; size_t zin; size_t zout; uint32_t crc32; z_stream zstream; ngx_http_request_t *request; } ngx_http_gzip_ctx_t; #if (NGX_HAVE_LITTLE_ENDIAN && NGX_HAVE_NONALIGNED) struct gztrailer { uint32_t crc32; uint32_t zlen; }; #else /* NGX_HAVE_BIG_ENDIAN || !NGX_HAVE_NONALIGNED */ struct gztrailer { u_char crc32[4]; u_char zlen[4]; }; #endif static void ngx_http_gzip_filter_memory(ngx_http_request_t *r, ngx_http_gzip_ctx_t *ctx); static ngx_int_t ngx_http_gzip_filter_buffer(ngx_http_gzip_ctx_t *ctx, ngx_chain_t *in); static ngx_int_t ngx_http_gzip_filter_deflate_start(ngx_http_request_t *r, ngx_http_gzip_ctx_t *ctx); static ngx_int_t ngx_http_gzip_filter_gzheader(ngx_http_request_t *r, ngx_http_gzip_ctx_t *ctx); static ngx_int_t ngx_http_gzip_filter_add_data(ngx_http_request_t *r, ngx_http_gzip_ctx_t *ctx); static ngx_int_t ngx_http_gzip_filter_get_buf(ngx_http_request_t *r, ngx_http_gzip_ctx_t *ctx); static ngx_int_t ngx_http_gzip_filter_deflate(ngx_http_request_t *r, ngx_http_gzip_ctx_t *ctx); static ngx_int_t ngx_http_gzip_filter_deflate_end(ngx_http_request_t *r, ngx_http_gzip_ctx_t *ctx); static void *ngx_http_gzip_filter_alloc(void *opaque, u_int items, u_int size); static void ngx_http_gzip_filter_free(void *opaque, void *address); static void ngx_http_gzip_filter_free_copy_buf(ngx_http_request_t *r, ngx_http_gzip_ctx_t *ctx); static ngx_int_t ngx_http_gzip_add_variables(ngx_conf_t *cf); static ngx_int_t ngx_http_gzip_ratio_variable(ngx_http_request_t *r, ngx_http_variable_value_t *v, uintptr_t data); static ngx_int_t ngx_http_gzip_filter_init(ngx_conf_t *cf); static void *ngx_http_gzip_create_conf(ngx_conf_t *cf); static char *ngx_http_gzip_merge_conf(ngx_conf_t *cf, void *parent, void *child); static char *ngx_http_gzip_window(ngx_conf_t *cf, void *post, void *data); static char *ngx_http_gzip_hash(ngx_conf_t *cf, void *post, void *data); static ngx_conf_num_bounds_t ngx_http_gzip_comp_level_bounds = { ngx_conf_check_num_bounds, 1, 9 }; static ngx_conf_post_handler_pt ngx_http_gzip_window_p = ngx_http_gzip_window; static ngx_conf_post_handler_pt ngx_http_gzip_hash_p = ngx_http_gzip_hash; static ngx_command_t ngx_http_gzip_filter_commands[] = { { ngx_string("gzip"), NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_HTTP_LIF_CONF |NGX_CONF_FLAG, ngx_conf_set_flag_slot, NGX_HTTP_LOC_CONF_OFFSET, offsetof(ngx_http_gzip_conf_t, enable), NULL }, { ngx_string("gzip_buffers"), NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_TAKE2, ngx_conf_set_bufs_slot, NGX_HTTP_LOC_CONF_OFFSET, offsetof(ngx_http_gzip_conf_t, bufs), NULL }, { ngx_string("gzip_types"), NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_1MORE, ngx_http_types_slot, NGX_HTTP_LOC_CONF_OFFSET, offsetof(ngx_http_gzip_conf_t, types_keys), &ngx_http_html_default_types[0] }, { ngx_string("gzip_comp_level"), NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_TAKE1, ngx_conf_set_num_slot, NGX_HTTP_LOC_CONF_OFFSET, offsetof(ngx_http_gzip_conf_t, level), &ngx_http_gzip_comp_level_bounds }, { ngx_string("gzip_window"), NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_TAKE1, ngx_conf_set_size_slot, NGX_HTTP_LOC_CONF_OFFSET, offsetof(ngx_http_gzip_conf_t, wbits), &ngx_http_gzip_window_p }, { ngx_string("gzip_hash"), NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_TAKE1, ngx_conf_set_size_slot, NGX_HTTP_LOC_CONF_OFFSET, offsetof(ngx_http_gzip_conf_t, memlevel), &ngx_http_gzip_hash_p }, { ngx_string("postpone_gzipping"), NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_TAKE1, ngx_conf_set_size_slot, NGX_HTTP_LOC_CONF_OFFSET, offsetof(ngx_http_gzip_conf_t, postpone_gzipping), NULL }, { ngx_string("gzip_no_buffer"), NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_FLAG, ngx_conf_set_flag_slot, NGX_HTTP_LOC_CONF_OFFSET, offsetof(ngx_http_gzip_conf_t, no_buffer), NULL }, { ngx_string("gzip_min_length"), NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_TAKE1, ngx_conf_set_size_slot, NGX_HTTP_LOC_CONF_OFFSET, offsetof(ngx_http_gzip_conf_t, min_length), NULL }, ngx_null_command }; static ngx_http_module_t ngx_http_gzip_filter_module_ctx = { ngx_http_gzip_add_variables, /* preconfiguration */ ngx_http_gzip_filter_init, /* postconfiguration */ NULL, /* create main configuration */ NULL, /* init main configuration */ NULL, /* create server configuration */ NULL, /* merge server configuration */ ngx_http_gzip_create_conf, /* create location configuration */ ngx_http_gzip_merge_conf /* merge location configuration */ }; ngx_module_t ngx_http_gzip_filter_module = { NGX_MODULE_V1, &ngx_http_gzip_filter_module_ctx, /* module context */ ngx_http_gzip_filter_commands, /* module directives */ NGX_HTTP_MODULE, /* module type */ NULL, /* init master */ NULL, /* init module */ NULL, /* init process */ NULL, /* init thread */ NULL, /* exit thread */ NULL, /* exit process */ NULL, /* exit master */ NGX_MODULE_V1_PADDING }; static ngx_str_t ngx_http_gzip_ratio = ngx_string("gzip_ratio"); static ngx_http_output_header_filter_pt ngx_http_next_header_filter; static ngx_http_output_body_filter_pt ngx_http_next_body_filter; static ngx_int_t ngx_http_gzip_header_filter(ngx_http_request_t *r) { ngx_table_elt_t *h; ngx_http_gzip_ctx_t *ctx; ngx_http_gzip_conf_t *conf; conf = ngx_http_get_module_loc_conf(r, ngx_http_gzip_filter_module); if (!conf->enable || (r->headers_out.status != NGX_HTTP_OK && r->headers_out.status != NGX_HTTP_FORBIDDEN && r->headers_out.status != NGX_HTTP_NOT_FOUND) || (r->headers_out.content_encoding && r->headers_out.content_encoding->value.len) || (r->headers_out.content_length_n != -1 && r->headers_out.content_length_n < conf->min_length) || ngx_http_test_content_type(r, &conf->types) == NULL || r->header_only) { return ngx_http_next_header_filter(r); } r->gzip_vary = 1; #if (NGX_HTTP_DEGRADATION) { ngx_http_core_loc_conf_t *clcf; clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module); if (clcf->gzip_disable_degradation && ngx_http_degraded(r)) { return ngx_http_next_header_filter(r); } } #endif if (!r->gzip_tested) { if (ngx_http_gzip_ok(r) != NGX_OK) { return ngx_http_next_header_filter(r); } } else if (!r->gzip_ok) { return ngx_http_next_header_filter(r); } ctx = ngx_pcalloc(r->pool, sizeof(ngx_http_gzip_ctx_t)); if (ctx == NULL) { return NGX_ERROR; } ngx_http_set_ctx(r, ctx, ngx_http_gzip_filter_module); ctx->request = r; ctx->buffering = (conf->postpone_gzipping != 0); ngx_http_gzip_filter_memory(r, ctx); h = ngx_list_push(&r->headers_out.headers); if (h == NULL) { return NGX_ERROR; } h->hash = 1; ngx_str_set(&h->key, "Content-Encoding"); ngx_str_set(&h->value, "gzip"); r->headers_out.content_encoding = h; r->main_filter_need_in_memory = 1; ngx_http_clear_content_length(r); ngx_http_clear_accept_ranges(r); ngx_http_weak_etag(r); return ngx_http_next_header_filter(r); } static ngx_int_t ngx_http_gzip_body_filter(ngx_http_request_t *r, ngx_chain_t *in) { int rc; ngx_uint_t flush; ngx_chain_t *cl; ngx_http_gzip_ctx_t *ctx; ctx = ngx_http_get_module_ctx(r, ngx_http_gzip_filter_module); if (ctx == NULL || ctx->done || r->header_only) { return ngx_http_next_body_filter(r, in); } ngx_log_debug0(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "http gzip filter"); if (ctx->buffering) { /* * With default memory settings zlib starts to output gzipped data * only after it has got about 90K, so it makes sense to allocate * zlib memory (200-400K) only after we have enough data to compress. * Although we copy buffers, nevertheless for not big responses * this allows to allocate zlib memory, to compress and to output * the response in one step using hot CPU cache. */ if (in) { switch (ngx_http_gzip_filter_buffer(ctx, in)) { case NGX_OK: return NGX_OK; case NGX_DONE: in = NULL; break; default: /* NGX_ERROR */ goto failed; } } else { ctx->buffering = 0; } } if (ctx->preallocated == NULL) { if (ngx_http_gzip_filter_deflate_start(r, ctx) != NGX_OK) { goto failed; } } if (in) { if (ngx_chain_add_copy(r->pool, &ctx->in, in) != NGX_OK) { goto failed; } r->connection->buffered |= NGX_HTTP_GZIP_BUFFERED; } if (ctx->nomem) { /* flush busy buffers */ if (ngx_http_next_body_filter(r, NULL) == NGX_ERROR) { goto failed; } cl = NULL; ngx_chain_update_chains(r->pool, &ctx->free, &ctx->busy, &cl, (ngx_buf_tag_t) &ngx_http_gzip_filter_module); ctx->nomem = 0; flush = 0; } else { flush = ctx->busy ? 1 : 0; } for ( ;; ) { /* cycle while we can write to a client */ for ( ;; ) { /* cycle while there is data to feed zlib and ... */ rc = ngx_http_gzip_filter_add_data(r, ctx); if (rc == NGX_DECLINED) { break; } if (rc == NGX_AGAIN) { continue; } /* ... there are buffers to write zlib output */ rc = ngx_http_gzip_filter_get_buf(r, ctx); if (rc == NGX_DECLINED) { break; } if (rc == NGX_ERROR) { goto failed; } rc = ngx_http_gzip_filter_deflate(r, ctx); if (rc == NGX_OK) { break; } if (rc == NGX_ERROR) { goto failed; } /* rc == NGX_AGAIN */ } if (ctx->out == NULL && !flush) { ngx_http_gzip_filter_free_copy_buf(r, ctx); return ctx->busy ? NGX_AGAIN : NGX_OK; } if (!ctx->gzheader) { if (ngx_http_gzip_filter_gzheader(r, ctx) != NGX_OK) { goto failed; } } rc = ngx_http_next_body_filter(r, ctx->out); if (rc == NGX_ERROR) { goto failed; } ngx_http_gzip_filter_free_copy_buf(r, ctx); ngx_chain_update_chains(r->pool, &ctx->free, &ctx->busy, &ctx->out, (ngx_buf_tag_t) &ngx_http_gzip_filter_module); ctx->last_out = &ctx->out; ctx->nomem = 0; flush = 0; if (ctx->done) { return rc; } } /* unreachable */ failed: ctx->done = 1; if (ctx->preallocated) { deflateEnd(&ctx->zstream); ngx_pfree(r->pool, ctx->preallocated); } ngx_http_gzip_filter_free_copy_buf(r, ctx); return NGX_ERROR; } static void ngx_http_gzip_filter_memory(ngx_http_request_t *r, ngx_http_gzip_ctx_t *ctx) { int wbits, memlevel; ngx_http_gzip_conf_t *conf; conf = ngx_http_get_module_loc_conf(r, ngx_http_gzip_filter_module); wbits = conf->wbits; memlevel = conf->memlevel; if (r->headers_out.content_length_n > 0) { /* the actual zlib window size is smaller by 262 bytes */ while (r->headers_out.content_length_n < ((1 << (wbits - 1)) - 262)) { wbits--; memlevel--; } if (memlevel < 1) { memlevel = 1; } } ctx->wbits = wbits; ctx->memlevel = memlevel; /* * We preallocate a memory for zlib in one buffer (200K-400K), this * decreases a number of malloc() and free() calls and also probably * decreases a number of syscalls (sbrk()/mmap() and so on). * Besides we free the memory as soon as a gzipping will complete * and do not wait while a whole response will be sent to a client. * * 8K is for zlib deflate_state, it takes * *) 5816 bytes on i386 and sparc64 (32-bit mode) * *) 5920 bytes on amd64 and sparc64 */ ctx->allocated = 8192 + (1 << (wbits + 2)) + (1 << (memlevel + 9)); } static ngx_int_t ngx_http_gzip_filter_buffer(ngx_http_gzip_ctx_t *ctx, ngx_chain_t *in) { size_t size, buffered; ngx_buf_t *b, *buf; ngx_chain_t *cl, **ll; ngx_http_request_t *r; ngx_http_gzip_conf_t *conf; r = ctx->request; r->connection->buffered |= NGX_HTTP_GZIP_BUFFERED; buffered = 0; ll = &ctx->in; for (cl = ctx->in; cl; cl = cl->next) { buffered += cl->buf->last - cl->buf->pos; ll = &cl->next; } conf = ngx_http_get_module_loc_conf(r, ngx_http_gzip_filter_module); while (in) { cl = ngx_alloc_chain_link(r->pool); if (cl == NULL) { return NGX_ERROR; } b = in->buf; size = b->last - b->pos; buffered += size; if (b->flush || b->last_buf || buffered > conf->postpone_gzipping) { ctx->buffering = 0; } if (ctx->buffering && size) { buf = ngx_create_temp_buf(r->pool, size); if (buf == NULL) { return NGX_ERROR; } buf->last = ngx_cpymem(buf->pos, b->pos, size); b->pos = b->last; buf->last_buf = b->last_buf; buf->tag = (ngx_buf_tag_t) &ngx_http_gzip_filter_module; cl->buf = buf; } else { cl->buf = b; } *ll = cl; ll = &cl->next; in = in->next; } *ll = NULL; return ctx->buffering ? NGX_OK : NGX_DONE; } static ngx_int_t ngx_http_gzip_filter_deflate_start(ngx_http_request_t *r, ngx_http_gzip_ctx_t *ctx) { int rc; ngx_http_gzip_conf_t *conf; conf = ngx_http_get_module_loc_conf(r, ngx_http_gzip_filter_module); ctx->preallocated = ngx_palloc(r->pool, ctx->allocated); if (ctx->preallocated == NULL) { return NGX_ERROR; } ctx->free_mem = ctx->preallocated; ctx->zstream.zalloc = ngx_http_gzip_filter_alloc; ctx->zstream.zfree = ngx_http_gzip_filter_free; ctx->zstream.opaque = ctx; rc = deflateInit2(&ctx->zstream, (int) conf->level, Z_DEFLATED, - ctx->wbits, ctx->memlevel, Z_DEFAULT_STRATEGY); if (rc != Z_OK) { ngx_log_error(NGX_LOG_ALERT, r->connection->log, 0, "deflateInit2() failed: %d", rc); return NGX_ERROR; } ctx->last_out = &ctx->out; ctx->crc32 = crc32(0L, Z_NULL, 0); ctx->flush = Z_NO_FLUSH; return NGX_OK; } static ngx_int_t ngx_http_gzip_filter_gzheader(ngx_http_request_t *r, ngx_http_gzip_ctx_t *ctx) { ngx_buf_t *b; ngx_chain_t *cl; static u_char gzheader[10] = { 0x1f, 0x8b, Z_DEFLATED, 0, 0, 0, 0, 0, 0, 3 }; b = ngx_pcalloc(r->pool, sizeof(ngx_buf_t)); if (b == NULL) { return NGX_ERROR; } b->memory = 1; b->pos = gzheader; b->last = b->pos + 10; cl = ngx_alloc_chain_link(r->pool); if (cl == NULL) { return NGX_ERROR; } cl->buf = b; cl->next = ctx->out; ctx->out = cl; ctx->gzheader = 1; return NGX_OK; } static ngx_int_t ngx_http_gzip_filter_add_data(ngx_http_request_t *r, ngx_http_gzip_ctx_t *ctx) { if (ctx->zstream.avail_in || ctx->flush != Z_NO_FLUSH || ctx->redo) { return NGX_OK; } ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "gzip in: %p", ctx->in); if (ctx->in == NULL) { return NGX_DECLINED; } if (ctx->copy_buf) { /* * to avoid CPU cache trashing we do not free() just quit buf, * but postpone free()ing after zlib compressing and data output */ ctx->copy_buf->next = ctx->copied; ctx->copied = ctx->copy_buf; ctx->copy_buf = NULL; } ctx->in_buf = ctx->in->buf; if (ctx->in_buf->tag == (ngx_buf_tag_t) &ngx_http_gzip_filter_module) { ctx->copy_buf = ctx->in; } ctx->in = ctx->in->next; ctx->zstream.next_in = ctx->in_buf->pos; ctx->zstream.avail_in = ctx->in_buf->last - ctx->in_buf->pos; ngx_log_debug3(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "gzip in_buf:%p ni:%p ai:%ud", ctx->in_buf, ctx->zstream.next_in, ctx->zstream.avail_in); if (ctx->in_buf->last_buf) { ctx->flush = Z_FINISH; } else if (ctx->in_buf->flush) { ctx->flush = Z_SYNC_FLUSH; } if (ctx->zstream.avail_in) { ctx->crc32 = crc32(ctx->crc32, ctx->zstream.next_in, ctx->zstream.avail_in); } else if (ctx->flush == Z_NO_FLUSH) { return NGX_AGAIN; } return NGX_OK; } static ngx_int_t ngx_http_gzip_filter_get_buf(ngx_http_request_t *r, ngx_http_gzip_ctx_t *ctx) { ngx_http_gzip_conf_t *conf; if (ctx->zstream.avail_out) { return NGX_OK; } conf = ngx_http_get_module_loc_conf(r, ngx_http_gzip_filter_module); if (ctx->free) { ctx->out_buf = ctx->free->buf; ctx->free = ctx->free->next; } else if (ctx->bufs < conf->bufs.num) { ctx->out_buf = ngx_create_temp_buf(r->pool, conf->bufs.size); if (ctx->out_buf == NULL) { return NGX_ERROR; } ctx->out_buf->tag = (ngx_buf_tag_t) &ngx_http_gzip_filter_module; ctx->out_buf->recycled = 1; ctx->bufs++; } else { ctx->nomem = 1; return NGX_DECLINED; } ctx->zstream.next_out = ctx->out_buf->pos; ctx->zstream.avail_out = conf->bufs.size; return NGX_OK; } static ngx_int_t ngx_http_gzip_filter_deflate(ngx_http_request_t *r, ngx_http_gzip_ctx_t *ctx) { int rc; ngx_buf_t *b; ngx_chain_t *cl; ngx_http_gzip_conf_t *conf; ngx_log_debug6(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "deflate in: ni:%p no:%p ai:%ud ao:%ud fl:%d redo:%d", ctx->zstream.next_in, ctx->zstream.next_out, ctx->zstream.avail_in, ctx->zstream.avail_out, ctx->flush, ctx->redo); rc = deflate(&ctx->zstream, ctx->flush); if (rc != Z_OK && rc != Z_STREAM_END && rc != Z_BUF_ERROR) { ngx_log_error(NGX_LOG_ALERT, r->connection->log, 0, "deflate() failed: %d, %d", ctx->flush, rc); return NGX_ERROR; } ngx_log_debug5(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "deflate out: ni:%p no:%p ai:%ud ao:%ud rc:%d", ctx->zstream.next_in, ctx->zstream.next_out, ctx->zstream.avail_in, ctx->zstream.avail_out, rc); ngx_log_debug2(NGX_LOG_DEBUG_HTTP, r->connection->log, 0, "gzip in_buf:%p pos:%p", ctx->in_buf, ctx->in_buf->pos); if (ctx->zstream.next_in) { ctx->in_buf->pos = ctx->zstream.next_in; if (ctx->zstream.avail_in == 0) { ctx->zstream.next_in = NULL; } } ctx->out_buf->last = ctx->zstream.next_out; if (ctx->zstream.avail_out == 0) { /* zlib wants to output some more gzipped data */ cl = ngx_alloc_chain_link(r->pool); if (cl == NULL) { return NGX_ERROR; } cl->buf = ctx->out_buf; cl->next = NULL; *ctx->last_out = cl; ctx->last_out = &cl->next; ctx->redo = 1; return NGX_AGAIN; } ctx->redo = 0; if (ctx->flush == Z_SYNC_FLUSH) { ctx->flush = Z_NO_FLUSH; cl = ngx_alloc_chain_link(r->pool); if (cl == NULL) { return NGX_ERROR; } b = ctx->out_buf; if (ngx_buf_size(b) == 0) { b = ngx_calloc_buf(ctx->request->pool); if (b == NULL) { return NGX_ERROR; } } else { ctx->zstream.avail_out = 0; } b->flush = 1; cl->buf = b; cl->next = NULL; *ctx->last_out = cl; ctx->last_out = &cl->next; r->connection->buffered &= ~NGX_HTTP_GZIP_BUFFERED; return NGX_OK; } if (rc == Z_STREAM_END) { if (ngx_http_gzip_filter_deflate_end(r, ctx) != NGX_OK) { return NGX_ERROR; } return NGX_OK; } conf = ngx_http_get_module_loc_conf(r, ngx_http_gzip_filter_module); if (conf->no_buffer && ctx->in == NULL) { cl = ngx_alloc_chain_link(r->pool); if (cl == NULL) { return NGX_ERROR; } cl->buf = ctx->out_buf; cl->next = NULL; *ctx->last_out = cl; ctx->last_out = &cl->next; return NGX_OK; } return NGX_AGAIN; } static ngx_int_t ngx_http_gzip_filter_deflate_end(ngx_http_request_t *r, ngx_http_gzip_ctx_t *ctx) { int rc; ngx_buf_t *b; ngx_chain_t *cl; struct gztrailer *trailer; ctx->zin = ctx->zstream.total_in; ctx->zout = 10 + ctx->zstream.total_out + 8; rc = deflateEnd(&ctx->zstream); if (rc != Z_OK) { ngx_log_error(NGX_LOG_ALERT, r->connection->log, 0, "deflateEnd() failed: %d", rc); return NGX_ERROR; } ngx_pfree(r->pool, ctx->preallocated); cl = ngx_alloc_chain_link(r->pool); if (cl == NULL) { return NGX_ERROR; } cl->buf = ctx->out_buf; cl->next = NULL; *ctx->last_out = cl; ctx->last_out = &cl->next; if (ctx->zstream.avail_out >= 8) { trailer = (struct gztrailer *) ctx->out_buf->last; ctx->out_buf->last += 8; ctx->out_buf->last_buf = 1; } else { b = ngx_create_temp_buf(r->pool, 8); if (b == NULL) { return NGX_ERROR; } b->last_buf = 1; cl = ngx_alloc_chain_link(r->pool); if (cl == NULL) { return NGX_ERROR; } cl->buf = b; cl->next = NULL; *ctx->last_out = cl; ctx->last_out = &cl->next; trailer = (struct gztrailer *) b->pos; b->last += 8; } #if (NGX_HAVE_LITTLE_ENDIAN && NGX_HAVE_NONALIGNED) trailer->crc32 = ctx->crc32; trailer->zlen = ctx->zin; #else trailer->crc32[0] = (u_char) (ctx->crc32 & 0xff); trailer->crc32[1] = (u_char) ((ctx->crc32 >> 8) & 0xff); trailer->crc32[2] = (u_char) ((ctx->crc32 >> 16) & 0xff); trailer->crc32[3] = (u_char) ((ctx->crc32 >> 24) & 0xff); trailer->zlen[0] = (u_char) (ctx->zin & 0xff); trailer->zlen[1] = (u_char) ((ctx->zin >> 8) & 0xff); trailer->zlen[2] = (u_char) ((ctx->zin >> 16) & 0xff); trailer->zlen[3] = (u_char) ((ctx->zin >> 24) & 0xff); #endif ctx->zstream.avail_in = 0; ctx->zstream.avail_out = 0; ctx->done = 1; r->connection->buffered &= ~NGX_HTTP_GZIP_BUFFERED; return NGX_OK; } static void * ngx_http_gzip_filter_alloc(void *opaque, u_int items, u_int size) { ngx_http_gzip_ctx_t *ctx = opaque; void *p; ngx_uint_t alloc; alloc = items * size; if (alloc % 512 != 0 && alloc < 8192) { /* * The zlib deflate_state allocation, it takes about 6K, * we allocate 8K. Other allocations are divisible by 512. */ alloc = 8192; } if (alloc <= ctx->allocated) { p = ctx->free_mem; ctx->free_mem += alloc; ctx->allocated -= alloc; ngx_log_debug4(NGX_LOG_DEBUG_HTTP, ctx->request->connection->log, 0, "gzip alloc: n:%ud s:%ud a:%ud p:%p", items, size, alloc, p); return p; } ngx_log_error(NGX_LOG_ALERT, ctx->request->connection->log, 0, "gzip filter failed to use preallocated memory: %ud of %ud", items * size, ctx->allocated); p = ngx_palloc(ctx->request->pool, items * size); return p; } static void ngx_http_gzip_filter_free(void *opaque, void *address) { #if 0 ngx_http_gzip_ctx_t *ctx = opaque; ngx_log_debug1(NGX_LOG_DEBUG_HTTP, ctx->request->connection->log, 0, "gzip free: %p", address); #endif } static void ngx_http_gzip_filter_free_copy_buf(ngx_http_request_t *r, ngx_http_gzip_ctx_t *ctx) { ngx_chain_t *cl; for (cl = ctx->copied; cl; cl = cl->next) { ngx_pfree(r->pool, cl->buf->start); } ctx->copied = NULL; } static ngx_int_t ngx_http_gzip_add_variables(ngx_conf_t *cf) { ngx_http_variable_t *var; var = ngx_http_add_variable(cf, &ngx_http_gzip_ratio, NGX_HTTP_VAR_NOHASH); if (var == NULL) { return NGX_ERROR; } var->get_handler = ngx_http_gzip_ratio_variable; return NGX_OK; } static ngx_int_t ngx_http_gzip_ratio_variable(ngx_http_request_t *r, ngx_http_variable_value_t *v, uintptr_t data) { ngx_uint_t zint, zfrac; ngx_http_gzip_ctx_t *ctx; v->valid = 1; v->no_cacheable = 0; v->not_found = 0; ctx = ngx_http_get_module_ctx(r, ngx_http_gzip_filter_module); if (ctx == NULL || ctx->zout == 0) { v->not_found = 1; return NGX_OK; } v->data = ngx_pnalloc(r->pool, NGX_INT32_LEN + 3); if (v->data == NULL) { return NGX_ERROR; } zint = (ngx_uint_t) (ctx->zin / ctx->zout); zfrac = (ngx_uint_t) ((ctx->zin * 100 / ctx->zout) % 100); if ((ctx->zin * 1000 / ctx->zout) % 10 > 4) { /* the rounding, e.g., 2.125 to 2.13 */ zfrac++; if (zfrac > 99) { zint++; zfrac = 0; } } v->len = ngx_sprintf(v->data, "%ui.%02ui", zint, zfrac) - v->data; return NGX_OK; } static void * ngx_http_gzip_create_conf(ngx_conf_t *cf) { ngx_http_gzip_conf_t *conf; conf = ngx_pcalloc(cf->pool, sizeof(ngx_http_gzip_conf_t)); if (conf == NULL) { return NULL; } /* * set by ngx_pcalloc(): * * conf->bufs.num = 0; * conf->types = { NULL }; * conf->types_keys = NULL; */ conf->enable = NGX_CONF_UNSET; conf->no_buffer = NGX_CONF_UNSET; conf->postpone_gzipping = NGX_CONF_UNSET_SIZE; conf->level = NGX_CONF_UNSET; conf->wbits = NGX_CONF_UNSET_SIZE; conf->memlevel = NGX_CONF_UNSET_SIZE; conf->min_length = NGX_CONF_UNSET; return conf; } static char * ngx_http_gzip_merge_conf(ngx_conf_t *cf, void *parent, void *child) { ngx_http_gzip_conf_t *prev = parent; ngx_http_gzip_conf_t *conf = child; ngx_conf_merge_value(conf->enable, prev->enable, 0); ngx_conf_merge_value(conf->no_buffer, prev->no_buffer, 0); ngx_conf_merge_bufs_value(conf->bufs, prev->bufs, (128 * 1024) / ngx_pagesize, ngx_pagesize); ngx_conf_merge_size_value(conf->postpone_gzipping, prev->postpone_gzipping, 0); ngx_conf_merge_value(conf->level, prev->level, 1); ngx_conf_merge_size_value(conf->wbits, prev->wbits, MAX_WBITS); ngx_conf_merge_size_value(conf->memlevel, prev->memlevel, MAX_MEM_LEVEL - 1); ngx_conf_merge_value(conf->min_length, prev->min_length, 20); if (ngx_http_merge_types(cf, &conf->types_keys, &conf->types, &prev->types_keys, &prev->types, ngx_http_html_default_types) != NGX_OK) { return NGX_CONF_ERROR; } return NGX_CONF_OK; } static ngx_int_t ngx_http_gzip_filter_init(ngx_conf_t *cf) { ngx_http_next_header_filter = ngx_http_top_header_filter; ngx_http_top_header_filter = ngx_http_gzip_header_filter; ngx_http_next_body_filter = ngx_http_top_body_filter; ngx_http_top_body_filter = ngx_http_gzip_body_filter; return NGX_OK; } static char * ngx_http_gzip_window(ngx_conf_t *cf, void *post, void *data) { size_t *np = data; size_t wbits, wsize; wbits = 15; for (wsize = 32 * 1024; wsize > 256; wsize >>= 1) { if (wsize == *np) { *np = wbits; return NGX_CONF_OK; } wbits--; } return "must be 512, 1k, 2k, 4k, 8k, 16k, or 32k"; } static char * ngx_http_gzip_hash(ngx_conf_t *cf, void *post, void *data) { size_t *np = data; size_t memlevel, hsize; memlevel = 9; for (hsize = 128 * 1024; hsize > 256; hsize >>= 1) { if (hsize == *np) { *np = memlevel; return NGX_CONF_OK; } memlevel--; } return "must be 512, 1k, 2k, 4k, 8k, 16k, 32k, 64k, or 128k"; }
goby/nginx-releases
src/http/modules/ngx_http_gzip_filter_module.c
C
bsd-2-clause
31,348
// Copyright 2015 Joyent, Inc. module.exports = { read: read, readPkcs8: readPkcs8, write: write, writePkcs8: writePkcs8, readECDSACurve: readECDSACurve, writeECDSACurve: writeECDSACurve }; var assert = require('assert-plus'); var asn1 = require('asn1'); var algs = require('../algs'); var utils = require('../utils'); var Key = require('../key'); var PrivateKey = require('../private-key'); var pem = require('./pem'); function read(buf, options) { return (pem.read(buf, options, 'pkcs8')); } function write(key, options) { return (pem.write(key, options, 'pkcs8')); } /* Helper to read in a single mpint */ function readMPInt(der, nm) { assert.strictEqual(der.peek(), asn1.Ber.Integer, nm + ' is not an Integer'); return (utils.mpNormalize(der.readString(asn1.Ber.Integer, true))); } function readPkcs8(alg, type, der) { /* Private keys in pkcs#8 format have a weird extra int */ if (der.peek() === asn1.Ber.Integer) { assert.strictEqual(type, 'private', 'unexpected Integer at start of public key'); der.readString(asn1.Ber.Integer, true); } der.readSequence(); var next = der.offset + der.length; var oid = der.readOID(); switch (oid) { case '1.2.840.113549.1.1.1': der._offset = next; if (type === 'public') return (readPkcs8RSAPublic(der)); else return (readPkcs8RSAPrivate(der)); case '1.2.840.10040.4.1': if (type === 'public') return (readPkcs8DSAPublic(der)); else return (readPkcs8DSAPrivate(der)); case '1.2.840.10045.2.1': if (type === 'public') return (readPkcs8ECDSAPublic(der)); else return (readPkcs8ECDSAPrivate(der)); default: throw (new Error('Unknown key type OID ' + oid)); } } function readPkcs8RSAPublic(der) { // bit string sequence der.readSequence(asn1.Ber.BitString); der.readByte(); der.readSequence(); // modulus var n = readMPInt(der, 'modulus'); var e = readMPInt(der, 'exponent'); // now, make the key var key = { type: 'rsa', source: der.originalInput, parts: [ { name: 'e', data: e }, { name: 'n', data: n } ] }; return (new Key(key)); } function readPkcs8RSAPrivate(der) { der.readSequence(asn1.Ber.OctetString); der.readSequence(); var ver = readMPInt(der, 'version'); assert.equal(ver[0], 0x0, 'unknown RSA private key version'); // modulus then public exponent var n = readMPInt(der, 'modulus'); var e = readMPInt(der, 'public exponent'); var d = readMPInt(der, 'private exponent'); var p = readMPInt(der, 'prime1'); var q = readMPInt(der, 'prime2'); var dmodp = readMPInt(der, 'exponent1'); var dmodq = readMPInt(der, 'exponent2'); var iqmp = readMPInt(der, 'iqmp'); // now, make the key var key = { type: 'rsa', parts: [ { name: 'n', data: n }, { name: 'e', data: e }, { name: 'd', data: d }, { name: 'iqmp', data: iqmp }, { name: 'p', data: p }, { name: 'q', data: q }, { name: 'dmodp', data: dmodp }, { name: 'dmodq', data: dmodq } ] }; return (new PrivateKey(key)); } function readPkcs8DSAPublic(der) { der.readSequence(); var p = readMPInt(der, 'p'); var q = readMPInt(der, 'q'); var g = readMPInt(der, 'g'); // bit string sequence der.readSequence(asn1.Ber.BitString); der.readByte(); var y = readMPInt(der, 'y'); // now, make the key var key = { type: 'dsa', parts: [ { name: 'p', data: p }, { name: 'q', data: q }, { name: 'g', data: g }, { name: 'y', data: y } ] }; return (new Key(key)); } function readPkcs8DSAPrivate(der) { der.readSequence(); var p = readMPInt(der, 'p'); var q = readMPInt(der, 'q'); var g = readMPInt(der, 'g'); der.readSequence(asn1.Ber.OctetString); var x = readMPInt(der, 'x'); /* The pkcs#8 format does not include the public key */ var y = utils.calculateDSAPublic(g, p, x); var key = { type: 'dsa', parts: [ { name: 'p', data: p }, { name: 'q', data: q }, { name: 'g', data: g }, { name: 'y', data: y }, { name: 'x', data: x } ] }; return (new PrivateKey(key)); } function readECDSACurve(der) { var curveName, curveNames; var j, c, cd; if (der.peek() === asn1.Ber.OID) { var oid = der.readOID(); curveNames = Object.keys(algs.curves); for (j = 0; j < curveNames.length; ++j) { c = curveNames[j]; cd = algs.curves[c]; if (cd.pkcs8oid === oid) { curveName = c; break; } } } else { // ECParameters sequence der.readSequence(); var version = der.readString(asn1.Ber.Integer, true); assert.strictEqual(version[0], 1, 'ECDSA key not version 1'); var curve = {}; // FieldID sequence der.readSequence(); var fieldTypeOid = der.readOID(); assert.strictEqual(fieldTypeOid, '1.2.840.10045.1.1', 'ECDSA key is not from a prime-field'); var p = curve.p = utils.mpNormalize( der.readString(asn1.Ber.Integer, true)); /* * p always starts with a 1 bit, so count the zeros to get its * real size. */ curve.size = p.length * 8 - utils.countZeros(p); // Curve sequence der.readSequence(); curve.a = utils.mpNormalize( der.readString(asn1.Ber.OctetString, true)); curve.b = utils.mpNormalize( der.readString(asn1.Ber.OctetString, true)); if (der.peek() === asn1.Ber.BitString) curve.s = der.readString(asn1.Ber.BitString, true); // Combined Gx and Gy curve.G = der.readString(asn1.Ber.OctetString, true); assert.strictEqual(curve.G[0], 0x4, 'uncompressed G is required'); curve.n = utils.mpNormalize( der.readString(asn1.Ber.Integer, true)); curve.h = utils.mpNormalize( der.readString(asn1.Ber.Integer, true)); assert.strictEqual(curve.h[0], 0x1, 'a cofactor=1 curve is ' + 'required'); curveNames = Object.keys(algs.curves); var ks = Object.keys(curve); for (j = 0; j < curveNames.length; ++j) { c = curveNames[j]; cd = algs.curves[c]; var equal = true; for (var i = 0; i < ks.length; ++i) { var k = ks[i]; if (cd[k] === undefined) continue; if (typeof (cd[k]) === 'object' && cd[k].equals !== undefined) { if (!cd[k].equals(curve[k])) { equal = false; break; } } else if (Buffer.isBuffer(cd[k])) { if (cd[k].toString('binary') !== curve[k].toString('binary')) { equal = false; break; } } else { if (cd[k] !== curve[k]) { equal = false; break; } } } if (equal) { curveName = c; break; } } } return (curveName); } function readPkcs8ECDSAPrivate(der) { var curveName = readECDSACurve(der); assert.string(curveName, 'a known elliptic curve'); der.readSequence(asn1.Ber.OctetString); der.readSequence(); var version = readMPInt(der, 'version'); assert.equal(version[0], 1, 'unknown version of ECDSA key'); var d = der.readString(asn1.Ber.OctetString, true); der.readSequence(0xa1); var Q = der.readString(asn1.Ber.BitString, true); Q = utils.ecNormalize(Q); var key = { type: 'ecdsa', parts: [ { name: 'curve', data: new Buffer(curveName) }, { name: 'Q', data: Q }, { name: 'd', data: d } ] }; return (new PrivateKey(key)); } function readPkcs8ECDSAPublic(der) { var curveName = readECDSACurve(der); assert.string(curveName, 'a known elliptic curve'); var Q = der.readString(asn1.Ber.BitString, true); Q = utils.ecNormalize(Q); var key = { type: 'ecdsa', parts: [ { name: 'curve', data: new Buffer(curveName) }, { name: 'Q', data: Q } ] }; return (new Key(key)); } function writePkcs8(der, key) { der.startSequence(); if (PrivateKey.isPrivateKey(key)) { var sillyInt = new Buffer(1); sillyInt[0] = 0x0; der.writeBuffer(sillyInt, asn1.Ber.Integer); } der.startSequence(); switch (key.type) { case 'rsa': der.writeOID('1.2.840.113549.1.1.1'); if (PrivateKey.isPrivateKey(key)) writePkcs8RSAPrivate(key, der); else writePkcs8RSAPublic(key, der); break; case 'dsa': der.writeOID('1.2.840.10040.4.1'); if (PrivateKey.isPrivateKey(key)) writePkcs8DSAPrivate(key, der); else writePkcs8DSAPublic(key, der); break; case 'ecdsa': der.writeOID('1.2.840.10045.2.1'); if (PrivateKey.isPrivateKey(key)) writePkcs8ECDSAPrivate(key, der); else writePkcs8ECDSAPublic(key, der); break; default: throw (new Error('Unsupported key type: ' + key.type)); } der.endSequence(); } function writePkcs8RSAPrivate(key, der) { der.writeNull(); der.endSequence(); der.startSequence(asn1.Ber.OctetString); der.startSequence(); var version = new Buffer(1); version[0] = 0; der.writeBuffer(version, asn1.Ber.Integer); der.writeBuffer(key.part.n.data, asn1.Ber.Integer); der.writeBuffer(key.part.e.data, asn1.Ber.Integer); der.writeBuffer(key.part.d.data, asn1.Ber.Integer); der.writeBuffer(key.part.p.data, asn1.Ber.Integer); der.writeBuffer(key.part.q.data, asn1.Ber.Integer); if (!key.part.dmodp || !key.part.dmodq) utils.addRSAMissing(key); der.writeBuffer(key.part.dmodp.data, asn1.Ber.Integer); der.writeBuffer(key.part.dmodq.data, asn1.Ber.Integer); der.writeBuffer(key.part.iqmp.data, asn1.Ber.Integer); der.endSequence(); der.endSequence(); } function writePkcs8RSAPublic(key, der) { der.writeNull(); der.endSequence(); der.startSequence(asn1.Ber.BitString); der.writeByte(0x00); der.startSequence(); der.writeBuffer(key.part.n.data, asn1.Ber.Integer); der.writeBuffer(key.part.e.data, asn1.Ber.Integer); der.endSequence(); der.endSequence(); } function writePkcs8DSAPrivate(key, der) { der.startSequence(); der.writeBuffer(key.part.p.data, asn1.Ber.Integer); der.writeBuffer(key.part.q.data, asn1.Ber.Integer); der.writeBuffer(key.part.g.data, asn1.Ber.Integer); der.endSequence(); der.endSequence(); der.startSequence(asn1.Ber.OctetString); der.writeBuffer(key.part.x.data, asn1.Ber.Integer); der.endSequence(); } function writePkcs8DSAPublic(key, der) { der.startSequence(); der.writeBuffer(key.part.p.data, asn1.Ber.Integer); der.writeBuffer(key.part.q.data, asn1.Ber.Integer); der.writeBuffer(key.part.g.data, asn1.Ber.Integer); der.endSequence(); der.endSequence(); der.startSequence(asn1.Ber.BitString); der.writeByte(0x00); der.writeBuffer(key.part.y.data, asn1.Ber.Integer); der.endSequence(); } function writeECDSACurve(key, der) { var curve = algs.curves[key.curve]; if (curve.pkcs8oid) { /* This one has a name in pkcs#8, so just write the oid */ der.writeOID(curve.pkcs8oid); } else { // ECParameters sequence der.startSequence(); var version = new Buffer(1); version.writeUInt8(1, 0); der.writeBuffer(version, asn1.Ber.Integer); // FieldID sequence der.startSequence(); der.writeOID('1.2.840.10045.1.1'); // prime-field der.writeBuffer(curve.p, asn1.Ber.Integer); der.endSequence(); // Curve sequence der.startSequence(); var a = curve.p; if (a[0] === 0x0) a = a.slice(1); der.writeBuffer(a, asn1.Ber.OctetString); der.writeBuffer(curve.b, asn1.Ber.OctetString); der.writeBuffer(curve.s, asn1.Ber.BitString); der.endSequence(); der.writeBuffer(curve.G, asn1.Ber.OctetString); der.writeBuffer(curve.n, asn1.Ber.Integer); var h = curve.h; if (!h) { h = new Buffer(1); h[0] = 1; } der.writeBuffer(h, asn1.Ber.Integer); // ECParameters der.endSequence(); } } function writePkcs8ECDSAPublic(key, der) { writeECDSACurve(key, der); der.endSequence(); var Q = utils.ecNormalize(key.part.Q.data, true); der.writeBuffer(Q, asn1.Ber.BitString); } function writePkcs8ECDSAPrivate(key, der) { writeECDSACurve(key, der); der.endSequence(); der.startSequence(asn1.Ber.OctetString); der.startSequence(); var version = new Buffer(1); version[0] = 1; der.writeBuffer(version, asn1.Ber.Integer); der.writeBuffer(key.part.d.data, asn1.Ber.OctetString); der.startSequence(0xa1); var Q = utils.ecNormalize(key.part.Q.data, true); der.writeBuffer(Q, asn1.Ber.BitString); der.endSequence(); der.endSequence(); der.endSequence(); }
ticolucci/dotfiles
atom/packages/atom-beautify/node_modules/sshpk/lib/formats/pkcs8.js
JavaScript
bsd-2-clause
11,872
class Nvm < Formula desc "Manage multiple Node.js versions" homepage "https://github.com/creationix/nvm" url "https://github.com/creationix/nvm/archive/v0.30.1.tar.gz" sha256 "c3f063041407845ab4aa4ced6468084f8f63fb96fc8d904f66464e02c0867c5a" head "https://github.com/creationix/nvm.git" bottle :unneeded def install prefix.install "nvm.sh", "nvm-exec" bash_completion.install "bash_completion" => "nvm" end def caveats; <<-EOS.undent Please note that upstream has asked us to make explicit managing nvm via Homebrew is unsupported by them and you should check any problems against the standard nvm install method prior to reporting. You should create NVM's working directory if it doesn't exist: mkdir ~/.nvm Add the following to #{shell_profile} or your desired shell configuration file: export NVM_DIR=~/.nvm . $(brew --prefix nvm)/nvm.sh You can set $NVM_DIR to any location, but leaving it unchanged from #{prefix} will destroy any nvm-installed Node installations upon upgrade/reinstall. Type `nvm help` for further information. EOS end test do output = pipe_output("#{prefix}/nvm-exec 2>&1") assert_no_match /No such file or directory/, output assert_no_match /nvm: command not found/, output assert_match /Node Version Manager/, output end end
dunn/homebrew
Library/Formula/nvm.rb
Ruby
bsd-2-clause
1,369
module.exports = ClientAuthenticationPacket; function ClientAuthenticationPacket(options) { options = options || {}; this.clientFlags = options.clientFlags; this.maxPacketSize = options.maxPacketSize; this.charsetNumber = options.charsetNumber; this.filler = undefined; this.user = options.user; this.scrambleBuff = options.scrambleBuff; this.database = options.database; this.protocol41 = options.protocol41; } ClientAuthenticationPacket.prototype.parse = function(parser) { if (this.protocol41) { this.clientFlags = parser.parseUnsignedNumber(4); this.maxPacketSize = parser.parseUnsignedNumber(4); this.charsetNumber = parser.parseUnsignedNumber(1); this.filler = parser.parseFiller(23); this.user = parser.parseNullTerminatedString(); this.scrambleBuff = parser.parseLengthCodedBuffer(); this.database = parser.parseNullTerminatedString(); } else { this.clientFlags = parser.parseUnsignedNumber(2); this.maxPacketSize = parser.parseUnsignedNumber(3); this.user = parser.parseNullTerminatedString(); this.scrambleBuff = parser.parseBuffer(8); this.database = parser.parseLengthCodedBuffer(); } }; ClientAuthenticationPacket.prototype.write = function(writer) { if (this.protocol41) { writer.writeUnsignedNumber(4, this.clientFlags); writer.writeUnsignedNumber(4, this.maxPacketSize); writer.writeUnsignedNumber(1, this.charsetNumber); writer.writeFiller(23); writer.writeNullTerminatedString(this.user); writer.writeLengthCodedBuffer(this.scrambleBuff); writer.writeNullTerminatedString(this.database); } else { writer.writeUnsignedNumber(2, this.clientFlags); writer.writeUnsignedNumber(3, this.maxPacketSize); writer.writeNullTerminatedString(this.user); writer.writeBuffer(this.scrambleBuff); if (this.database && this.database.length) { writer.writeFiller(1); writer.writeBuffer(new Buffer(this.database)); } } };
jsunconf/contribs
node_modules/mysql/lib/protocol/packets/ClientAuthenticationPacket.js
JavaScript
bsd-2-clause
2,034
/* ---------------------------------------------------------------------- * Copyright (C) 2010-2013 ARM Limited. All rights reserved. * * $Date: 17. January 2013 * $Revision: V1.4.1 * * Project: CMSIS DSP Library * Title: arm_cfft_radix4_init_f32.c * * Description: Radix-4 Decimation in Frequency Floating-point CFFT & CIFFT Initialization function * * Target Processor: Cortex-M4/Cortex-M3/Cortex-M0 * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * - Neither the name of ARM LIMITED nor the names of its contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * -------------------------------------------------------------------- */ #include "arm_math.h" #include "arm_common_tables.h" /** * @ingroup groupTransforms */ /** * @addtogroup ComplexFFT * @{ */ /** * @brief Initialization function for the floating-point CFFT/CIFFT. * @deprecated Do not use this function. It has been superceded by \ref arm_cfft_f32 and will be removed * in the future. * @param[in,out] *S points to an instance of the floating-point CFFT/CIFFT structure. * @param[in] fftLen length of the FFT. * @param[in] ifftFlag flag that selects forward (ifftFlag=0) or inverse (ifftFlag=1) transform. * @param[in] bitReverseFlag flag that enables (bitReverseFlag=1) or disables (bitReverseFlag=0) bit reversal of output. * @return The function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_ARGUMENT_ERROR if <code>fftLen</code> is not a supported value. * * \par Description: * \par * The parameter <code>ifftFlag</code> controls whether a forward or inverse transform is computed. * Set(=1) ifftFlag for calculation of CIFFT otherwise CFFT is calculated * \par * The parameter <code>bitReverseFlag</code> controls whether output is in normal order or bit reversed order. * Set(=1) bitReverseFlag for output to be in normal order otherwise output is in bit reversed order. * \par * The parameter <code>fftLen</code> Specifies length of CFFT/CIFFT process. Supported FFT Lengths are 16, 64, 256, 1024. * \par * This Function also initializes Twiddle factor table pointer and Bit reversal table pointer. */ arm_status arm_cfft_radix4_init_f32( arm_cfft_radix4_instance_f32 * S, uint16_t fftLen, uint8_t ifftFlag, uint8_t bitReverseFlag) { /* Initialise the default arm status */ arm_status status = ARM_MATH_SUCCESS; /* Initialise the FFT length */ S->fftLen = fftLen; /* Initialise the Twiddle coefficient pointer */ S->pTwiddle = (float32_t *) twiddleCoef; /* Initialise the Flag for selection of CFFT or CIFFT */ S->ifftFlag = ifftFlag; /* Initialise the Flag for calculation Bit reversal or not */ S->bitReverseFlag = bitReverseFlag; /* Initializations of structure parameters depending on the FFT length */ switch (S->fftLen) { case 4096u: /* Initializations of structure parameters for 4096 point FFT */ /* Initialise the twiddle coef modifier value */ S->twidCoefModifier = 1u; /* Initialise the bit reversal table modifier */ S->bitRevFactor = 1u; /* Initialise the bit reversal table pointer */ S->pBitRevTable = (uint16_t *) armBitRevTable; /* Initialise the 1/fftLen Value */ S->onebyfftLen = 0.000244140625; break; case 1024u: /* Initializations of structure parameters for 1024 point FFT */ /* Initialise the twiddle coef modifier value */ S->twidCoefModifier = 4u; /* Initialise the bit reversal table modifier */ S->bitRevFactor = 4u; /* Initialise the bit reversal table pointer */ S->pBitRevTable = (uint16_t *) & armBitRevTable[3]; /* Initialise the 1/fftLen Value */ S->onebyfftLen = 0.0009765625f; break; case 256u: /* Initializations of structure parameters for 256 point FFT */ S->twidCoefModifier = 16u; S->bitRevFactor = 16u; S->pBitRevTable = (uint16_t *) & armBitRevTable[15]; S->onebyfftLen = 0.00390625f; break; case 64u: /* Initializations of structure parameters for 64 point FFT */ S->twidCoefModifier = 64u; S->bitRevFactor = 64u; S->pBitRevTable = (uint16_t *) & armBitRevTable[63]; S->onebyfftLen = 0.015625f; break; case 16u: /* Initializations of structure parameters for 16 point FFT */ S->twidCoefModifier = 256u; S->bitRevFactor = 256u; S->pBitRevTable = (uint16_t *) & armBitRevTable[255]; S->onebyfftLen = 0.0625f; break; default: /* Reporting argument error if fftSize is not valid value */ status = ARM_MATH_ARGUMENT_ERROR; break; } return (status); } /** * @} end of ComplexFFT group */
leijian001/stm32f429_discovery
src/cmsis/dsp_lib/TransformFunctions/arm_cfft_radix4_init_f32.c
C
bsd-2-clause
6,132
body { padding-top: 70px; } ul.nav li.main { font-weight: bold; } div.col-md-3 { padding-left: 0; } div.col-md-9 { padding-bottom: 100px; } div.source-links { float: right; } /* * Side navigation * * Scrollspy and affixed enhanced navigation to highlight sections and secondary * sections of docs content. */ /* By default it's not affixed in mobile views, so undo that */ .bs-sidebar.affix { position: static; } .bs-sidebar.well { padding: 0; } /* First level of nav */ .bs-sidenav { margin-top: 30px; margin-bottom: 30px; padding-top: 10px; padding-bottom: 10px; border-radius: 5px; } /* All levels of nav */ .bs-sidebar .nav > li > a { display: block; padding: 5px 20px; } .bs-sidebar .nav > li > a:hover, .bs-sidebar .nav > li > a:focus { text-decoration: none; border-right: 1px solid; } .bs-sidebar .nav > .active > a, .bs-sidebar .nav > .active:hover > a, .bs-sidebar .nav > .active:focus > a { font-weight: bold; background-color: transparent; border-right: 1px solid; } /* Nav: second level (shown on .active) */ .bs-sidebar .nav .nav { display: none; /* Hide by default, but at >768px, show it */ margin-bottom: 8px; } .bs-sidebar .nav .nav > li > a { padding-top: 3px; padding-bottom: 3px; padding-left: 30px; font-size: 90%; } /* Show and affix the side nav when space allows it */ @media (min-width: 992px) { .bs-sidebar .nav > .active > ul { display: block; } /* Widen the fixed sidebar */ .bs-sidebar.affix, .bs-sidebar.affix-bottom { width: 213px; } .bs-sidebar.affix { position: fixed; /* Undo the static from mobile first approach */ top: 80px; } .bs-sidebar.affix-bottom { position: absolute; /* Undo the static from mobile first approach */ } .bs-sidebar.affix-bottom .bs-sidenav, .bs-sidebar.affix .bs-sidenav { margin-top: 0; margin-bottom: 0; } } @media (min-width: 1200px) { /* Widen the fixed sidebar again */ .bs-sidebar.affix-bottom, .bs-sidebar.affix { width: 263px; } }
cazzerson/mkdocs
mkdocs/themes/amelia/css/base.css
CSS
bsd-2-clause
2,152
class Chordii < Formula desc "Text file to music sheet converter" homepage "http://www.vromans.org/johan/projects/Chordii/" url "https://downloads.sourceforge.net/project/chordii/chordii/4.5/chordii-4.5.1.tar.gz" sha256 "16a3fe92a82ca734cb6d08a573e513510acd41d4020a6306ac3769f6af5aa08d" bottle do cellar :any sha256 "5592e19ddb7affade8a918992648c87bb92a83e201e28f8afdae87e3e3ba4c2b" => :yosemite sha256 "f828c0158bfa52c9e136c0332ea595e788af14073082847d51bc4c96e6c909ac" => :mavericks sha256 "532cb785f263790e7a314df2a276c2ee73de50fe630df8514586d888c0bb6281" => :mountain_lion end def install system "./configure", "--disable-dependency-tracking", "--prefix=#{prefix}" system "make", "install" end test do (testpath/"homebrew.cho").write <<-EOS.undent {title:Homebrew} {subtitle:I can't write lyrics. Send help} [C]Thank [G]You [F]Everyone, [C]We couldn't maintain [F]Homebrew without you, [G]Here's an appreciative song from us to [C]you. EOS system bin/"chordii", "--output=#{testpath}/homebrew.ps", "homebrew.cho" assert File.exist?("homebrew.ps") end end
chiefy/homebrew
Library/Formula/chordii.rb
Ruby
bsd-2-clause
1,153
#include <string.h> #include <stdlib.h> #include <jni.h> #include <android/log.h> #define LOG_TAG "welsdec" #define LOGI(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__) extern "C" int EncMain (int argc, char* argv[]); extern "C" JNIEXPORT void JNICALL Java_com_wels_enc_WelsEncTest_DoEncoderAutoTest (JNIEnv* env, jobject thiz, jstring jsIncfgName, jstring jsInlayerName, jstring jsInyuvName, jstring jsOutbitName) { /**************** Add the native codes/API *****************/ const char* argv[] = { (char*) ("encConsole.exe"), (char*) ((*env).GetStringUTFChars (jsIncfgName, NULL)), (char*) ("-org"), (char*) ((*env).GetStringUTFChars (jsInyuvName, NULL)), (char*) ("-bf"), (char*) ((*env).GetStringUTFChars (jsOutbitName, NULL)), (char*) ("-numl"), (char*) ("1"), (char*) ("-lconfig"), (char*) ("0"), (char*) ((*env).GetStringUTFChars (jsInlayerName, NULL)) }; LOGI ("Start to run JNI module!+++"); EncMain (sizeof (argv) / sizeof (argv[0]), (char**)&argv[0]); LOGI ("End to run JNI module!+++"); } JNIEXPORT void JNICALL Java_com_wels_enc_WelsEncTest_DoEncoderTest (JNIEnv* env, jobject thiz, jstring jsFileNameIn) { /**************** Add the native codes/API *****************/ char* argv[2]; int argc = 2; argv[0] = (char*) ("encConsole.exe"); argv[1] = (char*) ((*env).GetStringUTFChars (jsFileNameIn, NULL)); LOGI ("Start to run JNI module!+++"); EncMain (argc, argv); LOGI ("End to run JNI module!+++"); }
lucas-ez/openh264
codec/build/android/enc/jni/myjni.cpp
C++
bsd-2-clause
1,513
class Boost < Formula desc "Collection of portable C++ source libraries" homepage "http://www.boost.org" url "https://downloads.sourceforge.net/project/boost/boost/1.59.0/boost_1_59_0.tar.bz2" sha256 "727a932322d94287b62abb1bd2d41723eec4356a7728909e38adb65ca25241ca" head "https://github.com/boostorg/boost.git" bottle do cellar :any revision 1 sha256 "1e664fbdfe84de7bdc91154972073587856b47c12433106e9987fa3772534b3a" => :el_capitan sha256 "b828f7f58d21ba4850507e4d5b7d44dae89649c3b8e0af758b746e8b3f17d8c1" => :yosemite sha256 "a404a68cdd9a107b38b0467226e4077aa14d1b858b4931e9fa6a4c100092ea73" => :mavericks end env :userpaths option :universal option "with-icu4c", "Build regexp engine with icu support" option "without-single", "Disable building single-threading variant" option "without-static", "Disable building static library variant" option "with-mpi", "Build with MPI support" option :cxx11 deprecated_option "with-icu" => "with-icu4c" if build.cxx11? depends_on "icu4c" => [:optional, "c++11"] depends_on "open-mpi" => "c++11" if build.with? "mpi" else depends_on "icu4c" => :optional depends_on :mpi => [:cc, :cxx, :optional] end stable do # Fixed compilation of operator<< into a record ostream, when # the operator right hand argument is not directly supported by # formatting_ostream. Fixed https://svn.boost.org/trac/boost/ticket/11549 # from https://github.com/boostorg/log/commit/7da193f.patch patch do url "https://gist.githubusercontent.com/tdsmith/bc76ddea1e2bdb2a3a18/raw/03d125b12a4b03c28ee011a2d6d42a8137061a3b/boost-log.patch" sha256 "a49fd7461d9f3b478d2bddac19adca93fe0fabab71ee67e8f140cbd7d42d6870" end # Fixed missing symbols in libboost_log_setup (on mac/clang) # from https://github.com/boostorg/log/commit/870284ed31792708a6139925d00a0aadf46bf09f patch do url "https://gist.githubusercontent.com/autosquid/a4974e112b754e03aad7/raw/985358f8909033eb7ad9aae8fbf60881ef70a275/boost-log_setup.patch" sha256 "2c3a3bae1691df5f8fce8fbd4e5727d57bd4dd813748b70d7471c855c4f19d1c" end end fails_with :llvm do build 2335 cause "Dropped arguments to functions when linking with boost" end needs :cxx11 if build.cxx11? def install # https://svn.boost.org/trac/boost/ticket/8841 if build.with?("mpi") && build.with?("single") raise <<-EOS.undent Building MPI support for both single and multi-threaded flavors is not supported. Please use "--with-mpi" together with "--without-single". EOS end ENV.universal_binary if build.universal? # Force boost to compile with the desired compiler open("user-config.jam", "a") do |file| file.write "using darwin : : #{ENV.cxx} ;\n" file.write "using mpi ;\n" if build.with? "mpi" end # libdir should be set by --prefix but isn't bootstrap_args = ["--prefix=#{prefix}", "--libdir=#{lib}"] if build.with? "icu4c" icu4c_prefix = Formula["icu4c"].opt_prefix bootstrap_args << "--with-icu=#{icu4c_prefix}" else bootstrap_args << "--without-icu" end # Handle libraries that will not be built. without_libraries = ["python"] # The context library is implemented as x86_64 ASM, so it # won't build on PPC or 32-bit builds # see https://github.com/Homebrew/homebrew/issues/17646 if Hardware::CPU.ppc? || Hardware::CPU.is_32_bit? || build.universal? without_libraries << "context" # The coroutine library depends on the context library. without_libraries << "coroutine" end # Boost.Log cannot be built using Apple GCC at the moment. Disabled # on such systems. without_libraries << "log" if ENV.compiler == :gcc || ENV.compiler == :llvm without_libraries << "mpi" if build.without? "mpi" bootstrap_args << "--without-libraries=#{without_libraries.join(",")}" # layout should be synchronized with boost-python args = ["--prefix=#{prefix}", "--libdir=#{lib}", "-d2", "-j#{ENV.make_jobs}", "--layout=tagged", "--user-config=user-config.jam", "install"] if build.with? "single" args << "threading=multi,single" else args << "threading=multi" end if build.with? "static" args << "link=shared,static" else args << "link=shared" end args << "address-model=32_64" << "architecture=x86" << "pch=off" if build.universal? # Trunk starts using "clang++ -x c" to select C compiler which breaks C++11 # handling using ENV.cxx11. Using "cxxflags" and "linkflags" still works. if build.cxx11? args << "cxxflags=-std=c++11" if ENV.compiler == :clang args << "cxxflags=-stdlib=libc++" << "linkflags=-stdlib=libc++" end end system "./bootstrap.sh", *bootstrap_args system "./b2", "headers" system "./b2", *args end def caveats s = "" # ENV.compiler doesn't exist in caveats. Check library availability # instead. if Dir["#{lib}/libboost_log*"].empty? s += <<-EOS.undent Building of Boost.Log is disabled because it requires newer GCC or Clang. EOS end if Hardware::CPU.ppc? || Hardware::CPU.is_32_bit? || build.universal? s += <<-EOS.undent Building of Boost.Context and Boost.Coroutine is disabled as they are only supported on x86_64. EOS end s end test do (testpath/"test.cpp").write <<-EOS.undent #include <boost/algorithm/string.hpp> #include <string> #include <vector> #include <assert.h> using namespace boost::algorithm; using namespace std; int main() { string str("a,b"); vector<string> strVec; split(strVec, str, is_any_of(",")); assert(strVec.size()==2); assert(strVec[0]=="a"); assert(strVec[1]=="b"); return 0; } EOS system ENV.cxx, "test.cpp", "-std=c++1y", "-lboost_system", "-o", "test" system "./test" end end
tjschuck/homebrew
Library/Formula/boost.rb
Ruby
bsd-2-clause
6,116
class Gflags < Formula desc "Library for processing command-line flags" homepage "https://gflags.github.io/gflags/" url "https://github.com/gflags/gflags/archive/v2.1.2.tar.gz" sha256 "d8331bd0f7367c8afd5fcb5f5e85e96868a00fd24b7276fa5fcee1e5575c2662" bottle do cellar :any revision 2 sha256 "8e648b5824007745eb546beffe4d94a3c25a29556f89eaa4a156dec6984335dd" => :yosemite sha256 "8f4093596ce2b359821d9a3398b82d7d327288d24ca9f0218a9ade1ace2bdbfa" => :mavericks sha256 "19d46507297d14c4ff50d99c9279ddd513df439a5d87e5325ef8fb52c37f7e6d" => :mountain_lion end option "with-debug", "Build debug version" option "with-static", "Build gflags as a static (instead of shared) library." depends_on "cmake" => :build def install ENV.append_to_cflags "-DNDEBUG" if build.without? "debug" args = std_cmake_args if build.with? "static" args << "-DBUILD_SHARED_LIBS=OFF" else args << "-DBUILD_SHARED_LIBS=ON" end mkdir "buildroot" do system "cmake", "..", *args system "make", "install" end end end
supriyantomaftuh/homebrew
Library/Formula/gflags.rb
Ruby
bsd-2-clause
1,081
/* * Copyright (C) Igor Sysoev * Copyright (C) Nginx, Inc. */ #include <ngx_config.h> #include <ngx_core.h> #include <ngx_http.h> #define NGX_HTTP_GZIP_STATIC_OFF 0 #define NGX_HTTP_GZIP_STATIC_ON 1 #define NGX_HTTP_GZIP_STATIC_ALWAYS 2 typedef struct { ngx_uint_t enable; } ngx_http_gzip_static_conf_t; static ngx_int_t ngx_http_gzip_static_handler(ngx_http_request_t *r); static void *ngx_http_gzip_static_create_conf(ngx_conf_t *cf); static char *ngx_http_gzip_static_merge_conf(ngx_conf_t *cf, void *parent, void *child); static ngx_int_t ngx_http_gzip_static_init(ngx_conf_t *cf); static ngx_conf_enum_t ngx_http_gzip_static[] = { { ngx_string("off"), NGX_HTTP_GZIP_STATIC_OFF }, { ngx_string("on"), NGX_HTTP_GZIP_STATIC_ON }, { ngx_string("always"), NGX_HTTP_GZIP_STATIC_ALWAYS }, { ngx_null_string, 0 } }; static ngx_command_t ngx_http_gzip_static_commands[] = { { ngx_string("gzip_static"), NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_TAKE1, ngx_conf_set_enum_slot, NGX_HTTP_LOC_CONF_OFFSET, offsetof(ngx_http_gzip_static_conf_t, enable), &ngx_http_gzip_static }, ngx_null_command }; ngx_http_module_t ngx_http_gzip_static_module_ctx = { NULL, /* preconfiguration */ ngx_http_gzip_static_init, /* postconfiguration */ NULL, /* create main configuration */ NULL, /* init main configuration */ NULL, /* create server configuration */ NULL, /* merge server configuration */ ngx_http_gzip_static_create_conf, /* create location configuration */ ngx_http_gzip_static_merge_conf /* merge location configuration */ }; ngx_module_t ngx_http_gzip_static_module = { NGX_MODULE_V1, &ngx_http_gzip_static_module_ctx, /* module context */ ngx_http_gzip_static_commands, /* module directives */ NGX_HTTP_MODULE, /* module type */ NULL, /* init master */ NULL, /* init module */ NULL, /* init process */ NULL, /* init thread */ NULL, /* exit thread */ NULL, /* exit process */ NULL, /* exit master */ NGX_MODULE_V1_PADDING }; static ngx_int_t ngx_http_gzip_static_handler(ngx_http_request_t *r) { u_char *p; size_t root; ngx_str_t path; ngx_int_t rc; ngx_uint_t level; ngx_log_t *log; ngx_buf_t *b; ngx_chain_t out; ngx_table_elt_t *h; ngx_open_file_info_t of; ngx_http_core_loc_conf_t *clcf; ngx_http_gzip_static_conf_t *gzcf; if (!(r->method & (NGX_HTTP_GET|NGX_HTTP_HEAD))) { return NGX_DECLINED; } if (r->uri.data[r->uri.len - 1] == '/') { return NGX_DECLINED; } gzcf = ngx_http_get_module_loc_conf(r, ngx_http_gzip_static_module); if (gzcf->enable == NGX_HTTP_GZIP_STATIC_OFF) { return NGX_DECLINED; } if (gzcf->enable == NGX_HTTP_GZIP_STATIC_ON) { rc = ngx_http_gzip_ok(r); } else { /* always */ rc = NGX_OK; } clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module); if (!clcf->gzip_vary && rc != NGX_OK) { return NGX_DECLINED; } log = r->connection->log; p = ngx_http_map_uri_to_path(r, &path, &root, sizeof(".gz") - 1); if (p == NULL) { return NGX_HTTP_INTERNAL_SERVER_ERROR; } *p++ = '.'; *p++ = 'g'; *p++ = 'z'; *p = '\0'; path.len = p - path.data; ngx_log_debug1(NGX_LOG_DEBUG_HTTP, log, 0, "http filename: \"%s\"", path.data); ngx_memzero(&of, sizeof(ngx_open_file_info_t)); of.read_ahead = clcf->read_ahead; of.directio = clcf->directio; of.valid = clcf->open_file_cache_valid; of.min_uses = clcf->open_file_cache_min_uses; of.errors = clcf->open_file_cache_errors; of.events = clcf->open_file_cache_events; if (ngx_http_set_disable_symlinks(r, clcf, &path, &of) != NGX_OK) { return NGX_HTTP_INTERNAL_SERVER_ERROR; } if (ngx_open_cached_file(clcf->open_file_cache, &path, &of, r->pool) != NGX_OK) { switch (of.err) { case 0: return NGX_HTTP_INTERNAL_SERVER_ERROR; case NGX_ENOENT: case NGX_ENOTDIR: case NGX_ENAMETOOLONG: return NGX_DECLINED; case NGX_EACCES: #if (NGX_HAVE_OPENAT) case NGX_EMLINK: case NGX_ELOOP: #endif level = NGX_LOG_ERR; break; default: level = NGX_LOG_CRIT; break; } ngx_log_error(level, log, of.err, "%s \"%s\" failed", of.failed, path.data); return NGX_DECLINED; } if (gzcf->enable == NGX_HTTP_GZIP_STATIC_ON) { r->gzip_vary = 1; if (rc != NGX_OK) { return NGX_DECLINED; } } ngx_log_debug1(NGX_LOG_DEBUG_HTTP, log, 0, "http static fd: %d", of.fd); if (of.is_dir) { ngx_log_debug0(NGX_LOG_DEBUG_HTTP, log, 0, "http dir"); return NGX_DECLINED; } #if !(NGX_WIN32) /* the not regular files are probably Unix specific */ if (!of.is_file) { ngx_log_error(NGX_LOG_CRIT, log, 0, "\"%s\" is not a regular file", path.data); return NGX_HTTP_NOT_FOUND; } #endif r->root_tested = !r->error_page; rc = ngx_http_discard_request_body(r); if (rc != NGX_OK) { return rc; } log->action = "sending response to client"; r->headers_out.status = NGX_HTTP_OK; r->headers_out.content_length_n = of.size; r->headers_out.last_modified_time = of.mtime; if (ngx_http_set_etag(r) != NGX_OK) { return NGX_HTTP_INTERNAL_SERVER_ERROR; } if (ngx_http_set_content_type(r) != NGX_OK) { return NGX_HTTP_INTERNAL_SERVER_ERROR; } h = ngx_list_push(&r->headers_out.headers); if (h == NULL) { return NGX_ERROR; } h->hash = 1; ngx_str_set(&h->key, "Content-Encoding"); ngx_str_set(&h->value, "gzip"); r->headers_out.content_encoding = h; /* we need to allocate all before the header would be sent */ b = ngx_pcalloc(r->pool, sizeof(ngx_buf_t)); if (b == NULL) { return NGX_HTTP_INTERNAL_SERVER_ERROR; } b->file = ngx_pcalloc(r->pool, sizeof(ngx_file_t)); if (b->file == NULL) { return NGX_HTTP_INTERNAL_SERVER_ERROR; } rc = ngx_http_send_header(r); if (rc == NGX_ERROR || rc > NGX_OK || r->header_only) { return rc; } b->file_pos = 0; b->file_last = of.size; b->in_file = b->file_last ? 1 : 0; b->last_buf = (r == r->main) ? 1 : 0; b->last_in_chain = 1; b->file->fd = of.fd; b->file->name = path; b->file->log = log; b->file->directio = of.is_directio; out.buf = b; out.next = NULL; return ngx_http_output_filter(r, &out); } static void * ngx_http_gzip_static_create_conf(ngx_conf_t *cf) { ngx_http_gzip_static_conf_t *conf; conf = ngx_palloc(cf->pool, sizeof(ngx_http_gzip_static_conf_t)); if (conf == NULL) { return NULL; } conf->enable = NGX_CONF_UNSET_UINT; return conf; } static char * ngx_http_gzip_static_merge_conf(ngx_conf_t *cf, void *parent, void *child) { ngx_http_gzip_static_conf_t *prev = parent; ngx_http_gzip_static_conf_t *conf = child; ngx_conf_merge_uint_value(conf->enable, prev->enable, NGX_HTTP_GZIP_STATIC_OFF); return NGX_CONF_OK; } static ngx_int_t ngx_http_gzip_static_init(ngx_conf_t *cf) { ngx_http_handler_pt *h; ngx_http_core_main_conf_t *cmcf; cmcf = ngx_http_conf_get_module_main_conf(cf, ngx_http_core_module); h = ngx_array_push(&cmcf->phases[NGX_HTTP_CONTENT_PHASE].handlers); if (h == NULL) { return NGX_ERROR; } *h = ngx_http_gzip_static_handler; return NGX_OK; }
goby/nginx-releases
src/http/modules/ngx_http_gzip_static_module.c
C
bsd-2-clause
8,456
class Id3lib < Formula homepage 'http://id3lib.sourceforge.net/' stable do url 'https://downloads.sourceforge.net/project/id3lib/id3lib/3.8.3/id3lib-3.8.3.tar.gz' sha1 'c92c880da41d1ec0b242745a901702ae87970838' patch do url "https://trac.macports.org/export/112431/trunk/dports/audio/id3lib/files/id3lib-vbr-overflow.patch" sha1 "2fc0d348469980b30d7844dad63cac91ccd421c9" end patch do url "https://trac.macports.org/export/90780/trunk/dports/audio/id3lib/files/id3lib-main.patch" sha1 "8e52e21bd37fcd57bfaa8b1a8c11bf897d73a476" end end head ":pserver:anonymous:@id3lib.cvs.sourceforge.net:/cvsroot/id3lib", :using => :cvs, :module => "id3lib-devel" bottle do cellar :any revision 1 sha1 "ccb2a5ec637f99a36996920c1bbd9d284bb91958" => :yosemite sha1 "9db89ba6ca30f1ae05d7af44ad6ba82931a88c42" => :mavericks end depends_on 'autoconf' => :build depends_on 'automake' => :build depends_on 'libtool' => :build patch do url "https://trac.macports.org/export/112430/trunk/dports/audio/id3lib/files/no-iomanip.h.patch" sha1 "d4d782608cf038fbd1adcf5d08324a9d1c49bc38" end patch do url "https://trac.macports.org/export/112430/trunk/dports/audio/id3lib/files/automake.patch" sha1 "86a83a2e993ccc2bb23a32837ec996d3a959a9a1" end patch do url "https://trac.macports.org/export/112430/trunk/dports/audio/id3lib/files/boolcheck.patch" sha1 "55a4db02c74825157ef5df62f10ed8c4173e7dc7" end fails_with :llvm do build 2326 cause "Segfault during linking" end def install system "autoreconf -fi" system "./configure", "--disable-debug", "--disable-dependency-tracking", "--prefix=#{prefix}" system "make install" end end
benesch/homebrew
Library/Formula/id3lib.rb
Ruby
bsd-2-clause
1,786
class OpenMpi < Formula desc "High performance message passing library" homepage "https://www.open-mpi.org/" url "https://www.open-mpi.org/software/ompi/v1.10/downloads/openmpi-1.10.0.tar.bz2" sha256 "26b432ce8dcbad250a9787402f2c999ecb6c25695b00c9c6ee05a306c78b6490" bottle do sha256 "0db613a1d46fee336d4ff73fea321a258831898c75ed21fb9b7a04428488a864" => :el_capitan sha256 "27b7652c76a14b6cc2587963a7b90384844cbc52e947569f24bee71697447b37" => :yosemite sha256 "8db6160f29874dac3705f5c18a3cb9e62e0b36c8beaed70b72dc4aeda642d1c8" => :mavericks sha256 "823851cf8e01825899d97dc1766dc1c44eb11f5cc1a3a25b60b5c087c35ec81d" => :mountain_lion end head do url "https://github.com/open-mpi/ompi.git" depends_on "automake" => :build depends_on "autoconf" => :build depends_on "libtool" => :build end deprecated_option "disable-fortran" => "without-fortran" deprecated_option "enable-mpi-thread-multiple" => "with-mpi-thread-multiple" option "with-mpi-thread-multiple", "Enable MPI_THREAD_MULTIPLE" option :cxx11 conflicts_with "mpich", :because => "both install mpi__ compiler wrappers" conflicts_with "lcdf-typetools", :because => "both install same set of binaries." depends_on :java => :build depends_on :fortran => :recommended depends_on "libevent" def install ENV.cxx11 if build.cxx11? args = %W[ --prefix=#{prefix} --disable-dependency-tracking --disable-silent-rules --enable-ipv6 --with-libevent=#{Formula["libevent"].opt_prefix} --with-sge ] args << "--disable-mpi-fortran" if build.without? "fortran" args << "--enable-mpi-thread-multiple" if build.with? "mpi-thread-multiple" system "./autogen.pl" if build.head? system "./configure", *args system "make", "all" system "make", "check" system "make", "install" # If Fortran bindings were built, there will be stray `.mod` files # (Fortran header) in `lib` that need to be moved to `include`. include.install Dir["#{lib}/*.mod"] if build.stable? # Move vtsetup.jar from bin to libexec. libexec.install bin/"vtsetup.jar" inreplace bin/"vtsetup", "$bindir/vtsetup.jar", "$prefix/libexec/vtsetup.jar" end end test do (testpath/"hello.c").write <<-EOS.undent #include <mpi.h> #include <stdio.h> int main() { int size, rank, nameLen; char name[MPI_MAX_PROCESSOR_NAME]; MPI_Init(NULL, NULL); MPI_Comm_size(MPI_COMM_WORLD, &size); MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Get_processor_name(name, &nameLen); printf("[%d/%d] Hello, world! My name is %s.\\n", rank, size, name); MPI_Finalize(); return 0; } EOS system "#{bin}/mpicc", "hello.c", "-o", "hello" system "./hello" system "#{bin}/mpirun", "-np", "4", "./hello" end end
theckman/homebrew
Library/Formula/open-mpi.rb
Ruby
bsd-2-clause
2,892
class Zorba < Formula desc "NoSQL query processor" homepage "http://www.zorba.io/" url "https://github.com/28msec/zorba/archive/3.0.tar.gz" sha256 "75661fed35fb143498ba6539314a21e0e2b0cc18c4eaa5782d488430ac4dd9c8" revision 2 bottle do sha256 "db15418a3274cf4aeb35937e230ce97698182ddfde37807f16c035c8a5135ca0" => :el_capitan sha256 "32c0d43f093d70c672cd5aff4c0f5e5e4fe401c88db84e7cea78793a3871a7ba" => :yosemite sha256 "434987a856a507071999d743d5cef45693a4c2a0f905f0d52489ada70183e558" => :mavericks end option "with-big-integer", "Use 64 bit precision instead of arbitrary precision for performance" option "with-ssl-verification", "Enable SSL peer certificate verification" depends_on :macos => :mavericks depends_on "cmake" => :build depends_on "swig" => [:build, :recommended] depends_on "flex" depends_on "icu4c" depends_on "xerces-c" needs :cxx11 def install ENV.cxx11 args = std_cmake_args args << "-DZORBA_VERIFY_PEER_SSL_CERTIFICATE=ON" if build.with? "ssl-verification" args << "-DZORBA_WITH_BIG_INTEGER=ON" if build.with? "big-integer" # https://github.com/Homebrew/homebrew/issues/42372 # Seems to be an assumption `/usr/include/php` will exist without an obvious # override to that logic. args << "-DZORBA_SUPPRESS_SWIG=ON" if !MacOS::CLT.installed? || build.without?("swig") mkdir "build" do system "cmake", "..", *args system "make", "install" end end test do assert_equal shell_output("#{bin}/zorba -q 1+1").strip, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n2" end end
knpwrs/homebrew
Library/Formula/zorba.rb
Ruby
bsd-2-clause
1,620
/* * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2010 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * FCKRemoveFormatCommand Class: controls the execution of a core style. Core * styles are usually represented as buttons in the toolbar., like Bold and * Italic. */ var FCKRemoveFormatCommand = function() { this.Name = 'RemoveFormat' ; } FCKRemoveFormatCommand.prototype = { Execute : function() { FCKStyles.RemoveAll() ; FCK.Focus() ; FCK.Events.FireEvent( 'OnSelectionChange' ) ; }, GetState : function() { return FCK.EditorWindow ? FCK_TRISTATE_OFF : FCK_TRISTATE_DISABLED ; } };
NYPL/SummerReading.org
all/modules/fckeditor/fckeditor/editor/_source/commandclasses/fckremoveformatcommand.js
JavaScript
bsd-2-clause
1,167
class Gpsim < Formula desc "Simulator for Microchip's PIC microcontrollers" homepage "http://gpsim.sourceforge.net/" url "https://downloads.sourceforge.net/project/gpsim/gpsim/0.28.0/gpsim-0.28.1.tar.gz" sha256 "d8d41fb530630e6df31db89a0ca630038395aed4d07c48859655468ed25658ed" head "svn://svn.code.sf.net/p/gpsim/code/trunk" bottle do cellar :any sha256 "78a225eb11338a6699ccdb4c23ad4c1682cfdc34f06cf2c4fbeb571b238b45c9" => :yosemite sha256 "dfdf91a9f332b9880ec59934fe661bbc0d50b45d8f7c2cdde888f31bcaac9c40" => :mavericks sha256 "2d0cc0cf61b5df08cce8f9795666228487876cfda9045be3e371b6cd15c70bee" => :mountain_lion end depends_on "pkg-config" => :build depends_on "gputils" => :build depends_on "glib" depends_on "popt" def install system "./configure", "--disable-dependency-tracking", "--disable-gui", "--disable-shared", "--prefix=#{prefix}" system "make", "all" system "make", "install" end end
emilyst/homebrew
Library/Formula/gpsim.rb
Ruby
bsd-2-clause
1,035
class Hfsutils < Formula desc "Tools for reading and writing Macintosh volumes" homepage "http://www.mars.org/home/rob/proj/hfs/" url "ftp://ftp.mars.org/pub/hfs/hfsutils-3.2.6.tar.gz" sha256 "bc9d22d6d252b920ec9cdf18e00b7655a6189b3f34f42e58d5bb152957289840" bottle do cellar :any sha256 "2d0997b77b2bc7b3a0454c552c6ebd3b24c6efc01bc9e4814781f7971c8802f9" => :yosemite sha256 "06dddcb4d540a24b63b389213724b828f99bfc7c32272be1a9e4ca4472409c93" => :mavericks sha256 "251b45cb10a8c3ea4d543cd0a843acd266e4acd01637f7f999e8221324835e19" => :mountain_lion end def install system "./configure", "--prefix=#{prefix}", "--mandir=#{man}" bin.mkpath man1.mkpath system "make", "install" end test do system "dd", "if=/dev/zero", "of=disk.hfs", "bs=1k", "count=800" system bin/"hformat", "-l", "Test Disk", "disk.hfs" output = shell_output("#{bin}/hmount disk.hfs") assert_match /^Volume name is "Test Disk"$/, output assert_match /^Volume has 803840 bytes free$/, output end end
JerroldLee/homebrew
Library/Formula/hfsutils.rb
Ruby
bsd-2-clause
1,040
require "formula" class Gammaray < Formula homepage "http://www.kdab.com/kdab-products/gammaray/" url "https://github.com/KDAB/GammaRay/archive/v2.2.0.tar.gz" sha1 "c6055ae24b67465528b1747f2ac291adcd805a8e" bottle do sha1 "07bfe7c133e5a72e116f07b5cd65e70b6e5ee00b" => :yosemite sha1 "7d1e58d5d6c9212c52445859921554c22f0f4404" => :mavericks sha1 "8f1aa69e5a27f6078f3fe5c3c5b67f6caa931f55" => :mountain_lion end option "without-qt4", "Build against Qt5 instead of Qt4 (default)" option "with-vtk", "Build with VTK-with-Qt support, for object 3D visualizer" needs :cxx11 depends_on "cmake" => :build depends_on "qt" if build.with? "qt4" depends_on "qt5" if build.without? "qt4" depends_on "graphviz" => :recommended # VTK needs to have Qt support, and it needs to match GammaRay's depends_on "homebrew/science/vtk" => [:optional, ((build.with? "qt4") ? "with-qt" : "with-qt5")] def install args = std_cmake_args args << "-DGAMMARAY_ENFORCE_QT4_BUILD=" + ((build.with? "qt4") ? "ON" : "OFF") args << "-DCMAKE_DISABLE_FIND_PACKAGE_VTK=" + ((build.without? "vtk") ? "ON" : "OFF" ) args << "-DCMAKE_DISABLE_FIND_PACKAGE_Graphviz=" + ((build.without? "graphviz") ? "ON" : "OFF" ) mkdir "build" do system "cmake", "..", *args system "make", "install" end end test do assert_match /^qt/, %x[#{bin}/gammaray --list-probes].chomp end end
jtrag/homebrew
Library/Formula/gammaray.rb
Ruby
bsd-2-clause
1,422
class Cspice < Formula desc "Observation geometry system for robotic space science missions" homepage "https://naif.jpl.nasa.gov/naif/index.html" url "https://naif.jpl.nasa.gov/pub/naif/toolkit/C/MacIntel_OSX_AppleC_64bit/packages/cspice.tar.Z" version "65" sha256 "c009981340de17fb1d9b55e1746f32336e1a7a3ae0b4b8d68f899ecb6e96dd5d" bottle do cellar :any_skip_relocation revision 3 sha256 "daa552c39c338739c8c435d1b7c5c77975172905ff91b5893667da6ad60f7a7e" => :el_capitan sha256 "fda8c9832e01c3b51bf68981434501632083a0a88909f62b4248f63f248a5971" => :yosemite sha256 "61e4b947ed7223919ae92ddfcaf1f64267ab8d27467bcfb4de51cbdd10edbaa1" => :mavericks end conflicts_with "openhmd", :because => "both install `simple` binaries" conflicts_with "libftdi0", :because => "both install `simple` binaries" conflicts_with "enscript", :because => "both install `states` binaries" conflicts_with "fondu", :because => "both install `tobin` binaries" def install rm_f Dir["lib/*"] rm_f Dir["exe/*"] system "csh", "makeall.csh" mv "exe", "bin" pkgshare.install "doc", "data" prefix.install "bin", "include", "lib" lib.install_symlink "cspice.a" => "libcspice.a" lib.install_symlink "csupport.a" => "libcsupport.a" end test do system "#{bin}/tobin", "#{pkgshare}/data/cook_01.tsp", "DELME" end end
osimola/homebrew
Library/Formula/cspice.rb
Ruby
bsd-2-clause
1,368