text
stringlengths
2
1.04M
meta
dict
using System; using System.Collections.Generic; using System.Threading.Tasks; using Dommel.IntegrationTests; using Xunit; namespace Dommel.Json.IntegrationTests; [Collection("JSON Database")] public class InsertTests { [Theory] [ClassData(typeof(JsonDatabaseTestData))] public void InsertsNullObject(DatabaseDriver database) { using var con = database.GetConnection(); var id = con.Insert(new Lead { Email = "foo@example.com", Data = null!, }); var lead = con.Get<Lead>(id); Assert.NotNull(lead); Assert.Null(lead!.Data); } [Theory] [ClassData(typeof(JsonDatabaseTestData))] public async Task InsertsNullObjectAsync(DatabaseDriver database) { using var con = database.GetConnection(); var id = await con.InsertAsync(new Lead { Email = "foo@example.com", Data = null!, }); var lead = await con.GetAsync<Lead>(id); Assert.NotNull(lead); Assert.Null(lead!.Data); } [Theory] [ClassData(typeof(JsonDatabaseTestData))] public void InsertsEmptyJsonObject(DatabaseDriver database) { using var con = database.GetConnection(); var id = con.Insert(new Lead { Email = "foo@example.com", Data = new LeadData(), }); var lead = con.Get<Lead>(id); Assert.NotNull(lead); Assert.NotNull(lead!.Data); Assert.Null(lead.Data?.FirstName); } [Theory] [ClassData(typeof(JsonDatabaseTestData))] public async Task InsertsEmptyJsonObjectAsync(DatabaseDriver database) { using var con = database.GetConnection(); var id = await con.InsertAsync(new Lead { Email = "foo@example.com", Data = new LeadData(), }); var lead = await con.GetAsync<Lead>(id); Assert.NotNull(lead); Assert.NotNull(lead!.Data); Assert.Null(lead.Data?.FirstName); } [Theory] [ClassData(typeof(JsonDatabaseTestData))] public void InsertsJsonObject(DatabaseDriver database) { using var con = database.GetConnection(); var id = con.Insert(new Lead { Email = "foo@example.com", Data = new LeadData { FirstName = "Foo", LastName = "Bar", Birthdate = new DateTime(1985, 7, 1), Email = "foo@example.com", } }); var lead = con.Get<Lead>(id); Assert.NotNull(lead); Assert.NotNull(lead!.Data); Assert.NotNull(lead.Data?.FirstName); } [Theory] [ClassData(typeof(JsonDatabaseTestData))] public async Task InsertsJsonObjectAsync(DatabaseDriver database) { using var con = database.GetConnection(); var id = await con.InsertAsync(new Lead { Email = "foo@example.com", Data = new LeadData { FirstName = "Foo", LastName = "Bar", Birthdate = new DateTime(1985, 7, 1), Email = "foo@example.com", } }); var lead = await con.GetAsync<Lead>(id); Assert.NotNull(lead); Assert.NotNull(lead!.Data); Assert.NotNull(lead.Data?.FirstName); } [Theory] [ClassData(typeof(JsonDatabaseTestData))] public void InsertsDictionary(DatabaseDriver database) { using var con = database.GetConnection(); var id = con.Insert(new Lead { Email = "foo@example.com", Metadata = new Dictionary<string, string> { ["Foo"] = "Bar", ["DateModified"] = DateTime.UtcNow.ToString(), } }); var lead = con.Get<Lead>(id); Assert.NotNull(lead); Assert.NotNull(lead!.Metadata); Assert.Equal("Bar", Assert.Contains("Foo", lead.Metadata)); Assert.Contains("DateModified", lead.Metadata); } [Theory] [ClassData(typeof(JsonDatabaseTestData))] public async Task InsertsDictionaryAsync(DatabaseDriver database) { using var con = database.GetConnection(); var id = await con.InsertAsync(new Lead { Email = "foo@example.com", Metadata = new Dictionary<string, string> { ["Foo"] = "Bar", ["DateModified"] = DateTime.UtcNow.ToString(), } }); var lead = await con.GetAsync<Lead>(id); Assert.NotNull(lead); Assert.NotNull(lead!.Metadata); Assert.Equal("Bar", Assert.Contains("Foo", lead.Metadata)); Assert.Contains("DateModified", lead.Metadata); } }
{ "content_hash": "8285241b286a038b5f06fec963980c27", "timestamp": "", "source": "github", "line_count": 167, "max_line_length": 74, "avg_line_length": 28.7125748502994, "alnum_prop": 0.5607924921793535, "repo_name": "henkmollema/Dommel", "id": "7e15c45f774365196216b2a1e9943c5ab71559bc", "size": "4797", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/Dommel.Json.IntegrationTests/InsertTests.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "404" }, { "name": "C#", "bytes": "490359" }, { "name": "PowerShell", "bytes": "3180" } ], "symlink_target": "" }
from unittest import TestCase import klineyes from klineyes.util.test_data import load_test_data class TestEyes(TestCase): def test_get_dates_pattern(self): ''' testing :return: ''' klineyes.get_dates_pattern(input_data=load_test_data(), ptypes=['hammer', 'line', 'star'])
{ "content_hash": "070a93e5a7085313ab7669a68f3fceb9", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 98, "avg_line_length": 22.857142857142858, "alnum_prop": 0.64375, "repo_name": "tenstone/klineyes", "id": "fb3fd86292dca0483f7cd4c678cca8ff70d6b9ec", "size": "320", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/test_klineyes.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "16279" } ], "symlink_target": "" }
' Copyright (c) 2015 ZZZ Projects. All rights reserved ' Licensed under MIT License (MIT) (https://github.com/zzzprojects/Z.ExtensionMethods) ' Website: http://www.zzzprojects.com/ ' Feedback / Feature Requests / Issues : http://zzzprojects.uservoice.com/forums/283927 ' All ZZZ Projects products: Entity Framework Extensions / Bulk Operations / Extension Methods /Icon Library Imports System.Net Public Module Extensions_264 ''' <summary> ''' Converts a short value from network byte order to host byte order. ''' </summary> ''' <param name="network">The number to convert, expressed in network byte order.</param> ''' <returns>A short value, expressed in host byte order.</returns> <System.Runtime.CompilerServices.Extension> _ Public Function NetworkToHostOrder(network As Int16) As Int16 Return IPAddress.NetworkToHostOrder(network) End Function End Module
{ "content_hash": "f7722e407418c604fa85d9405ecd6c28", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 108, "avg_line_length": 40, "alnum_prop": 0.7602272727272728, "repo_name": "mario-loza/Z.ExtensionMethods", "id": "06c8b49cbe22f8bd9458034f15a407285f489b1b", "size": "881", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src (VB.NET)/Z.ExtensionMethods.VB/Z.Core/System.Int16/System.Net.IPAddress/Int16.NetworkToHostOrder.vb", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "2220012" }, { "name": "Visual Basic", "bytes": "1418004" } ], "symlink_target": "" }
using Microsoft.AspNetCore.Html; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; namespace NonFactors.Mvc.Grid { public static class GridExtensions { public static HtmlGrid<T> Grid<T>(this IHtmlHelper html, IEnumerable<T> source) where T : class { return new HtmlGrid<T>(html, new Grid<T>(source)); } public static HtmlGrid<T> Grid<T>(this IHtmlHelper html, String partialViewName, IEnumerable<T> source) where T : class { return new HtmlGrid<T>(html, new Grid<T>(source)) { PartialViewName = partialViewName }; } public static IHtmlContent AjaxGrid(this IHtmlHelper _, String url, Object? htmlAttributes = null) { TagBuilder grid = new TagBuilder("div"); grid.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes)); grid.Attributes["data-url"] = url; grid.AddCssClass("mvc-grid"); return grid; } public static IServiceCollection AddMvcGrid(this IServiceCollection services, Action<GridFilters>? configure = null) { GridFilters filters = new GridFilters(); configure?.Invoke(filters); return services.AddSingleton<IGridFilters>(filters); } } }
{ "content_hash": "608c7e87dc6afb8365d8e7305b3df6ae", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 127, "avg_line_length": 36.76923076923077, "alnum_prop": 0.6645746164574616, "repo_name": "NonFactors/MVC6.Grid", "id": "c0ce3c95676665f292554152ca09a6eef50700b8", "size": "1436", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/Mvc.Grid.Core/Html/GridExtensions.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "261290" }, { "name": "CSS", "bytes": "7665" }, { "name": "HTML", "bytes": "9850" }, { "name": "JavaScript", "bytes": "37253" } ], "symlink_target": "" }
package com.github.aleksandermielczarek.realmrepository.configuration; import io.realm.Realm; /** * Created by Aleksander Mielczarek on 22.09.2016. */ public interface RealmProvider { Realm provideRealm(); }
{ "content_hash": "3c098d6a4416d90ce73afe3f06cb5be2", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 70, "avg_line_length": 18.166666666666668, "alnum_prop": 0.7614678899082569, "repo_name": "AleksanderMielczarek/RealmRepository", "id": "6398c02bf14a8d1f26a464c3506abc2aa663176c", "size": "218", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "realmrepository/src/main/java/com/github/aleksandermielczarek/realmrepository/configuration/RealmProvider.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "101781" } ], "symlink_target": "" }
[[ -z "${BASH_SOURCE}" ]] && echo "Cannot locate self." && exit 1 cd "${BASH_SOURCE%/*}" echo 'cleaning old generated code...' rm -rf ./clients/* rm -rf ./commands/* echo 'building client generator...' go get google.golang.org/api/google-api-go-generator echo 'building gcloud_apis_gen...' go get ./gcloud_apis_gen || exit 1 echo 'generating command source for gcloud_apis...' gcloud_apis_gen --discovery-dir ./discovery_docs --clients-dir ./clients --commands-dir ./commands || exit
{ "content_hash": "227b0fce0c175c9ccf0e56b944691a1c", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 106, "avg_line_length": 40.416666666666664, "alnum_prop": 0.6907216494845361, "repo_name": "mbrukman/gcloud", "id": "201807d86ff16e6f8000ee0aed2726632a5705d4", "size": "498", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "gcloud_apis/gen.bash", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "2232806" }, { "name": "Shell", "bytes": "498" } ], "symlink_target": "" }
""" Wind Turbine Company - 2013 Author: Stephan Rayner Email: stephan.rayner@gmail.com """ from HIL.controller.Base_Controller import Base_Controller from Yaw_Generation import Yaw_Generation Yaw_Generation = Yaw_Generation() class Yaw_Manual(Base_Controller): """docstring for Yaw_Manual""" def __init__(self): super(Yaw_Manual, self).__init__() self.controler = "mcc" self.readVariable = ['@GV.DO_YawPin1', '@GV.DO_YawPin2'] self.writeVariable = ["@GV.HWB_YawDriveCWDemand", "@GV.HWB_YawDriveCCWDemand"] def write(self, direction): assert(direction in ["cw", "ccw", "clockwise", "counterclockwise"]) if(direction in["cw", "clockwise"]): self.mcc.raw_write(self.mccip, self.writeVariable[0], "1") self.mcc.raw_write(self.mccip, self.writeVariable[1], "0") pass else: self.mcc.raw_write(self.mccip, self.writeVariable[0], "0") self.mcc.raw_write(self.mccip, self.writeVariable[1], "1") def read(self): self.generation = Yaw_Generation.read() [Temp1, Temp2] = self.mcc.read(self.readVariable).items() Yaw_Pins = [Temp1[1], Temp2[1]] if self.generation == '1': if Yaw_Pins == ['1', '0']: return 'counterclockwise' elif Yaw_Pins == ['0', '1']: return 'clockwise' else: return 'Neither counterclockwise nor clockwise' if self.generation == '2': if Yaw_Pins == ['1', '1']: return 'clockwise' elif Yaw_Pins == ['1', '0']: return 'counterclockwise' else: return 'Neither counterclockwise nor clockwise' def reset(self): for variable in self.writeVariable: self.mcc.raw_write(self.mccip, variable, '0') def help(self): return "Help string for Yaw_Manual"
{ "content_hash": "0b171d2649f2e76555a047e566c2e3da", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 86, "avg_line_length": 36.39622641509434, "alnum_prop": 0.5759460860549508, "repo_name": "stephan-rayner/HIL-TestStation", "id": "bc96c7d3608c6635bf6269b3bc13c8fc9a6121a2", "size": "1929", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "HIL/controller/e3120/Yaw_Manual.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "95483" } ], "symlink_target": "" }
import { Template } from 'meteor/templating'; import { t, roomTypes } from '../../utils/client'; import { settings } from '../../settings/client'; import { Rooms } from '../../models/client'; import { callbacks } from '../../callbacks/client'; Template.chatRoomItem.helpers({ roomData() { const unread = this.unread > 0 ? this.unread : false; // if (this.unread > 0 && (!hasFocus || openedRoom !== this.rid)) { // unread = this.unread; // } const roomType = roomTypes.getConfig(this.t); const archivedClass = this.archived ? 'archived' : false; const room = Rooms.findOne(this.rid); const icon = roomTypes.getIcon(this.t === 'd' ? room : this); const roomData = { ...this, icon: icon !== 'at' && icon, avatar: roomTypes.getConfig(this.t).getAvatarPath(room || this), username: this.name, route: roomTypes.getRouteLink(this.t, this), name: roomType.roomName(this), unread, active: false, archivedClass, status: this.t === 'd' || this.t === 'l', isGroupChat: roomType.isGroupChat(room), }; roomData.username = roomData.username || roomData.name; if (!this.lastMessage && settings.get('Store_Last_Message')) { const room = Rooms.findOne(this.rid || this._id, { fields: { lastMessage: 1 } }); roomData.lastMessage = (room && room.lastMessage) || { msg: t('No_messages_yet') }; } return roomData; }, }); callbacks.add('enter-room', (sub) => { const items = $('.rooms-list .sidebar-item'); items.filter('.sidebar-item--active').removeClass('sidebar-item--active'); if (sub) { items.filter(`[data-id=${ sub._id }]`).addClass('sidebar-item--active'); } return sub; });
{ "content_hash": "2a9f6e46c8a0b2cbb6359270f2cd8fe6", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 86, "avg_line_length": 31.07547169811321, "alnum_prop": 0.6363084395871281, "repo_name": "subesokun/Rocket.Chat", "id": "45d7a5c8555c22a1e569d01638a8de503c6e6d4b", "size": "1647", "binary": false, "copies": "3", "ref": "refs/heads/develop", "path": "app/ui-sidenav/client/chatRoomItem.js", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "549" }, { "name": "CSS", "bytes": "397150" }, { "name": "Cap'n Proto", "bytes": "3960" }, { "name": "CoffeeScript", "bytes": "30843" }, { "name": "Dockerfile", "bytes": "1874" }, { "name": "HTML", "bytes": "443704" }, { "name": "JavaScript", "bytes": "4470036" }, { "name": "Ruby", "bytes": "4653" }, { "name": "Shell", "bytes": "32549" }, { "name": "Standard ML", "bytes": "1843" } ], "symlink_target": "" }
using namespace std; using namespace ngraph; constexpr NodeTypeInfo pattern::op::Or::type_info; const NodeTypeInfo& pattern::op::Or::get_type_info() const { return type_info; } bool pattern::op::Or::match_value(Matcher* matcher, const Output<Node>& pattern_value, const Output<Node>& graph_value) { for (auto input_value : input_values()) { auto saved = matcher->start_match(); if (matcher->match_value(input_value, graph_value)) { return saved.finish(true); } } return false; }
{ "content_hash": "08f9909be231b0c4a83999358d9db404", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 68, "avg_line_length": 25.583333333333332, "alnum_prop": 0.5716612377850163, "repo_name": "NervanaSystems/ngraph", "id": "f43d3b469ba4a9448d65933fdc557e71914ac329", "size": "1449", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/ngraph/pattern/op/or.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "3147" }, { "name": "C++", "bytes": "19522833" }, { "name": "CMake", "bytes": "223605" }, { "name": "Dockerfile", "bytes": "2036" }, { "name": "Groovy", "bytes": "13002" }, { "name": "MLIR", "bytes": "55258" }, { "name": "Makefile", "bytes": "13532" }, { "name": "Python", "bytes": "331191" }, { "name": "Shell", "bytes": "43252" } ], "symlink_target": "" }
$(document).ready(function(){ /** Show error message */ function show_error(message){ console.error(message); if(PNotify){ $(function(){ new PNotify({ title: 'Error', text: message, type: 'error', desktop: { desktop: true } }); }); } } /* Payment */ $(".pay_button").click(function(event){ $(".pay_button").attr("disabled", true); $(".pay_button").addClass("disabled"); var $this = $(this); var url = vpos_constants["SET_PAYMENT_ATTRIBUTES_URL"]; var $form = $(this).parents("form"); var post = { payment_code: vpos_constants["PAYMENT_CODE"], url_ok: vpos_constants["URL_OK"], url_nok: vpos_constants["URL_NOK"], vpos_id: $(this).data("id") }; // Reference number if($this.data("reference_number")){ post["reference_number"] = $this.data("reference_number"); } // Evitar que se pueda pulsar más de una vez sobre el botón if(this.clicked){ event.preventDefault(); return; } else{ this.clicked = true; } $this.addClass("waiting"); $.post(url, post, function(data){ var $input; if("status" in data && data["status"]=="error"){ show_error("Unable to create an operation number"); return false; } var formdata = data['data']; // Assignment of each attribute generated by server $form.attr({ "action": data['action'], "method": data['method'] }); if(data['enctype']){ $form.attr("enctype", data['enctype']); } for (name in formdata) { $input = $('<input type="hidden" />'); $input.attr("name", name).val(formdata[name]); $form.append($input); } $form.submit(); return false; }); return false; }); });
{ "content_hash": "4c9787e3bccb2a64e090f1729aa38fe5", "timestamp": "", "source": "github", "line_count": 88, "max_line_length": 64, "avg_line_length": 19.5, "alnum_prop": 0.5769230769230769, "repo_name": "intelligenia/django-virtual-pos", "id": "21e4c59d3d809442c4ca12b5993371c762d0ce8f", "size": "1718", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "djangovirtualpos/static/js/djangovirtualpos/payment/set_payment_attributes.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "518" }, { "name": "JavaScript", "bytes": "1718" }, { "name": "Python", "bytes": "232980" } ], "symlink_target": "" }
/* ! * Vue.js v2.4.0 * (c) 2014-2017 Evan You * Released under the MIT License. */ (function(global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.Vue = factory()); }(this, function() { 'use strict'; /* */ // these helpers produces better vm code in JS engines due to their // explicitness and function inlining function isUndef(v) { return v === undefined || v === null; } function isDef(v) { return v !== undefined && v !== null; } function isTrue(v) { return v === true; } function isFalse(v) { return v === false; } /** * Check if value is primitive */ function isPrimitive(value) { return typeof value === 'string' || typeof value === 'number'; } /** * Quick object check - this is primarily used to tell * Objects from primitive values when we know the value * is a JSON-compliant type. */ function isObject(obj) { return obj !== null && typeof obj === 'object'; } const _toString = Object.prototype.toString; /** * Strict object type check. Only returns true * for plain JavaScript objects. */ function isPlainObject(obj) { return _toString.call(obj) === '[object Object]'; } function isRegExp(v) { return _toString.call(v) === '[object RegExp]'; } /** * Check if val is a valid array index. */ function isValidArrayIndex(val) { const n = parseFloat(val); return n >= 0 && Math.floor(n) === n && isFinite(val); } /** * Convert a value to a string that is actually rendered. */ function toString(val) { return val == null ? '' : typeof val === 'object' ? JSON.stringify(val, null, 2) : String(val); } /** * Convert a input value to a number for persistence. * If the conversion fails, return original string. */ function toNumber(val) { const n = parseFloat(val); return isNaN(n) ? val : n; } /** * Make a map and return a function for checking if a key * is in that map. */ function makeMap( str, expectsLowerCase ) { const map = Object.create(null); const list = str.split(','); for (let i = 0; i < list.length; i++) { map[list[i]] = true; } return expectsLowerCase ? function(val) { return map[val.toLowerCase()]; } : function(val) { return map[val]; }; } /** * Check if a tag is a built-in tag. */ const isBuiltInTag = makeMap('slot,component', true); /** * Check if a attribute is a reserved attribute. */ const isReservedAttribute = makeMap('key,ref,slot,is'); /** * Remove an item from an array */ function remove(arr, item) { if (arr.length) { const index = arr.indexOf(item); if (index > -1) { return arr.splice(index, 1); } } } /** * Check whether the object has the property. */ const hasOwnProperty = Object.prototype.hasOwnProperty; function hasOwn(obj, key) { return hasOwnProperty.call(obj, key); } /** * Create a cached version of a pure function. */ function cached(fn) { const cache = Object.create(null); return function cachedFn(str) { const hit = cache[str]; return hit || (cache[str] = fn(str)); }; } /** * Camelize a hyphen-delimited string. */ const camelizeRE = /-(\w)/g; const camelize = cached(function(str) { return str.replace(camelizeRE, function(_, c) { return c ? c.toUpperCase() : ''; }); }); /** * Capitalize a string. */ const capitalize = cached(function(str) { return str.charAt(0).toUpperCase() + str.slice(1); }); /** * Hyphenate a camelCase string. */ const hyphenateRE = /([^-])([A-Z])/g; const hyphenate = cached(function(str) { return str .replace(hyphenateRE, '$1-$2') .replace(hyphenateRE, '$1-$2') .toLowerCase(); }); /** * Simple bind, faster than native */ function bind(fn, ctx) { function boundFn(a) { const l = arguments.length; return l ? l > 1 ? fn.apply(ctx, arguments) : fn.call(ctx, a) : fn.call(ctx); } // record original fn length boundFn._length = fn.length; return boundFn; } /** * Convert an Array-like object to a real Array. */ function toArray(list, start) { start = start || 0; let i = list.length - start; const ret = new Array(i); while (i--) { ret[i] = list[i + start]; } return ret; } /** * Mix properties into target object. */ function extend(to, _from) { for (const key in _from) { to[key] = _from[key]; } return to; } /** * Merge an Array of Objects into a single Object. */ function toObject(arr) { const res = {}; for (let i = 0; i < arr.length; i++) { if (arr[i]) { extend(res, arr[i]); } } return res; } /** * Perform no operation. * Stubbing args to make Flow happy without leaving useless transpiled code * with ...rest (https://flow.org/blog/2017/05/07/Strict-Function-Call-Arity/) */ function noop(a, b, c) {} /** * Always return false. */ const no = function(a, b, c) { return false; }; /** * Return same value */ const identity = function(_) { return _; }; /** * Generate a static keys string from compiler modules. */ function genStaticKeys(modules) { return modules.reduce(function(keys, m) { return keys.concat(m.staticKeys || []); }, []).join(','); } /** * Check if two values are loosely equal - that is, * if they are plain objects, do they have the same shape? */ function looseEqual(a, b) { const isObjectA = isObject(a); const isObjectB = isObject(b); if (isObjectA && isObjectB) { try { return JSON.stringify(a) === JSON.stringify(b); } catch (e) { // possible circular reference return a === b; } } else if (!isObjectA && !isObjectB) { return String(a) === String(b); } else { return false; } } function looseIndexOf(arr, val) { for (let i = 0; i < arr.length; i++) { if (looseEqual(arr[i], val)) { return i; } } return -1; } /** * Ensure a function is called only once. */ function once(fn) { let called = false; return function() { if (!called) { called = true; fn.apply(this, arguments); } }; } const SSR_ATTR = 'data-server-rendered'; const ASSET_TYPES = [ 'component', 'directive', 'filter', ]; const LIFECYCLE_HOOKS = [ 'beforeCreate', 'created', 'beforeMount', 'mounted', 'beforeUpdate', 'updated', 'beforeDestroy', 'destroyed', 'activated', 'deactivated', ]; /* */ const config = ({ /** * Option merge strategies (used in core/util/options) */ optionMergeStrategies: Object.create(null), /** * Whether to suppress warnings. */ silent: false, /** * Show production mode tip message on boot? */ productionTip: 'development' !== 'production', /** * Whether to enable devtools */ devtools: 'development' !== 'production', /** * Whether to record perf */ performance: false, /** * Error handler for watcher errors */ errorHandler: null, /** * Warn handler for watcher warns */ warnHandler: null, /** * Ignore certain custom elements */ ignoredElements: [], /** * Custom user key aliases for v-on */ keyCodes: Object.create(null), /** * Check if a tag is reserved so that it cannot be registered as a * component. This is platform-dependent and may be overwritten. */ isReservedTag: no, /** * Check if an attribute is reserved so that it cannot be used as a component * prop. This is platform-dependent and may be overwritten. */ isReservedAttr: no, /** * Check if a tag is an unknown element. * Platform-dependent. */ isUnknownElement: no, /** * Get the namespace of an element */ getTagNamespace: noop, /** * Parse the real tag name for the specific platform. */ parsePlatformTagName: identity, /** * Check if an attribute must be bound using property, e.g. value * Platform-dependent. */ mustUseProp: no, /** * Exposed for legacy reasons */ _lifecycleHooks: LIFECYCLE_HOOKS, }); /* */ const emptyObject = Object.freeze({}); /** * Check if a string starts with $ or _ */ function isReserved(str) { const c = (str + '').charCodeAt(0); return c === 0x24 || c === 0x5F; } /** * Define a property. */ function def(obj, key, val, enumerable) { Object.defineProperty(obj, key, { value: val, enumerable: !!enumerable, writable: true, configurable: true, }); } /** * Parse simple path. */ const bailRE = /[^\w.$]/; function parsePath(path) { if (bailRE.test(path)) { return; } const segments = path.split('.'); return function(obj) { for (let i = 0; i < segments.length; i++) { if (!obj) { return; } obj = obj[segments[i]]; } return obj; }; } /* */ let warn = noop; let tip = noop; let formatComponentName = (null); // work around flow check { const hasConsole = typeof console !== 'undefined'; const classifyRE = /(?:^|[-_])(\w)/g; const classify = function(str) { return str .replace(classifyRE, function(c) { return c.toUpperCase(); }) .replace(/[-_]/g, ''); }; warn = function(msg, vm) { const trace = vm ? generateComponentTrace(vm) : ''; if (config.warnHandler) { config.warnHandler.call(null, msg, vm, trace); } else if (hasConsole && (!config.silent)) { console.error(('[Vue warn]: ' + msg + trace)); } }; tip = function(msg, vm) { if (hasConsole && (!config.silent)) { console.warn('[Vue tip]: ' + msg + ( vm ? generateComponentTrace(vm) : '' )); } }; formatComponentName = function(vm, includeFile) { if (vm.$root === vm) { return '<Root>'; } let name = typeof vm === 'string' ? vm : typeof vm === 'function' && vm.options ? vm.options.name : vm._isVue ? vm.$options.name || vm.$options._componentTag : vm.name; const file = vm._isVue && vm.$options.__file; if (!name && file) { const match = file.match(/([^/\\]+)\.vue$/); name = match && match[1]; } return ( (name ? ('<' + (classify(name)) + '>') : '<Anonymous>') + (file && includeFile !== false ? (' at ' + file) : '') ); }; const repeat = function(str, n) { let res = ''; while (n) { if (n % 2 === 1) { res += str; } if (n > 1) { str += str; } n >>= 1; } return res; }; var generateComponentTrace = function(vm) { if (vm._isVue && vm.$parent) { const tree = []; let currentRecursiveSequence = 0; while (vm) { if (tree.length > 0) { const last = tree[tree.length - 1]; if (last.constructor === vm.constructor) { currentRecursiveSequence++; vm = vm.$parent; continue; } else if (currentRecursiveSequence > 0) { tree[tree.length - 1] = [ last, currentRecursiveSequence ]; currentRecursiveSequence = 0; } } tree.push(vm); vm = vm.$parent; } return '\n\nfound in\n\n' + tree .map(function(vm, i) { return ('' + (i === 0 ? '---> ' : repeat(' ', 5 + i * 2)) + (Array.isArray(vm) ? ((formatComponentName(vm[0])) + '... (' + (vm[1]) + ' recursive calls)') : formatComponentName(vm))); }) .join('\n'); } return ('\n\n(found in ' + (formatComponentName(vm)) + ')'); }; } /* */ function handleError(err, vm, info) { if (config.errorHandler) { config.errorHandler.call(null, err, vm, info); } else { { warn(('Error in ' + info + ': "' + (err.toString()) + '"'), vm); } /* istanbul ignore else */ if (inBrowser && typeof console !== 'undefined') { console.error(err); } else { throw err; } } } /* */ /* globals MutationObserver */ // can we use __proto__? const hasProto = '__proto__' in {}; // Browser environment sniffing var inBrowser = typeof window !== 'undefined'; const UA = inBrowser && window.navigator.userAgent.toLowerCase(); const isIE = UA && /msie|trident/.test(UA); const isIE9 = UA && UA.indexOf('msie 9.0') > 0; const isEdge = UA && UA.indexOf('edge/') > 0; const isAndroid = UA && UA.indexOf('android') > 0; const isIOS = UA && /iphone|ipad|ipod|ios/.test(UA); const isChrome = UA && /chrome\/\d+/.test(UA) && !isEdge; // Firefix has a "watch" function on Object.prototype... const nativeWatch = ({}).watch; let supportsPassive = false; if (inBrowser) { try { const opts = {}; Object.defineProperty(opts, 'passive', ({ get: function get() { /* istanbul ignore next */ supportsPassive = true; }, })); // https://github.com/facebook/flow/issues/285 window.addEventListener('test-passive', null, opts); } catch (e) {} } // this needs to be lazy-evaled because vue may be required before // vue-server-renderer can set VUE_ENV let _isServer; const isServerRendering = function() { if (_isServer === undefined) { /* istanbul ignore if */ if (!inBrowser && typeof global !== 'undefined') { // detect presence of vue-server-renderer and avoid // Webpack shimming the process _isServer = global.process.env.VUE_ENV === 'server'; } else { _isServer = false; } } return _isServer; }; // detect devtools const devtools = inBrowser && window.__VUE_DEVTOOLS_GLOBAL_HOOK__; /* istanbul ignore next */ function isNative(Ctor) { return typeof Ctor === 'function' && /native code/.test(Ctor.toString()); } const hasSymbol = typeof Symbol !== 'undefined' && isNative(Symbol) && typeof Reflect !== 'undefined' && isNative(Reflect.ownKeys); /** * Defer a task to execute it asynchronously. */ const nextTick = (function() { const callbacks = []; let pending = false; let timerFunc; function nextTickHandler() { pending = false; const copies = callbacks.slice(0); callbacks.length = 0; for (let i = 0; i < copies.length; i++) { copies[i](); } } // the nextTick behavior leverages the microtask queue, which can be accessed // via either native Promise.then or MutationObserver. // MutationObserver has wider support, however it is seriously bugged in // UIWebView in iOS >= 9.3.3 when triggered in touch event handlers. It // completely stops working after triggering a few times... so, if native // Promise is available, we will use it: /* istanbul ignore if */ if (typeof Promise !== 'undefined' && isNative(Promise)) { const p = Promise.resolve(); const logError = function(err) { console.error(err); }; timerFunc = function() { p.then(nextTickHandler).catch(logError); // in problematic UIWebViews, Promise.then doesn't completely break, but // it can get stuck in a weird state where callbacks are pushed into the // microtask queue but the queue isn't being flushed, until the browser // needs to do some other work, e.g. handle a timer. Therefore we can // "force" the microtask queue to be flushed by adding an empty timer. if (isIOS) { setTimeout(noop); } }; } else if (typeof MutationObserver !== 'undefined' && ( isNative(MutationObserver) || // PhantomJS and iOS 7.x MutationObserver.toString() === '[object MutationObserverConstructor]' )) { // use MutationObserver where native Promise is not available, // e.g. PhantomJS IE11, iOS7, Android 4.4 let counter = 1; const observer = new MutationObserver(nextTickHandler); const textNode = document.createTextNode(String(counter)); observer.observe(textNode, { characterData: true, }); timerFunc = function() { counter = (counter + 1) % 2; textNode.data = String(counter); }; } else { // fallback to setTimeout /* istanbul ignore next */ timerFunc = function() { setTimeout(nextTickHandler, 0); }; } return function queueNextTick(cb, ctx) { let _resolve; callbacks.push(function() { if (cb) { try { cb.call(ctx); } catch (e) { handleError(e, ctx, 'nextTick'); } } else if (_resolve) { _resolve(ctx); } }); if (!pending) { pending = true; timerFunc(); } if (!cb && typeof Promise !== 'undefined') { return new Promise(function(resolve, reject) { _resolve = resolve; }); } }; })(); let _Set; /* istanbul ignore if */ if (typeof Set !== 'undefined' && isNative(Set)) { // use native Set when available. _Set = Set; } else { // a non-standard Set polyfill that only works with primitive keys. _Set = (function() { function Set() { this.set = Object.create(null); } Set.prototype.has = function has(key) { return this.set[key] === true; }; Set.prototype.add = function add(key) { this.set[key] = true; }; Set.prototype.clear = function clear() { this.set = Object.create(null); }; return Set; }()); } /* */ let uid = 0; /** * A dep is an observable that can have multiple * directives subscribing to it. */ const Dep = function Dep() { this.id = uid++; this.subs = []; }; Dep.prototype.addSub = function addSub(sub) { this.subs.push(sub); }; Dep.prototype.removeSub = function removeSub(sub) { remove(this.subs, sub); }; Dep.prototype.depend = function depend() { if (Dep.target) { Dep.target.addDep(this); } }; Dep.prototype.notify = function notify() { // stabilize the subscriber list first const subs = this.subs.slice(); for (let i = 0, l = subs.length; i < l; i++) { subs[i].update(); } }; // the current target watcher being evaluated. // this is globally unique because there could be only one // watcher being evaluated at any time. Dep.target = null; const targetStack = []; function pushTarget(_target) { if (Dep.target) { targetStack.push(Dep.target); } Dep.target = _target; } function popTarget() { Dep.target = targetStack.pop(); } /* * not type checking this file because flow doesn't play well with * dynamically accessing methods on Array prototype */ const arrayProto = Array.prototype; const arrayMethods = Object.create(arrayProto); [ 'push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse', ] .forEach(function(method) { // cache original method const original = arrayProto[method]; def(arrayMethods, method, function mutator() { let args = [], len = arguments.length; while (len--) args[len] = arguments[len]; const result = original.apply(this, args); const ob = this.__ob__; let inserted; switch (method) { case 'push': case 'unshift': inserted = args; break; case 'splice': inserted = args.slice(2); break; } if (inserted) { ob.observeArray(inserted); } // notify change ob.dep.notify(); return result; }); }); /* */ const arrayKeys = Object.getOwnPropertyNames(arrayMethods); /** * By default, when a reactive property is set, the new value is * also converted to become reactive. However when passing down props, * we don't want to force conversion because the value may be a nested value * under a frozen data structure. Converting it would defeat the optimization. */ const observerState = { shouldConvert: true, }; /** * Observer class that are attached to each observed * object. Once attached, the observer converts target * object's property keys into getter/setters that * collect dependencies and dispatches updates. */ const Observer = function Observer(value) { this.value = value; this.dep = new Dep(); this.vmCount = 0; def(value, '__ob__', this); if (Array.isArray(value)) { const augment = hasProto ? protoAugment : copyAugment; augment(value, arrayMethods, arrayKeys); this.observeArray(value); } else { this.walk(value); } }; /** * Walk through each property and convert them into * getter/setters. This method should only be called when * value type is Object. */ Observer.prototype.walk = function walk(obj) { const keys = Object.keys(obj); for (let i = 0; i < keys.length; i++) { defineReactive$$1(obj, keys[i], obj[keys[i]]); } }; /** * Observe a list of Array items. */ Observer.prototype.observeArray = function observeArray(items) { for (let i = 0, l = items.length; i < l; i++) { observe(items[i]); } }; // helpers /** * Augment an target Object or Array by intercepting * the prototype chain using __proto__ */ function protoAugment(target, src, keys) { /* eslint-disable no-proto */ target.__proto__ = src; /* eslint-enable no-proto */ } /** * Augment an target Object or Array by defining * hidden properties. */ /* istanbul ignore next */ function copyAugment(target, src, keys) { for (let i = 0, l = keys.length; i < l; i++) { const key = keys[i]; def(target, key, src[key]); } } /** * Attempt to create an observer instance for a value, * returns the new observer if successfully observed, * or the existing observer if the value already has one. */ function observe(value, asRootData) { if (!isObject(value)) { return; } let ob; if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) { ob = value.__ob__; } else if ( observerState.shouldConvert && !isServerRendering() && (Array.isArray(value) || isPlainObject(value)) && Object.isExtensible(value) && !value._isVue ) { ob = new Observer(value); } if (asRootData && ob) { ob.vmCount++; } return ob; } /** * Define a reactive property on an Object. */ function defineReactive$$1( obj, key, val, customSetter, shallow ) { const dep = new Dep(); const property = Object.getOwnPropertyDescriptor(obj, key); if (property && property.configurable === false) { return; } // cater for pre-defined getter/setters const getter = property && property.get; const setter = property && property.set; let childOb = !shallow && observe(val); Object.defineProperty(obj, key, { enumerable: true, configurable: true, get: function reactiveGetter() { const value = getter ? getter.call(obj) : val; if (Dep.target) { dep.depend(); if (childOb) { childOb.dep.depend(); } if (Array.isArray(value)) { dependArray(value); } } return value; }, set: function reactiveSetter(newVal) { const value = getter ? getter.call(obj) : val; /* eslint-disable no-self-compare */ if (newVal === value || (newVal !== newVal && value !== value)) { return; } /* eslint-enable no-self-compare */ if ('development' !== 'production' && customSetter) { customSetter(); } if (setter) { setter.call(obj, newVal); } else { val = newVal; } childOb = !shallow && observe(newVal); dep.notify(); }, }); } /** * Set a property on an object. Adds the new property and * triggers change notification if the property doesn't * already exist. */ function set(target, key, val) { if (Array.isArray(target) && isValidArrayIndex(key)) { target.length = Math.max(target.length, key); target.splice(key, 1, val); return val; } if (hasOwn(target, key)) { target[key] = val; return val; } const ob = (target).__ob__; if (target._isVue || (ob && ob.vmCount)) { 'development' !== 'production' && warn( 'Avoid adding reactive properties to a Vue instance or its root $data ' + 'at runtime - declare it upfront in the data option.' ); return val; } if (!ob) { target[key] = val; return val; } defineReactive$$1(ob.value, key, val); ob.dep.notify(); return val; } /** * Delete a property and trigger change if necessary. */ function del(target, key) { if (Array.isArray(target) && isValidArrayIndex(key)) { target.splice(key, 1); return; } const ob = (target).__ob__; if (target._isVue || (ob && ob.vmCount)) { 'development' !== 'production' && warn( 'Avoid deleting properties on a Vue instance or its root $data ' + '- just set it to null.' ); return; } if (!hasOwn(target, key)) { return; } delete target[key]; if (!ob) { return; } ob.dep.notify(); } /** * Collect dependencies on array elements when the array is touched, since * we cannot intercept array element access like property getters. */ function dependArray(value) { for (let e = (void 0), i = 0, l = value.length; i < l; i++) { e = value[i]; e && e.__ob__ && e.__ob__.dep.depend(); if (Array.isArray(e)) { dependArray(e); } } } /* */ /** * Option overwriting strategies are functions that handle * how to merge a parent option value and a child option * value into the final value. */ const strats = config.optionMergeStrategies; /** * Options with restrictions */ { strats.el = strats.propsData = function(parent, child, vm, key) { if (!vm) { warn( 'option "' + key + '" can only be used during instance ' + 'creation with the `new` keyword.' ); } return defaultStrat(parent, child); }; } /** * Helper that recursively merges two data objects together. */ function mergeData(to, from) { if (!from) { return to; } let key, toVal, fromVal; const keys = Object.keys(from); for (let i = 0; i < keys.length; i++) { key = keys[i]; toVal = to[key]; fromVal = from[key]; if (!hasOwn(to, key)) { set(to, key, fromVal); } else if (isPlainObject(toVal) && isPlainObject(fromVal)) { mergeData(toVal, fromVal); } } return to; } /** * Data */ function mergeDataOrFn( parentVal, childVal, vm ) { if (!vm) { // in a Vue.extend merge, both should be functions if (!childVal) { return parentVal; } if (!parentVal) { return childVal; } // when parentVal & childVal are both present, // we need to return a function that returns the // merged result of both functions... no need to // check if parentVal is a function here because // it has to be a function to pass previous merges. return function mergedDataFn() { return mergeData( typeof childVal === 'function' ? childVal.call(this) : childVal, parentVal.call(this) ); }; } else if (parentVal || childVal) { return function mergedInstanceDataFn() { // instance merge const instanceData = typeof childVal === 'function' ? childVal.call(vm) : childVal; const defaultData = typeof parentVal === 'function' ? parentVal.call(vm) : undefined; if (instanceData) { return mergeData(instanceData, defaultData); } return defaultData; }; } } strats.data = function( parentVal, childVal, vm ) { if (!vm) { if (childVal && typeof childVal !== 'function') { 'development' !== 'production' && warn( 'The "data" option should be a function ' + 'that returns a per-instance value in component ' + 'definitions.', vm ); return parentVal; } return mergeDataOrFn.call(this, parentVal, childVal); } return mergeDataOrFn(parentVal, childVal, vm); }; /** * Hooks and props are merged as arrays. */ function mergeHook( parentVal, childVal ) { return childVal ? parentVal ? parentVal.concat(childVal) : Array.isArray(childVal) ? childVal : [ childVal ] : parentVal; } LIFECYCLE_HOOKS.forEach(function(hook) { strats[hook] = mergeHook; }); /** * Assets * * When a vm is present (instance creation), we need to do * a three-way merge between constructor options, instance * options and parent options. */ function mergeAssets(parentVal, childVal) { const res = Object.create(parentVal || null); return childVal ? extend(res, childVal) : res; } ASSET_TYPES.forEach(function(type) { strats[type + 's'] = mergeAssets; }); /** * Watchers. * * Watchers hashes should not overwrite one * another, so we merge them as arrays. */ strats.watch = function(parentVal, childVal) { // work around Firefox's Object.prototype.watch... if (parentVal === nativeWatch) { parentVal = undefined; } if (childVal === nativeWatch) { childVal = undefined; } /* istanbul ignore if */ if (!childVal) { return Object.create(parentVal || null); } if (!parentVal) { return childVal; } const ret = {}; extend(ret, parentVal); for (const key in childVal) { let parent = ret[key]; const child = childVal[key]; if (parent && !Array.isArray(parent)) { parent = [ parent ]; } ret[key] = parent ? parent.concat(child) : Array.isArray(child) ? child : [ child ]; } return ret; }; /** * Other object hashes. */ strats.props = strats.methods = strats.inject = strats.computed = function(parentVal, childVal) { if (!childVal) { return Object.create(parentVal || null); } if (!parentVal) { return childVal; } const ret = Object.create(null); extend(ret, parentVal); extend(ret, childVal); return ret; }; strats.provide = mergeDataOrFn; /** * Default strategy. */ var defaultStrat = function(parentVal, childVal) { return childVal === undefined ? parentVal : childVal; }; /** * Validate component names */ function checkComponents(options) { for (const key in options.components) { const lower = key.toLowerCase(); if (isBuiltInTag(lower) || config.isReservedTag(lower)) { warn( 'Do not use built-in or reserved HTML elements as component ' + 'id: ' + key ); } } } /** * Ensure all props option syntax are normalized into the * Object-based format. */ function normalizeProps(options) { const props = options.props; if (!props) { return; } const res = {}; let i, val, name; if (Array.isArray(props)) { i = props.length; while (i--) { val = props[i]; if (typeof val === 'string') { name = camelize(val); res[name] = { type: null, }; } else { warn('props must be strings when using array syntax.'); } } } else if (isPlainObject(props)) { for (const key in props) { val = props[key]; name = camelize(key); res[name] = isPlainObject(val) ? val : { type: val, }; } } options.props = res; } /** * Normalize all injections into Object-based format */ function normalizeInject(options) { const inject = options.inject; if (Array.isArray(inject)) { const normalized = options.inject = {}; for (let i = 0; i < inject.length; i++) { normalized[inject[i]] = inject[i]; } } } /** * Normalize raw function directives into object format. */ function normalizeDirectives(options) { const dirs = options.directives; if (dirs) { for (const key in dirs) { const def = dirs[key]; if (typeof def === 'function') { dirs[key] = { bind: def, update: def, }; } } } } /** * Merge two option objects into a new one. * Core utility used in both instantiation and inheritance. */ function mergeOptions( parent, child, vm ) { { checkComponents(child); } if (typeof child === 'function') { child = child.options; } normalizeProps(child); normalizeInject(child); normalizeDirectives(child); const extendsFrom = child.extends; if (extendsFrom) { parent = mergeOptions(parent, extendsFrom, vm); } if (child.mixins) { for (let i = 0, l = child.mixins.length; i < l; i++) { parent = mergeOptions(parent, child.mixins[i], vm); } } const options = {}; let key; for (key in parent) { mergeField(key); } for (key in child) { if (!hasOwn(parent, key)) { mergeField(key); } } function mergeField(key) { const strat = strats[key] || defaultStrat; options[key] = strat(parent[key], child[key], vm, key); } return options; } /** * Resolve an asset. * This function is used because child instances need access * to assets defined in its ancestor chain. */ function resolveAsset( options, type, id, warnMissing ) { /* istanbul ignore if */ if (typeof id !== 'string') { return; } const assets = options[type]; // check local registration variations first if (hasOwn(assets, id)) { return assets[id]; } const camelizedId = camelize(id); if (hasOwn(assets, camelizedId)) { return assets[camelizedId]; } const PascalCaseId = capitalize(camelizedId); if (hasOwn(assets, PascalCaseId)) { return assets[PascalCaseId]; } // fallback to prototype chain const res = assets[id] || assets[camelizedId] || assets[PascalCaseId]; if ('development' !== 'production' && warnMissing && !res) { warn( 'Failed to resolve ' + type.slice(0, -1) + ': ' + id, options ); } return res; } /* */ function validateProp( key, propOptions, propsData, vm ) { const prop = propOptions[key]; const absent = !hasOwn(propsData, key); let value = propsData[key]; // handle boolean props if (isType(Boolean, prop.type)) { if (absent && !hasOwn(prop, 'default')) { value = false; } else if (!isType(String, prop.type) && (value === '' || value === hyphenate(key))) { value = true; } } // check default value if (value === undefined) { value = getPropDefaultValue(vm, prop, key); // since the default value is a fresh copy, // make sure to observe it. const prevShouldConvert = observerState.shouldConvert; observerState.shouldConvert = true; observe(value); observerState.shouldConvert = prevShouldConvert; } { assertProp(prop, key, value, vm, absent); } return value; } /** * Get the default value of a prop. */ function getPropDefaultValue(vm, prop, key) { // no default, return undefined if (!hasOwn(prop, 'default')) { return undefined; } const def = prop.default; // warn against non-factory defaults for Object & Array if ('development' !== 'production' && isObject(def)) { warn( 'Invalid default value for prop "' + key + '": ' + 'Props with type Object/Array must use a factory function ' + 'to return the default value.', vm ); } // the raw prop value was also undefined from previous render, // return previous default value to avoid unnecessary watcher trigger if (vm && vm.$options.propsData && vm.$options.propsData[key] === undefined && vm._props[key] !== undefined ) { return vm._props[key]; } // call factory function for non-Function types // a value is Function if its prototype is function even across different execution context return typeof def === 'function' && getType(prop.type) !== 'Function' ? def.call(vm) : def; } /** * Assert whether a prop is valid. */ function assertProp( prop, name, value, vm, absent ) { if (prop.required && absent) { warn( 'Missing required prop: "' + name + '"', vm ); return; } if (value == null && !prop.required) { return; } let type = prop.type; let valid = !type || type === true; const expectedTypes = []; if (type) { if (!Array.isArray(type)) { type = [ type ]; } for (let i = 0; i < type.length && !valid; i++) { const assertedType = assertType(value, type[i]); expectedTypes.push(assertedType.expectedType || ''); valid = assertedType.valid; } } if (!valid) { warn( 'Invalid prop: type check failed for prop "' + name + '".' + ' Expected ' + expectedTypes.map(capitalize).join(', ') + ', got ' + Object.prototype.toString.call(value).slice(8, -1) + '.', vm ); return; } const validator = prop.validator; if (validator) { if (!validator(value)) { warn( 'Invalid prop: custom validator check failed for prop "' + name + '".', vm ); } } } const simpleCheckRE = /^(String|Number|Boolean|Function|Symbol)$/; function assertType(value, type) { let valid; const expectedType = getType(type); if (simpleCheckRE.test(expectedType)) { valid = typeof value === expectedType.toLowerCase(); } else if (expectedType === 'Object') { valid = isPlainObject(value); } else if (expectedType === 'Array') { valid = Array.isArray(value); } else { valid = value instanceof type; } return { valid, expectedType, }; } /** * Use function string name to check built-in types, * because a simple equality check will fail when running * across different vms / iframes. */ function getType(fn) { const match = fn && fn.toString().match(/^\s*function (\w+)/); return match ? match[1] : ''; } function isType(type, fn) { if (!Array.isArray(fn)) { return getType(fn) === getType(type); } for (let i = 0, len = fn.length; i < len; i++) { if (getType(fn[i]) === getType(type)) { return true; } } /* istanbul ignore next */ return false; } /* */ let mark; let measure; { const perf = inBrowser && window.performance; /* istanbul ignore if */ if ( perf && perf.mark && perf.measure && perf.clearMarks && perf.clearMeasures ) { mark = function(tag) { return perf.mark(tag); }; measure = function(name, startTag, endTag) { perf.measure(name, startTag, endTag); perf.clearMarks(startTag); perf.clearMarks(endTag); perf.clearMeasures(name); }; } } /* not type checking this file because flow doesn't play well with Proxy */ let initProxy; { const allowedGlobals = makeMap( 'Infinity,undefined,NaN,isFinite,isNaN,' + 'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' + 'Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,' + 'require' // for Webpack/Browserify ); const warnNonPresent = function(target, key) { warn( 'Property or method "' + key + '" is not defined on the instance but ' + 'referenced during render. Make sure to declare reactive data ' + 'properties in the data option.', target ); }; const hasProxy = typeof Proxy !== 'undefined' && Proxy.toString().match(/native code/); if (hasProxy) { const isBuiltInModifier = makeMap('stop,prevent,self,ctrl,shift,alt,meta'); config.keyCodes = new Proxy(config.keyCodes, { set: function set(target, key, value) { if (isBuiltInModifier(key)) { warn(('Avoid overwriting built-in modifier in config.keyCodes: .' + key)); return false; } target[key] = value; return true; }, }); } const hasHandler = { has: function has(target, key) { const has = key in target; const isAllowed = allowedGlobals(key) || key.charAt(0) === '_'; if (!has && !isAllowed) { warnNonPresent(target, key); } return has || !isAllowed; }, }; const getHandler = { get: function get(target, key) { if (typeof key === 'string' && !(key in target)) { warnNonPresent(target, key); } return target[key]; }, }; initProxy = function initProxy(vm) { if (hasProxy) { // determine which proxy handler to use const options = vm.$options; const handlers = options.render && options.render._withStripped ? getHandler : hasHandler; vm._renderProxy = new Proxy(vm, handlers); } else { vm._renderProxy = vm; } }; } /* */ const VNode = function VNode( tag, data, children, text, elm, context, componentOptions, asyncFactory ) { this.tag = tag; this.data = data; this.children = children; this.text = text; this.elm = elm; this.ns = undefined; this.context = context; this.functionalContext = undefined; this.key = data && data.key; this.componentOptions = componentOptions; this.componentInstance = undefined; this.parent = undefined; this.raw = false; this.isStatic = false; this.isRootInsert = true; this.isComment = false; this.isCloned = false; this.isOnce = false; this.asyncFactory = asyncFactory; this.asyncMeta = undefined; this.isAsyncPlaceholder = false; }; const prototypeAccessors = { child: {}, }; // DEPRECATED: alias for componentInstance for backwards compat. /* istanbul ignore next */ prototypeAccessors.child.get = function() { return this.componentInstance; }; Object.defineProperties(VNode.prototype, prototypeAccessors); const createEmptyVNode = function(text) { if (text === void 0) text = ''; const node = new VNode(); node.text = text; node.isComment = true; return node; }; function createTextVNode(val) { return new VNode(undefined, undefined, undefined, String(val)); } // optimized shallow clone // used for static nodes and slot nodes because they may be reused across // multiple renders, cloning them avoids errors when DOM manipulations rely // on their elm reference. function cloneVNode(vnode) { const cloned = new VNode( vnode.tag, vnode.data, vnode.children, vnode.text, vnode.elm, vnode.context, vnode.componentOptions, vnode.asyncFactory ); cloned.ns = vnode.ns; cloned.isStatic = vnode.isStatic; cloned.key = vnode.key; cloned.isComment = vnode.isComment; cloned.isCloned = true; return cloned; } function cloneVNodes(vnodes) { const len = vnodes.length; const res = new Array(len); for (let i = 0; i < len; i++) { res[i] = cloneVNode(vnodes[i]); } return res; } /* */ const normalizeEvent = cached(function(name) { const passive = name.charAt(0) === '&'; name = passive ? name.slice(1) : name; const once$$1 = name.charAt(0) === '~'; // Prefixed last, checked first name = once$$1 ? name.slice(1) : name; const capture = name.charAt(0) === '!'; name = capture ? name.slice(1) : name; return { name, once: once$$1, capture, passive, }; }); function createFnInvoker(fns) { function invoker() { const arguments$1 = arguments; const fns = invoker.fns; if (Array.isArray(fns)) { const cloned = fns.slice(); for (let i = 0; i < cloned.length; i++) { cloned[i].apply(null, arguments$1); } } else { // return handler return value for single handlers return fns.apply(null, arguments); } } invoker.fns = fns; return invoker; } function updateListeners( on, oldOn, add, remove$$1, vm ) { let name, cur, old, event; for (name in on) { cur = on[name]; old = oldOn[name]; event = normalizeEvent(name); if (isUndef(cur)) { 'development' !== 'production' && warn( 'Invalid handler for event "' + (event.name) + '": got ' + String(cur), vm ); } else if (isUndef(old)) { if (isUndef(cur.fns)) { cur = on[name] = createFnInvoker(cur); } add(event.name, cur, event.once, event.capture, event.passive); } else if (cur !== old) { old.fns = cur; on[name] = old; } } for (name in oldOn) { if (isUndef(on[name])) { event = normalizeEvent(name); remove$$1(event.name, oldOn[name], event.capture); } } } /* */ function mergeVNodeHook(def, hookKey, hook) { let invoker; const oldHook = def[hookKey]; function wrappedHook() { hook.apply(this, arguments); // important: remove merged hook to ensure it's called only once // and prevent memory leak remove(invoker.fns, wrappedHook); } if (isUndef(oldHook)) { // no existing hook invoker = createFnInvoker([ wrappedHook ]); } else { /* istanbul ignore if */ if (isDef(oldHook.fns) && isTrue(oldHook.merged)) { // already a merged invoker invoker = oldHook; invoker.fns.push(wrappedHook); } else { // existing plain hook invoker = createFnInvoker([ oldHook, wrappedHook ]); } } invoker.merged = true; def[hookKey] = invoker; } /* */ function extractPropsFromVNodeData( data, Ctor, tag ) { // we are only extracting raw values here. // validation and default values are handled in the child // component itself. const propOptions = Ctor.options.props; if (isUndef(propOptions)) { return; } const res = {}; const attrs = data.attrs; const props = data.props; if (isDef(attrs) || isDef(props)) { for (const key in propOptions) { const altKey = hyphenate(key); { const keyInLowerCase = key.toLowerCase(); if ( key !== keyInLowerCase && attrs && hasOwn(attrs, keyInLowerCase) ) { tip( 'Prop "' + keyInLowerCase + '" is passed to component ' + (formatComponentName(tag || Ctor)) + ', but the declared prop name is' + ' "' + key + '". ' + 'Note that HTML attributes are case-insensitive and camelCased ' + 'props need to use their kebab-case equivalents when using in-DOM ' + 'templates. You should probably use "' + altKey + '" instead of "' + key + '".' ); } } checkProp(res, props, key, altKey, true) || checkProp(res, attrs, key, altKey, false); } } return res; } function checkProp( res, hash, key, altKey, preserve ) { if (isDef(hash)) { if (hasOwn(hash, key)) { res[key] = hash[key]; if (!preserve) { delete hash[key]; } return true; } else if (hasOwn(hash, altKey)) { res[key] = hash[altKey]; if (!preserve) { delete hash[altKey]; } return true; } } return false; } /* */ // The template compiler attempts to minimize the need for normalization by // statically analyzing the template at compile time. // // For plain HTML markup, normalization can be completely skipped because the // generated render function is guaranteed to return Array<VNode>. There are // two cases where extra normalization is needed: // 1. When the children contains components - because a functional component // may return an Array instead of a single root. In this case, just a simple // normalization is needed - if any child is an Array, we flatten the whole // thing with Array.prototype.concat. It is guaranteed to be only 1-level deep // because functional components already normalize their own children. function simpleNormalizeChildren(children) { for (let i = 0; i < children.length; i++) { if (Array.isArray(children[i])) { return Array.prototype.concat.apply([], children); } } return children; } // 2. When the children contains constructs that always generated nested Arrays, // e.g. <template>, <slot>, v-for, or when the children is provided by user // with hand-written render functions / JSX. In such cases a full normalization // is needed to cater to all possible types of children values. function normalizeChildren(children) { return isPrimitive(children) ? [ createTextVNode(children) ] : Array.isArray(children) ? normalizeArrayChildren(children) : undefined; } function isTextNode(node) { return isDef(node) && isDef(node.text) && isFalse(node.isComment); } function normalizeArrayChildren(children, nestedIndex) { const res = []; let i, c, last; for (i = 0; i < children.length; i++) { c = children[i]; if (isUndef(c) || typeof c === 'boolean') { continue; } last = res[res.length - 1]; // nested if (Array.isArray(c)) { res.push.apply(res, normalizeArrayChildren(c, ((nestedIndex || '') + '_' + i))); } else if (isPrimitive(c)) { if (isTextNode(last)) { // merge adjacent text nodes // this is necessary for SSR hydration because text nodes are // essentially merged when rendered to HTML strings (last).text += String(c); } else if (c !== '') { // convert primitive to vnode res.push(createTextVNode(c)); } } else { if (isTextNode(c) && isTextNode(last)) { // merge adjacent text nodes res[res.length - 1] = createTextVNode(last.text + c.text); } else { // default key for nested array children (likely generated by v-for) if (isTrue(children._isVList) && isDef(c.tag) && isUndef(c.key) && isDef(nestedIndex)) { c.key = '__vlist' + nestedIndex + '_' + i + '__'; } res.push(c); } } } return res; } /* */ function ensureCtor(comp, base) { if (comp.__esModule && comp.default) { comp = comp.default; } return isObject(comp) ? base.extend(comp) : comp; } function createAsyncPlaceholder( factory, data, context, children, tag ) { const node = createEmptyVNode(); node.asyncFactory = factory; node.asyncMeta = { data, context, children, tag, }; return node; } function resolveAsyncComponent( factory, baseCtor, context ) { if (isTrue(factory.error) && isDef(factory.errorComp)) { return factory.errorComp; } if (isDef(factory.resolved)) { return factory.resolved; } if (isTrue(factory.loading) && isDef(factory.loadingComp)) { return factory.loadingComp; } if (isDef(factory.contexts)) { // already pending factory.contexts.push(context); } else { const contexts = factory.contexts = [ context ]; let sync = true; const forceRender = function() { for (let i = 0, l = contexts.length; i < l; i++) { contexts[i].$forceUpdate(); } }; const resolve = once(function(res) { // cache resolved factory.resolved = ensureCtor(res, baseCtor); // invoke callbacks only if this is not a synchronous resolve // (async resolves are shimmed as synchronous during SSR) if (!sync) { forceRender(); } }); const reject = once(function(reason) { 'development' !== 'production' && warn( 'Failed to resolve async component: ' + (String(factory)) + (reason ? ('\nReason: ' + reason) : '') ); if (isDef(factory.errorComp)) { factory.error = true; forceRender(); } }); const res = factory(resolve, reject); if (isObject(res)) { if (typeof res.then === 'function') { // () => Promise if (isUndef(factory.resolved)) { res.then(resolve, reject); } } else if (isDef(res.component) && typeof res.component.then === 'function') { res.component.then(resolve, reject); if (isDef(res.error)) { factory.errorComp = ensureCtor(res.error, baseCtor); } if (isDef(res.loading)) { factory.loadingComp = ensureCtor(res.loading, baseCtor); if (res.delay === 0) { factory.loading = true; } else { setTimeout(function() { if (isUndef(factory.resolved) && isUndef(factory.error)) { factory.loading = true; forceRender(); } }, res.delay || 200); } } if (isDef(res.timeout)) { setTimeout(function() { if (isUndef(factory.resolved)) { reject( 'timeout (' + (res.timeout) + 'ms)' ); } }, res.timeout); } } } sync = false; // return in case resolved synchronously return factory.loading ? factory.loadingComp : factory.resolved; } } /* */ function getFirstComponentChild(children) { if (Array.isArray(children)) { for (let i = 0; i < children.length; i++) { const c = children[i]; if (isDef(c) && isDef(c.componentOptions)) { return c; } } } } /* */ /* */ function initEvents(vm) { vm._events = Object.create(null); vm._hasHookEvent = false; // init parent attached events const listeners = vm.$options._parentListeners; if (listeners) { updateComponentListeners(vm, listeners); } } let target; function add(event, fn, once$$1) { if (once$$1) { target.$once(event, fn); } else { target.$on(event, fn); } } function remove$1(event, fn) { target.$off(event, fn); } function updateComponentListeners( vm, listeners, oldListeners ) { target = vm; updateListeners(listeners, oldListeners || {}, add, remove$1, vm); } function eventsMixin(Vue) { const hookRE = /^hook:/; Vue.prototype.$on = function(event, fn) { const this$1 = this; const vm = this; if (Array.isArray(event)) { for (let i = 0, l = event.length; i < l; i++) { this$1.$on(event[i], fn); } } else { (vm._events[event] || (vm._events[event] = [])).push(fn); // optimize hook:event cost by using a boolean flag marked at registration // instead of a hash lookup if (hookRE.test(event)) { vm._hasHookEvent = true; } } return vm; }; Vue.prototype.$once = function(event, fn) { const vm = this; function on() { vm.$off(event, on); fn.apply(vm, arguments); } on.fn = fn; vm.$on(event, on); return vm; }; Vue.prototype.$off = function(event, fn) { const this$1 = this; const vm = this; // all if (!arguments.length) { vm._events = Object.create(null); return vm; } // array of events if (Array.isArray(event)) { for (let i$1 = 0, l = event.length; i$1 < l; i$1++) { this$1.$off(event[i$1], fn); } return vm; } // specific event const cbs = vm._events[event]; if (!cbs) { return vm; } if (arguments.length === 1) { vm._events[event] = null; return vm; } // specific handler let cb; let i = cbs.length; while (i--) { cb = cbs[i]; if (cb === fn || cb.fn === fn) { cbs.splice(i, 1); break; } } return vm; }; Vue.prototype.$emit = function(event) { const vm = this; { const lowerCaseEvent = event.toLowerCase(); if (lowerCaseEvent !== event && vm._events[lowerCaseEvent]) { tip( 'Event "' + lowerCaseEvent + '" is emitted in component ' + (formatComponentName(vm)) + ' but the handler is registered for "' + event + '". ' + 'Note that HTML attributes are case-insensitive and you cannot use ' + 'v-on to listen to camelCase events when using in-DOM templates. ' + 'You should probably use "' + (hyphenate(event)) + '" instead of "' + event + '".' ); } } let cbs = vm._events[event]; if (cbs) { cbs = cbs.length > 1 ? toArray(cbs) : cbs; const args = toArray(arguments, 1); for (let i = 0, l = cbs.length; i < l; i++) { try { cbs[i].apply(vm, args); } catch (e) { handleError(e, vm, ('event handler for "' + event + '"')); } } } return vm; }; } /* */ /** * Runtime helper for resolving raw children VNodes into a slot object. */ function resolveSlots( children, context ) { const slots = {}; if (!children) { return slots; } const defaultSlot = []; for (let i = 0, l = children.length; i < l; i++) { const child = children[i]; // named slots should only be respected if the vnode was rendered in the // same context. if ((child.context === context || child.functionalContext === context) && child.data && child.data.slot != null ) { const name = child.data.slot; const slot = (slots[name] || (slots[name] = [])); if (child.tag === 'template') { slot.push.apply(slot, child.children); } else { slot.push(child); } } else { defaultSlot.push(child); } } // ignore whitespace if (!defaultSlot.every(isWhitespace)) { slots.default = defaultSlot; } return slots; } function isWhitespace(node) { return node.isComment || node.text === ' '; } function resolveScopedSlots( fns, // see flow/vnode res ) { res = res || {}; for (let i = 0; i < fns.length; i++) { if (Array.isArray(fns[i])) { resolveScopedSlots(fns[i], res); } else { res[fns[i].key] = fns[i].fn; } } return res; } /* */ let activeInstance = null; let isUpdatingChildComponent = false; function initLifecycle(vm) { const options = vm.$options; // locate first non-abstract parent let parent = options.parent; if (parent && !options.abstract) { while (parent.$options.abstract && parent.$parent) { parent = parent.$parent; } parent.$children.push(vm); } vm.$parent = parent; vm.$root = parent ? parent.$root : vm; vm.$children = []; vm.$refs = {}; vm._watcher = null; vm._inactive = null; vm._directInactive = false; vm._isMounted = false; vm._isDestroyed = false; vm._isBeingDestroyed = false; } function lifecycleMixin(Vue) { Vue.prototype._update = function(vnode, hydrating) { const vm = this; if (vm._isMounted) { callHook(vm, 'beforeUpdate'); } const prevEl = vm.$el; const prevVnode = vm._vnode; const prevActiveInstance = activeInstance; activeInstance = vm; vm._vnode = vnode; // Vue.prototype.__patch__ is injected in entry points // based on the rendering backend used. if (!prevVnode) { // initial render vm.$el = vm.__patch__( vm.$el, vnode, hydrating, false /* removeOnly */, vm.$options._parentElm, vm.$options._refElm ); // no need for the ref nodes after initial patch // this prevents keeping a detached DOM tree in memory (#5851) vm.$options._parentElm = vm.$options._refElm = null; } else { // updates vm.$el = vm.__patch__(prevVnode, vnode); } activeInstance = prevActiveInstance; // update __vue__ reference if (prevEl) { prevEl.__vue__ = null; } if (vm.$el) { vm.$el.__vue__ = vm; } // if parent is an HOC, update its $el as well if (vm.$vnode && vm.$parent && vm.$vnode === vm.$parent._vnode) { vm.$parent.$el = vm.$el; } // updated hook is called by the scheduler to ensure that children are // updated in a parent's updated hook. }; Vue.prototype.$forceUpdate = function() { const vm = this; if (vm._watcher) { vm._watcher.update(); } }; Vue.prototype.$destroy = function() { const vm = this; if (vm._isBeingDestroyed) { return; } callHook(vm, 'beforeDestroy'); vm._isBeingDestroyed = true; // remove self from parent const parent = vm.$parent; if (parent && !parent._isBeingDestroyed && !vm.$options.abstract) { remove(parent.$children, vm); } // teardown watchers if (vm._watcher) { vm._watcher.teardown(); } let i = vm._watchers.length; while (i--) { vm._watchers[i].teardown(); } // remove reference from data ob // frozen object may not have observer. if (vm._data.__ob__) { vm._data.__ob__.vmCount--; } // call the last hook... vm._isDestroyed = true; // invoke destroy hooks on current rendered tree vm.__patch__(vm._vnode, null); // fire destroyed hook callHook(vm, 'destroyed'); // turn off all instance listeners. vm.$off(); // remove __vue__ reference if (vm.$el) { vm.$el.__vue__ = null; } }; } function mountComponent( vm, el, hydrating ) { vm.$el = el; if (!vm.$options.render) { vm.$options.render = createEmptyVNode; { /* istanbul ignore if */ if ((vm.$options.template && vm.$options.template.charAt(0) !== '#') || vm.$options.el || el) { warn( 'You are using the runtime-only build of Vue where the template ' + 'compiler is not available. Either pre-compile the templates into ' + 'render functions, or use the compiler-included build.', vm ); } else { warn( 'Failed to mount component: template or render function not defined.', vm ); } } } callHook(vm, 'beforeMount'); let updateComponent; /* istanbul ignore if */ if ('development' !== 'production' && config.performance && mark) { updateComponent = function() { const name = vm._name; const id = vm._uid; const startTag = 'vue-perf-start:' + id; const endTag = 'vue-perf-end:' + id; mark(startTag); const vnode = vm._render(); mark(endTag); measure((name + ' render'), startTag, endTag); mark(startTag); vm._update(vnode, hydrating); mark(endTag); measure((name + ' patch'), startTag, endTag); }; } else { updateComponent = function() { vm._update(vm._render(), hydrating); }; } vm._watcher = new Watcher(vm, updateComponent, noop); hydrating = false; // manually mounted instance, call mounted on self // mounted is called for render-created child components in its inserted hook if (vm.$vnode == null) { vm._isMounted = true; callHook(vm, 'mounted'); } return vm; } function updateChildComponent( vm, propsData, listeners, parentVnode, renderChildren ) { { isUpdatingChildComponent = true; } // determine whether component has slot children // we need to do this before overwriting $options._renderChildren const hasChildren = !!( renderChildren || // has new static slots vm.$options._renderChildren || // has old static slots parentVnode.data.scopedSlots || // has new scoped slots vm.$scopedSlots !== emptyObject // has old scoped slots ); vm.$options._parentVnode = parentVnode; vm.$vnode = parentVnode; // update vm's placeholder node without re-render if (vm._vnode) { // update child tree's parent vm._vnode.parent = parentVnode; } vm.$options._renderChildren = renderChildren; // update $attrs and $listensers hash // these are also reactive so they may trigger child update if the child // used them during render vm.$attrs = parentVnode.data && parentVnode.data.attrs; vm.$listeners = listeners; // update props if (propsData && vm.$options.props) { observerState.shouldConvert = false; const props = vm._props; const propKeys = vm.$options._propKeys || []; for (let i = 0; i < propKeys.length; i++) { const key = propKeys[i]; props[key] = validateProp(key, vm.$options.props, propsData, vm); } observerState.shouldConvert = true; // keep a copy of raw propsData vm.$options.propsData = propsData; } // update listeners if (listeners) { const oldListeners = vm.$options._parentListeners; vm.$options._parentListeners = listeners; updateComponentListeners(vm, listeners, oldListeners); } // resolve slots + force update if has children if (hasChildren) { vm.$slots = resolveSlots(renderChildren, parentVnode.context); vm.$forceUpdate(); } { isUpdatingChildComponent = false; } } function isInInactiveTree(vm) { while (vm && (vm = vm.$parent)) { if (vm._inactive) { return true; } } return false; } function activateChildComponent(vm, direct) { if (direct) { vm._directInactive = false; if (isInInactiveTree(vm)) { return; } } else if (vm._directInactive) { return; } if (vm._inactive || vm._inactive === null) { vm._inactive = false; for (let i = 0; i < vm.$children.length; i++) { activateChildComponent(vm.$children[i]); } callHook(vm, 'activated'); } } function deactivateChildComponent(vm, direct) { if (direct) { vm._directInactive = true; if (isInInactiveTree(vm)) { return; } } if (!vm._inactive) { vm._inactive = true; for (let i = 0; i < vm.$children.length; i++) { deactivateChildComponent(vm.$children[i]); } callHook(vm, 'deactivated'); } } function callHook(vm, hook) { const handlers = vm.$options[hook]; if (handlers) { for (let i = 0, j = handlers.length; i < j; i++) { try { handlers[i].call(vm); } catch (e) { handleError(e, vm, (hook + ' hook')); } } } if (vm._hasHookEvent) { vm.$emit('hook:' + hook); } } /* */ const MAX_UPDATE_COUNT = 100; const queue = []; const activatedChildren = []; let has = {}; let circular = {}; let waiting = false; let flushing = false; let index = 0; /** * Reset the scheduler's state. */ function resetSchedulerState() { index = queue.length = activatedChildren.length = 0; has = {}; { circular = {}; } waiting = flushing = false; } /** * Flush both queues and run the watchers. */ function flushSchedulerQueue() { flushing = true; let watcher, id; // Sort queue before flush. // This ensures that: // 1. Components are updated from parent to child. (because parent is always // created before the child) // 2. A component's user watchers are run before its render watcher (because // user watchers are created before the render watcher) // 3. If a component is destroyed during a parent component's watcher run, // its watchers can be skipped. queue.sort(function(a, b) { return a.id - b.id; }); // do not cache length because more watchers might be pushed // as we run existing watchers for (index = 0; index < queue.length; index++) { watcher = queue[index]; id = watcher.id; has[id] = null; watcher.run(); // in dev build, check and stop circular updates. if ('development' !== 'production' && has[id] != null) { circular[id] = (circular[id] || 0) + 1; if (circular[id] > MAX_UPDATE_COUNT) { warn( 'You may have an infinite update loop ' + ( watcher.user ? ('in watcher with expression "' + (watcher.expression) + '"') : 'in a component render function.' ), watcher.vm ); break; } } } // keep copies of post queues before resetting state const activatedQueue = activatedChildren.slice(); const updatedQueue = queue.slice(); resetSchedulerState(); // call component updated and activated hooks callActivatedHooks(activatedQueue); callUpdatedHooks(updatedQueue); // devtool hook /* istanbul ignore if */ if (devtools && config.devtools) { devtools.emit('flush'); } } function callUpdatedHooks(queue) { let i = queue.length; while (i--) { const watcher = queue[i]; const vm = watcher.vm; if (vm._watcher === watcher && vm._isMounted) { callHook(vm, 'updated'); } } } /** * Queue a kept-alive component that was activated during patch. * The queue will be processed after the entire tree has been patched. */ function queueActivatedComponent(vm) { // setting _inactive to false here so that a render function can // rely on checking whether it's in an inactive tree (e.g. router-view) vm._inactive = false; activatedChildren.push(vm); } function callActivatedHooks(queue) { for (let i = 0; i < queue.length; i++) { queue[i]._inactive = true; activateChildComponent(queue[i], true /* true */); } } /** * Push a watcher into the watcher queue. * Jobs with duplicate IDs will be skipped unless it's * pushed when the queue is being flushed. */ function queueWatcher(watcher) { const id = watcher.id; if (has[id] == null) { has[id] = true; if (!flushing) { queue.push(watcher); } else { // if already flushing, splice the watcher based on its id // if already past its id, it will be run next immediately. let i = queue.length - 1; while (i > index && queue[i].id > watcher.id) { i--; } queue.splice(i + 1, 0, watcher); } // queue the flush if (!waiting) { waiting = true; nextTick(flushSchedulerQueue); } } } /* */ let uid$2 = 0; /** * A watcher parses an expression, collects dependencies, * and fires callback when the expression value changes. * This is used for both the $watch() api and directives. */ var Watcher = function Watcher( vm, expOrFn, cb, options ) { this.vm = vm; vm._watchers.push(this); // options if (options) { this.deep = !!options.deep; this.user = !!options.user; this.lazy = !!options.lazy; this.sync = !!options.sync; } else { this.deep = this.user = this.lazy = this.sync = false; } this.cb = cb; this.id = ++uid$2; // uid for batching this.active = true; this.dirty = this.lazy; // for lazy watchers this.deps = []; this.newDeps = []; this.depIds = new _Set(); this.newDepIds = new _Set(); this.expression = expOrFn.toString(); // parse expression for getter if (typeof expOrFn === 'function') { this.getter = expOrFn; } else { this.getter = parsePath(expOrFn); if (!this.getter) { this.getter = function() {}; 'development' !== 'production' && warn( 'Failed watching path: "' + expOrFn + '" ' + 'Watcher only accepts simple dot-delimited paths. ' + 'For full control, use a function instead.', vm ); } } this.value = this.lazy ? undefined : this.get(); }; /** * Evaluate the getter, and re-collect dependencies. */ Watcher.prototype.get = function get() { pushTarget(this); let value; const vm = this.vm; try { value = this.getter.call(vm, vm); } catch (e) { if (this.user) { handleError(e, vm, ('getter for watcher "' + (this.expression) + '"')); } else { throw e; } } finally { // "touch" every property so they are all tracked as // dependencies for deep watching if (this.deep) { traverse(value); } popTarget(); this.cleanupDeps(); } return value; }; /** * Add a dependency to this directive. */ Watcher.prototype.addDep = function addDep(dep) { const id = dep.id; if (!this.newDepIds.has(id)) { this.newDepIds.add(id); this.newDeps.push(dep); if (!this.depIds.has(id)) { dep.addSub(this); } } }; /** * Clean up for dependency collection. */ Watcher.prototype.cleanupDeps = function cleanupDeps() { const this$1 = this; let i = this.deps.length; while (i--) { const dep = this$1.deps[i]; if (!this$1.newDepIds.has(dep.id)) { dep.removeSub(this$1); } } let tmp = this.depIds; this.depIds = this.newDepIds; this.newDepIds = tmp; this.newDepIds.clear(); tmp = this.deps; this.deps = this.newDeps; this.newDeps = tmp; this.newDeps.length = 0; }; /** * Subscriber interface. * Will be called when a dependency changes. */ Watcher.prototype.update = function update() { /* istanbul ignore else */ if (this.lazy) { this.dirty = true; } else if (this.sync) { this.run(); } else { queueWatcher(this); } }; /** * Scheduler job interface. * Will be called by the scheduler. */ Watcher.prototype.run = function run() { if (this.active) { const value = this.get(); if ( value !== this.value || // Deep watchers and watchers on Object/Arrays should fire even // when the value is the same, because the value may // have mutated. isObject(value) || this.deep ) { // set new value const oldValue = this.value; this.value = value; if (this.user) { try { this.cb.call(this.vm, value, oldValue); } catch (e) { handleError(e, this.vm, ('callback for watcher "' + (this.expression) + '"')); } } else { this.cb.call(this.vm, value, oldValue); } } } }; /** * Evaluate the value of the watcher. * This only gets called for lazy watchers. */ Watcher.prototype.evaluate = function evaluate() { this.value = this.get(); this.dirty = false; }; /** * Depend on all deps collected by this watcher. */ Watcher.prototype.depend = function depend() { const this$1 = this; let i = this.deps.length; while (i--) { this$1.deps[i].depend(); } }; /** * Remove self from all dependencies' subscriber list. */ Watcher.prototype.teardown = function teardown() { const this$1 = this; if (this.active) { // remove self from vm's watcher list // this is a somewhat expensive operation so we skip it // if the vm is being destroyed. if (!this.vm._isBeingDestroyed) { remove(this.vm._watchers, this); } let i = this.deps.length; while (i--) { this$1.deps[i].removeSub(this$1); } this.active = false; } }; /** * Recursively traverse an object to evoke all converted * getters, so that every nested property inside the object * is collected as a "deep" dependency. */ const seenObjects = new _Set(); function traverse(val) { seenObjects.clear(); _traverse(val, seenObjects); } function _traverse(val, seen) { let i, keys; const isA = Array.isArray(val); if ((!isA && !isObject(val)) || !Object.isExtensible(val)) { return; } if (val.__ob__) { const depId = val.__ob__.dep.id; if (seen.has(depId)) { return; } seen.add(depId); } if (isA) { i = val.length; while (i--) { _traverse(val[i], seen); } } else { keys = Object.keys(val); i = keys.length; while (i--) { _traverse(val[keys[i]], seen); } } } /* */ const sharedPropertyDefinition = { enumerable: true, configurable: true, get: noop, set: noop, }; function proxy(target, sourceKey, key) { sharedPropertyDefinition.get = function proxyGetter() { return this[sourceKey][key]; }; sharedPropertyDefinition.set = function proxySetter(val) { this[sourceKey][key] = val; }; Object.defineProperty(target, key, sharedPropertyDefinition); } function initState(vm) { vm._watchers = []; const opts = vm.$options; if (opts.props) { initProps(vm, opts.props); } if (opts.methods) { initMethods(vm, opts.methods); } if (opts.data) { initData(vm); } else { observe(vm._data = {}, true /* asRootData */); } if (opts.computed) { initComputed(vm, opts.computed); } if (opts.watch && opts.watch !== nativeWatch) { initWatch(vm, opts.watch); } } function checkOptionType(vm, name) { const option = vm.$options[name]; if (!isPlainObject(option)) { warn( ('component option "' + name + '" should be an object.'), vm ); } } function initProps(vm, propsOptions) { const propsData = vm.$options.propsData || {}; const props = vm._props = {}; // cache prop keys so that future props updates can iterate using Array // instead of dynamic object key enumeration. const keys = vm.$options._propKeys = []; const isRoot = !vm.$parent; // root instance props should be converted observerState.shouldConvert = isRoot; const loop = function(key) { keys.push(key); const value = validateProp(key, propsOptions, propsData, vm); /* istanbul ignore else */ { if (isReservedAttribute(key) || config.isReservedAttr(key)) { warn( ('"' + key + '" is a reserved attribute and cannot be used as component prop.'), vm ); } defineReactive$$1(props, key, value, function() { if (vm.$parent && !isUpdatingChildComponent) { warn( 'Avoid mutating a prop directly since the value will be ' + 'overwritten whenever the parent component re-renders. ' + "Instead, use a data or computed property based on the prop's " + 'value. Prop being mutated: "' + key + '"', vm ); } }); } // static props are already proxied on the component's prototype // during Vue.extend(). We only need to proxy props defined at // instantiation here. if (!(key in vm)) { proxy(vm, '_props', key); } }; for (const key in propsOptions) loop(key); observerState.shouldConvert = true; } function initData(vm) { let data = vm.$options.data; data = vm._data = typeof data === 'function' ? getData(data, vm) : data || {}; if (!isPlainObject(data)) { data = {}; 'development' !== 'production' && warn( 'data functions should return an object:\n' + 'https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function', vm ); } // proxy data on instance const keys = Object.keys(data); const props = vm.$options.props; const methods = vm.$options.methods; let i = keys.length; while (i--) { const key = keys[i]; { if (methods && hasOwn(methods, key)) { warn( ('method "' + key + '" has already been defined as a data property.'), vm ); } } if (props && hasOwn(props, key)) { 'development' !== 'production' && warn( 'The data property "' + key + '" is already declared as a prop. ' + 'Use prop default value instead.', vm ); } else if (!isReserved(key)) { proxy(vm, '_data', key); } } // observe data observe(data, true /* asRootData */); } function getData(data, vm) { try { return data.call(vm); } catch (e) { handleError(e, vm, 'data()'); return {}; } } const computedWatcherOptions = { lazy: true, }; function initComputed(vm, computed) { 'development' !== 'production' && checkOptionType(vm, 'computed'); const watchers = vm._computedWatchers = Object.create(null); for (const key in computed) { const userDef = computed[key]; let getter = typeof userDef === 'function' ? userDef : userDef.get; { if (getter === undefined) { warn( ('No getter function has been defined for computed property "' + key + '".'), vm ); getter = noop; } } // create internal watcher for the computed property. watchers[key] = new Watcher(vm, getter, noop, computedWatcherOptions); // component-defined computed properties are already defined on the // component prototype. We only need to define computed properties defined // at instantiation here. if (!(key in vm)) { defineComputed(vm, key, userDef); } else { if (key in vm.$data) { warn(('The computed property "' + key + '" is already defined in data.'), vm); } else if (vm.$options.props && key in vm.$options.props) { warn(('The computed property "' + key + '" is already defined as a prop.'), vm); } } } } function defineComputed(target, key, userDef) { if (typeof userDef === 'function') { sharedPropertyDefinition.get = createComputedGetter(key); sharedPropertyDefinition.set = noop; } else { sharedPropertyDefinition.get = userDef.get ? userDef.cache !== false ? createComputedGetter(key) : userDef.get : noop; sharedPropertyDefinition.set = userDef.set ? userDef.set : noop; } Object.defineProperty(target, key, sharedPropertyDefinition); } function createComputedGetter(key) { return function computedGetter() { const watcher = this._computedWatchers && this._computedWatchers[key]; if (watcher) { if (watcher.dirty) { watcher.evaluate(); } if (Dep.target) { watcher.depend(); } return watcher.value; } }; } function initMethods(vm, methods) { 'development' !== 'production' && checkOptionType(vm, 'methods'); const props = vm.$options.props; for (const key in methods) { vm[key] = methods[key] == null ? noop : bind(methods[key], vm); { if (methods[key] == null) { warn( 'method "' + key + '" has an undefined value in the component definition. ' + 'Did you reference the function correctly?', vm ); } if (props && hasOwn(props, key)) { warn( ('method "' + key + '" has already been defined as a prop.'), vm ); } } } } function initWatch(vm, watch) { 'development' !== 'production' && checkOptionType(vm, 'watch'); for (const key in watch) { const handler = watch[key]; if (Array.isArray(handler)) { for (let i = 0; i < handler.length; i++) { createWatcher(vm, key, handler[i]); } } else { createWatcher(vm, key, handler); } } } function createWatcher( vm, keyOrFn, handler, options ) { if (isPlainObject(handler)) { options = handler; handler = handler.handler; } if (typeof handler === 'string') { handler = vm[handler]; } return vm.$watch(keyOrFn, handler, options); } function stateMixin(Vue) { // flow somehow has problems with directly declared definition object // when using Object.defineProperty, so we have to procedurally build up // the object here. const dataDef = {}; dataDef.get = function() { return this._data; }; const propsDef = {}; propsDef.get = function() { return this._props; }; { dataDef.set = function(newData) { warn( 'Avoid replacing instance root $data. ' + 'Use nested data properties instead.', this ); }; propsDef.set = function() { warn('$props is readonly.', this); }; } Object.defineProperty(Vue.prototype, '$data', dataDef); Object.defineProperty(Vue.prototype, '$props', propsDef); Vue.prototype.$set = set; Vue.prototype.$delete = del; Vue.prototype.$watch = function( expOrFn, cb, options ) { const vm = this; if (isPlainObject(cb)) { return createWatcher(vm, expOrFn, cb, options); } options = options || {}; options.user = true; const watcher = new Watcher(vm, expOrFn, cb, options); if (options.immediate) { cb.call(vm, watcher.value); } return function unwatchFn() { watcher.teardown(); }; }; } /* */ function initProvide(vm) { const provide = vm.$options.provide; if (provide) { vm._provided = typeof provide === 'function' ? provide.call(vm) : provide; } } function initInjections(vm) { const result = resolveInject(vm.$options.inject, vm); if (result) { observerState.shouldConvert = false; Object.keys(result).forEach(function(key) { /* istanbul ignore else */ { defineReactive$$1(vm, key, result[key], function() { warn( 'Avoid mutating an injected value directly since the changes will be ' + 'overwritten whenever the provided component re-renders. ' + 'injection being mutated: "' + key + '"', vm ); }); } }); observerState.shouldConvert = true; } } function resolveInject(inject, vm) { if (inject) { // inject is :any because flow is not smart enough to figure out cached const result = Object.create(null); const keys = hasSymbol ? Reflect.ownKeys(inject) : Object.keys(inject); for (let i = 0; i < keys.length; i++) { const key = keys[i]; const provideKey = inject[key]; let source = vm; while (source) { if (source._provided && provideKey in source._provided) { result[key] = source._provided[provideKey]; break; } source = source.$parent; } if ('development' !== 'production' && !hasOwn(result, key)) { warn(('Injection "' + key + '" not found'), vm); } } return result; } } /* */ function createFunctionalComponent( Ctor, propsData, data, context, children ) { const props = {}; const propOptions = Ctor.options.props; if (isDef(propOptions)) { for (const key in propOptions) { props[key] = validateProp(key, propOptions, propsData || {}); } } else { if (isDef(data.attrs)) { mergeProps(props, data.attrs); } if (isDef(data.props)) { mergeProps(props, data.props); } } // ensure the createElement function in functional components // gets a unique context - this is necessary for correct named slot check const _context = Object.create(context); const h = function(a, b, c, d) { return createElement(_context, a, b, c, d, true); }; const vnode = Ctor.options.render.call(null, h, { data, props, children, parent: context, listeners: data.on || {}, injections: resolveInject(Ctor.options.inject, context), slots() { return resolveSlots(children, context); }, }); if (vnode instanceof VNode) { vnode.functionalContext = context; vnode.functionalOptions = Ctor.options; if (data.slot) { (vnode.data || (vnode.data = {})).slot = data.slot; } } return vnode; } function mergeProps(to, from) { for (const key in from) { to[camelize(key)] = from[key]; } } /* */ // hooks to be invoked on component VNodes during patch var componentVNodeHooks = { init: function init( vnode, hydrating, parentElm, refElm ) { if (!vnode.componentInstance || vnode.componentInstance._isDestroyed) { const child = vnode.componentInstance = createComponentInstanceForVnode( vnode, activeInstance, parentElm, refElm ); child.$mount(hydrating ? vnode.elm : undefined, hydrating); } else if (vnode.data.keepAlive) { // kept-alive components, treat as a patch const mountedNode = vnode; // work around flow componentVNodeHooks.prepatch(mountedNode, mountedNode); } }, prepatch: function prepatch(oldVnode, vnode) { const options = vnode.componentOptions; const child = vnode.componentInstance = oldVnode.componentInstance; updateChildComponent( child, options.propsData, // updated props options.listeners, // updated listeners vnode, // new parent vnode options.children // new children ); }, insert: function insert(vnode) { const context = vnode.context; const componentInstance = vnode.componentInstance; if (!componentInstance._isMounted) { componentInstance._isMounted = true; callHook(componentInstance, 'mounted'); } if (vnode.data.keepAlive) { if (context._isMounted) { // vue-router#1212 // During updates, a kept-alive component's child components may // change, so directly walking the tree here may call activated hooks // on incorrect children. Instead we push them into a queue which will // be processed after the whole patch process ended. queueActivatedComponent(componentInstance); } else { activateChildComponent(componentInstance, true /* direct */); } } }, destroy: function destroy(vnode) { const componentInstance = vnode.componentInstance; if (!componentInstance._isDestroyed) { if (!vnode.data.keepAlive) { componentInstance.$destroy(); } else { deactivateChildComponent(componentInstance, true /* direct */); } } }, }; const hooksToMerge = Object.keys(componentVNodeHooks); function createComponent( Ctor, data, context, children, tag ) { if (isUndef(Ctor)) { return; } const baseCtor = context.$options._base; // plain options object: turn it into a constructor if (isObject(Ctor)) { Ctor = baseCtor.extend(Ctor); } // if at this stage it's not a constructor or an async component factory, // reject. if (typeof Ctor !== 'function') { { warn(('Invalid Component definition: ' + (String(Ctor))), context); } return; } // async component let asyncFactory; if (isUndef(Ctor.cid)) { asyncFactory = Ctor; Ctor = resolveAsyncComponent(asyncFactory, baseCtor, context); if (Ctor === undefined) { // return a placeholder node for async component, which is rendered // as a comment node but preserves all the raw information for the node. // the information will be used for async server-rendering and hydration. return createAsyncPlaceholder( asyncFactory, data, context, children, tag ); } } data = data || {}; // resolve constructor options in case global mixins are applied after // component constructor creation resolveConstructorOptions(Ctor); // transform component v-model data into props & events if (isDef(data.model)) { transformModel(Ctor.options, data); } // extract props const propsData = extractPropsFromVNodeData(data, Ctor, tag); // functional component if (isTrue(Ctor.options.functional)) { return createFunctionalComponent(Ctor, propsData, data, context, children); } // keep listeners const listeners = data.on; if (isTrue(Ctor.options.abstract)) { // abstract components do not keep anything // other than props & listeners & slot // work around flow const slot = data.slot; data = {}; if (slot) { data.slot = slot; } } // merge component management hooks onto the placeholder node mergeHooks(data); // return a placeholder vnode const name = Ctor.options.name || tag; const vnode = new VNode( ('vue-component-' + (Ctor.cid) + (name ? ('-' + name) : '')), data, undefined, undefined, undefined, context, { Ctor, propsData, listeners, tag, children, }, asyncFactory ); return vnode; } function createComponentInstanceForVnode( vnode, // we know it's MountedComponentVNode but flow doesn't parent, // activeInstance in lifecycle state parentElm, refElm ) { const vnodeComponentOptions = vnode.componentOptions; const options = { _isComponent: true, parent, propsData: vnodeComponentOptions.propsData, _componentTag: vnodeComponentOptions.tag, _parentVnode: vnode, _parentListeners: vnodeComponentOptions.listeners, _renderChildren: vnodeComponentOptions.children, _parentElm: parentElm || null, _refElm: refElm || null, }; // check inline-template render functions const inlineTemplate = vnode.data.inlineTemplate; if (isDef(inlineTemplate)) { options.render = inlineTemplate.render; options.staticRenderFns = inlineTemplate.staticRenderFns; } return new vnodeComponentOptions.Ctor(options); } function mergeHooks(data) { if (!data.hook) { data.hook = {}; } for (let i = 0; i < hooksToMerge.length; i++) { const key = hooksToMerge[i]; const fromParent = data.hook[key]; const ours = componentVNodeHooks[key]; data.hook[key] = fromParent ? mergeHook$1(ours, fromParent) : ours; } } function mergeHook$1(one, two) { return function(a, b, c, d) { one(a, b, c, d); two(a, b, c, d); }; } // transform component v-model info (value and callback) into // prop and event handler respectively. function transformModel(options, data) { const prop = (options.model && options.model.prop) || 'value'; const event = (options.model && options.model.event) || 'input'; (data.props || (data.props = {}))[prop] = data.model.value; const on = data.on || (data.on = {}); if (isDef(on[event])) { on[event] = [ data.model.callback ].concat(on[event]); } else { on[event] = data.model.callback; } } /* */ const SIMPLE_NORMALIZE = 1; const ALWAYS_NORMALIZE = 2; // wrapper function for providing a more flexible interface // without getting yelled at by flow function createElement( context, tag, data, children, normalizationType, alwaysNormalize ) { if (Array.isArray(data) || isPrimitive(data)) { normalizationType = children; children = data; data = undefined; } if (isTrue(alwaysNormalize)) { normalizationType = ALWAYS_NORMALIZE; } return _createElement(context, tag, data, children, normalizationType); } function _createElement( context, tag, data, children, normalizationType ) { if (isDef(data) && isDef((data).__ob__)) { 'development' !== 'production' && warn( 'Avoid using observed data object as vnode data: ' + (JSON.stringify(data)) + '\n' + 'Always create fresh vnode data objects in each render!', context ); return createEmptyVNode(); } // object syntax in v-bind if (isDef(data) && isDef(data.is)) { tag = data.is; } if (!tag) { // in case of component :is set to falsy value return createEmptyVNode(); } // warn against non-primitive key if ('development' !== 'production' && isDef(data) && isDef(data.key) && !isPrimitive(data.key) ) { warn( 'Avoid using non-primitive value as key, ' + 'use string/number value instead.', context ); } // support single function children as default scoped slot if (Array.isArray(children) && typeof children[0] === 'function' ) { data = data || {}; data.scopedSlots = { default: children[0], }; children.length = 0; } if (normalizationType === ALWAYS_NORMALIZE) { children = normalizeChildren(children); } else if (normalizationType === SIMPLE_NORMALIZE) { children = simpleNormalizeChildren(children); } let vnode, ns; if (typeof tag === 'string') { let Ctor; ns = config.getTagNamespace(tag); if (config.isReservedTag(tag)) { // platform built-in elements vnode = new VNode( config.parsePlatformTagName(tag), data, children, undefined, undefined, context ); } else if (isDef(Ctor = resolveAsset(context.$options, 'components', tag))) { // component vnode = createComponent(Ctor, data, context, children, tag); } else { // unknown or unlisted namespaced elements // check at runtime because it may get assigned a namespace when its // parent normalizes children vnode = new VNode( tag, data, children, undefined, undefined, context ); } } else { // direct component options / constructor vnode = createComponent(tag, data, context, children); } if (isDef(vnode)) { if (ns) { applyNS(vnode, ns); } return vnode; } return createEmptyVNode(); } function applyNS(vnode, ns) { vnode.ns = ns; if (vnode.tag === 'foreignObject') { // use default namespace inside foreignObject return; } if (isDef(vnode.children)) { for (let i = 0, l = vnode.children.length; i < l; i++) { const child = vnode.children[i]; if (isDef(child.tag) && isUndef(child.ns)) { applyNS(child, ns); } } } } /* */ /** * Runtime helper for rendering v-for lists. */ function renderList( val, render ) { let ret, i, l, keys, key; if (Array.isArray(val) || typeof val === 'string') { ret = new Array(val.length); for (i = 0, l = val.length; i < l; i++) { ret[i] = render(val[i], i); } } else if (typeof val === 'number') { ret = new Array(val); for (i = 0; i < val; i++) { ret[i] = render(i + 1, i); } } else if (isObject(val)) { keys = Object.keys(val); ret = new Array(keys.length); for (i = 0, l = keys.length; i < l; i++) { key = keys[i]; ret[i] = render(val[key], key, i); } } if (isDef(ret)) { (ret)._isVList = true; } return ret; } /* */ /** * Runtime helper for rendering <slot> */ function renderSlot( name, fallback, props, bindObject ) { const scopedSlotFn = this.$scopedSlots[name]; if (scopedSlotFn) { // scoped slot props = props || {}; if (bindObject) { props = extend(extend({}, bindObject), props); } return scopedSlotFn(props) || fallback; } const slotNodes = this.$slots[name]; // warn duplicate slot usage if (slotNodes && 'development' !== 'production') { slotNodes._rendered && warn( 'Duplicate presence of slot "' + name + '" found in the same render tree ' + '- this will likely cause render errors.', this ); slotNodes._rendered = true; } return slotNodes || fallback; } /* */ /** * Runtime helper for resolving filters */ function resolveFilter(id) { return resolveAsset(this.$options, 'filters', id, true) || identity; } /* */ /** * Runtime helper for checking keyCodes from config. */ function checkKeyCodes( eventKeyCode, key, builtInAlias ) { const keyCodes = config.keyCodes[key] || builtInAlias; if (Array.isArray(keyCodes)) { return keyCodes.indexOf(eventKeyCode) === -1; } return keyCodes !== eventKeyCode; } /* */ /** * Runtime helper for merging v-bind="object" into a VNode's data. */ function bindObjectProps( data, tag, value, asProp, isSync ) { if (value) { if (!isObject(value)) { 'development' !== 'production' && warn( 'v-bind without argument expects an Object or Array value', this ); } else { if (Array.isArray(value)) { value = toObject(value); } let hash; const loop = function(key) { if ( key === 'class' || key === 'style' || isReservedAttribute(key) ) { hash = data; } else { const type = data.attrs && data.attrs.type; hash = asProp || config.mustUseProp(tag, type, key) ? data.domProps || (data.domProps = {}) : data.attrs || (data.attrs = {}); } if (!(key in hash)) { hash[key] = value[key]; if (isSync) { const on = data.on || (data.on = {}); on[('update:' + key)] = function($event) { value[key] = $event; }; } } }; for (const key in value) loop(key); } } return data; } /* */ /** * Runtime helper for rendering static trees. */ function renderStatic( index, isInFor ) { let tree = this._staticTrees[index]; // if has already-rendered static tree and not inside v-for, // we can reuse the same tree by doing a shallow clone. if (tree && !isInFor) { return Array.isArray(tree) ? cloneVNodes(tree) : cloneVNode(tree); } // otherwise, render a fresh tree. tree = this._staticTrees[index] = this.$options.staticRenderFns[index].call(this._renderProxy); markStatic(tree, ('__static__' + index), false); return tree; } /** * Runtime helper for v-once. * Effectively it means marking the node as static with a unique key. */ function markOnce( tree, index, key ) { markStatic(tree, ('__once__' + index + (key ? ('_' + key) : '')), true); return tree; } function markStatic( tree, key, isOnce ) { if (Array.isArray(tree)) { for (let i = 0; i < tree.length; i++) { if (tree[i] && typeof tree[i] !== 'string') { markStaticNode(tree[i], (key + '_' + i), isOnce); } } } else { markStaticNode(tree, key, isOnce); } } function markStaticNode(node, key, isOnce) { node.isStatic = true; node.key = key; node.isOnce = isOnce; } /* */ function bindObjectListeners(data, value) { if (value) { if (!isPlainObject(value)) { 'development' !== 'production' && warn( 'v-on without argument expects an Object value', this ); } else { const on = data.on = data.on ? extend({}, data.on) : {}; for (const key in value) { const existing = on[key]; const ours = value[key]; on[key] = existing ? [].concat(ours, existing) : ours; } } } return data; } /* */ function initRender(vm) { vm._vnode = null; // the root of the child tree vm._staticTrees = null; const parentVnode = vm.$vnode = vm.$options._parentVnode; // the placeholder node in parent tree const renderContext = parentVnode && parentVnode.context; vm.$slots = resolveSlots(vm.$options._renderChildren, renderContext); vm.$scopedSlots = emptyObject; // bind the createElement fn to this instance // so that we get proper render context inside it. // args order: tag, data, children, normalizationType, alwaysNormalize // internal version is used by render functions compiled from templates vm._c = function(a, b, c, d) { return createElement(vm, a, b, c, d, false); }; // normalization is always applied for the public version, used in // user-written render functions. vm.$createElement = function(a, b, c, d) { return createElement(vm, a, b, c, d, true); }; // $attrs & $listeners are exposed for easier HOC creation. // they need to be reactive so that HOCs using them are always updated const parentData = parentVnode && parentVnode.data; /* istanbul ignore else */ { defineReactive$$1(vm, '$attrs', parentData && parentData.attrs, function() { !isUpdatingChildComponent && warn('$attrs is readonly.', vm); }, true); defineReactive$$1(vm, '$listeners', parentData && parentData.on, function() { !isUpdatingChildComponent && warn('$listeners is readonly.', vm); }, true); } } function renderMixin(Vue) { Vue.prototype.$nextTick = function(fn) { return nextTick(fn, this); }; Vue.prototype._render = function() { const vm = this; const ref = vm.$options; const render = ref.render; const staticRenderFns = ref.staticRenderFns; const _parentVnode = ref._parentVnode; if (vm._isMounted) { // clone slot nodes on re-renders for (const key in vm.$slots) { vm.$slots[key] = cloneVNodes(vm.$slots[key]); } } vm.$scopedSlots = (_parentVnode && _parentVnode.data.scopedSlots) || emptyObject; if (staticRenderFns && !vm._staticTrees) { vm._staticTrees = []; } // set parent vnode. this allows render functions to have access // to the data on the placeholder node. vm.$vnode = _parentVnode; // render self let vnode; try { vnode = render.call(vm._renderProxy, vm.$createElement); } catch (e) { handleError(e, vm, 'render function'); // return error render result, // or previous vnode to prevent render error causing blank component /* istanbul ignore else */ { vnode = vm.$options.renderError ? vm.$options.renderError.call(vm._renderProxy, vm.$createElement, e) : vm._vnode; } } // return empty vnode in case the render function errored out if (!(vnode instanceof VNode)) { if ('development' !== 'production' && Array.isArray(vnode)) { warn( 'Multiple root nodes returned from render function. Render function ' + 'should return a single root node.', vm ); } vnode = createEmptyVNode(); } // set parent vnode.parent = _parentVnode; return vnode; }; // internal render helpers. // these are exposed on the instance prototype to reduce generated render // code size. Vue.prototype._o = markOnce; Vue.prototype._n = toNumber; Vue.prototype._s = toString; Vue.prototype._l = renderList; Vue.prototype._t = renderSlot; Vue.prototype._q = looseEqual; Vue.prototype._i = looseIndexOf; Vue.prototype._m = renderStatic; Vue.prototype._f = resolveFilter; Vue.prototype._k = checkKeyCodes; Vue.prototype._b = bindObjectProps; Vue.prototype._v = createTextVNode; Vue.prototype._e = createEmptyVNode; Vue.prototype._u = resolveScopedSlots; Vue.prototype._g = bindObjectListeners; } /* */ let uid$1 = 0; function initMixin(Vue) { Vue.prototype._init = function(options) { const vm = this; // a uid vm._uid = uid$1++; let startTag, endTag; /* istanbul ignore if */ if ('development' !== 'production' && config.performance && mark) { startTag = 'vue-perf-init:' + (vm._uid); endTag = 'vue-perf-end:' + (vm._uid); mark(startTag); } // a flag to avoid this being observed vm._isVue = true; // merge options if (options && options._isComponent) { // optimize internal component instantiation // since dynamic options merging is pretty slow, and none of the // internal component options needs special treatment. initInternalComponent(vm, options); } else { vm.$options = mergeOptions( resolveConstructorOptions(vm.constructor), options || {}, vm ); } /* istanbul ignore else */ { initProxy(vm); } // expose real self vm._self = vm; initLifecycle(vm); initEvents(vm); initRender(vm); callHook(vm, 'beforeCreate'); initInjections(vm); // resolve injections before data/props initState(vm); initProvide(vm); // resolve provide after data/props callHook(vm, 'created'); /* istanbul ignore if */ if ('development' !== 'production' && config.performance && mark) { vm._name = formatComponentName(vm, false); mark(endTag); measure(((vm._name) + ' init'), startTag, endTag); } if (vm.$options.el) { vm.$mount(vm.$options.el); } }; } function initInternalComponent(vm, options) { const opts = vm.$options = Object.create(vm.constructor.options); // doing this because it's faster than dynamic enumeration. opts.parent = options.parent; opts.propsData = options.propsData; opts._parentVnode = options._parentVnode; opts._parentListeners = options._parentListeners; opts._renderChildren = options._renderChildren; opts._componentTag = options._componentTag; opts._parentElm = options._parentElm; opts._refElm = options._refElm; if (options.render) { opts.render = options.render; opts.staticRenderFns = options.staticRenderFns; } } function resolveConstructorOptions(Ctor) { let options = Ctor.options; if (Ctor.super) { const superOptions = resolveConstructorOptions(Ctor.super); const cachedSuperOptions = Ctor.superOptions; if (superOptions !== cachedSuperOptions) { // super option changed, // need to resolve new options. Ctor.superOptions = superOptions; // check if there are any late-modified/attached options (#4976) const modifiedOptions = resolveModifiedOptions(Ctor); // update base extend options if (modifiedOptions) { extend(Ctor.extendOptions, modifiedOptions); } options = Ctor.options = mergeOptions(superOptions, Ctor.extendOptions); if (options.name) { options.components[options.name] = Ctor; } } } return options; } function resolveModifiedOptions(Ctor) { let modified; const latest = Ctor.options; const extended = Ctor.extendOptions; const sealed = Ctor.sealedOptions; for (const key in latest) { if (latest[key] !== sealed[key]) { if (!modified) { modified = {}; } modified[key] = dedupe(latest[key], extended[key], sealed[key]); } } return modified; } function dedupe(latest, extended, sealed) { // compare latest and sealed to ensure lifecycle hooks won't be duplicated // between merges if (Array.isArray(latest)) { const res = []; sealed = Array.isArray(sealed) ? sealed : [ sealed ]; extended = Array.isArray(extended) ? extended : [ extended ]; for (let i = 0; i < latest.length; i++) { // push original options and not sealed options to exclude duplicated options if (extended.indexOf(latest[i]) >= 0 || sealed.indexOf(latest[i]) < 0) { res.push(latest[i]); } } return res; } return latest; } function Vue$3(options) { if ('development' !== 'production' && !(this instanceof Vue$3) ) { warn('Vue is a constructor and should be called with the `new` keyword'); } this._init(options); } initMixin(Vue$3); stateMixin(Vue$3); eventsMixin(Vue$3); lifecycleMixin(Vue$3); renderMixin(Vue$3); /* */ function initUse(Vue) { Vue.use = function(plugin) { const installedPlugins = (this._installedPlugins || (this._installedPlugins = [])); if (installedPlugins.indexOf(plugin) > -1) { return this; } // additional parameters const args = toArray(arguments, 1); args.unshift(this); if (typeof plugin.install === 'function') { plugin.install.apply(plugin, args); } else if (typeof plugin === 'function') { plugin.apply(null, args); } installedPlugins.push(plugin); return this; }; } /* */ function initMixin$1(Vue) { Vue.mixin = function(mixin) { this.options = mergeOptions(this.options, mixin); return this; }; } /* */ function initExtend(Vue) { /** * Each instance constructor, including Vue, has a unique * cid. This enables us to create wrapped "child * constructors" for prototypal inheritance and cache them. */ Vue.cid = 0; let cid = 1; /** * Class inheritance */ Vue.extend = function(extendOptions) { extendOptions = extendOptions || {}; const Super = this; const SuperId = Super.cid; const cachedCtors = extendOptions._Ctor || (extendOptions._Ctor = {}); if (cachedCtors[SuperId]) { return cachedCtors[SuperId]; } const name = extendOptions.name || Super.options.name; { if (!/^[a-zA-Z][\w-]*$/.test(name)) { warn( 'Invalid component name: "' + name + '". Component names ' + 'can only contain alphanumeric characters and the hyphen, ' + 'and must start with a letter.' ); } } const Sub = function VueComponent(options) { this._init(options); }; Sub.prototype = Object.create(Super.prototype); Sub.prototype.constructor = Sub; Sub.cid = cid++; Sub.options = mergeOptions( Super.options, extendOptions ); Sub.super = Super; // For props and computed properties, we define the proxy getters on // the Vue instances at extension time, on the extended prototype. This // avoids Object.defineProperty calls for each instance created. if (Sub.options.props) { initProps$1(Sub); } if (Sub.options.computed) { initComputed$1(Sub); } // allow further extension/mixin/plugin usage Sub.extend = Super.extend; Sub.mixin = Super.mixin; Sub.use = Super.use; // create asset registers, so extended classes // can have their private assets too. ASSET_TYPES.forEach(function(type) { Sub[type] = Super[type]; }); // enable recursive self-lookup if (name) { Sub.options.components[name] = Sub; } // keep a reference to the super options at extension time. // later at instantiation we can check if Super's options have // been updated. Sub.superOptions = Super.options; Sub.extendOptions = extendOptions; Sub.sealedOptions = extend({}, Sub.options); // cache constructor cachedCtors[SuperId] = Sub; return Sub; }; } function initProps$1(Comp) { const props = Comp.options.props; for (const key in props) { proxy(Comp.prototype, '_props', key); } } function initComputed$1(Comp) { const computed = Comp.options.computed; for (const key in computed) { defineComputed(Comp.prototype, key, computed[key]); } } /* */ function initAssetRegisters(Vue) { /** * Create asset registration methods. */ ASSET_TYPES.forEach(function(type) { Vue[type] = function( id, definition ) { if (!definition) { return this.options[type + 's'][id]; } /* istanbul ignore if */ { if (type === 'component' && config.isReservedTag(id)) { warn( 'Do not use built-in or reserved HTML elements as component ' + 'id: ' + id ); } } if (type === 'component' && isPlainObject(definition)) { definition.name = definition.name || id; definition = this.options._base.extend(definition); } if (type === 'directive' && typeof definition === 'function') { definition = { bind: definition, update: definition, }; } this.options[type + 's'][id] = definition; return definition; }; }); } /* */ const patternTypes = [ String, RegExp, Array ]; function getComponentName(opts) { return opts && (opts.Ctor.options.name || opts.tag); } function matches(pattern, name) { if (Array.isArray(pattern)) { return pattern.indexOf(name) > -1; } else if (typeof pattern === 'string') { return pattern.split(',').indexOf(name) > -1; } else if (isRegExp(pattern)) { return pattern.test(name); } /* istanbul ignore next */ return false; } function pruneCache(cache, current, filter) { for (const key in cache) { const cachedNode = cache[key]; if (cachedNode) { const name = getComponentName(cachedNode.componentOptions); if (name && !filter(name)) { if (cachedNode !== current) { pruneCacheEntry(cachedNode); } cache[key] = null; } } } } function pruneCacheEntry(vnode) { if (vnode) { vnode.componentInstance.$destroy(); } } const KeepAlive = { name: 'keep-alive', abstract: true, props: { include: patternTypes, exclude: patternTypes, }, created: function created() { this.cache = Object.create(null); }, destroyed: function destroyed() { const this$1 = this; for (const key in this$1.cache) { pruneCacheEntry(this$1.cache[key]); } }, watch: { include: function include(val) { pruneCache(this.cache, this._vnode, function(name) { return matches(val, name); }); }, exclude: function exclude(val) { pruneCache(this.cache, this._vnode, function(name) { return !matches(val, name); }); }, }, render: function render() { const vnode = getFirstComponentChild(this.$slots.default); const componentOptions = vnode && vnode.componentOptions; if (componentOptions) { // check pattern const name = getComponentName(componentOptions); if (name && ( (this.include && !matches(this.include, name)) || (this.exclude && matches(this.exclude, name)) )) { return vnode; } const key = vnode.key == null // same constructor may get registered as different local components // so cid alone is not enough (#3269) ? componentOptions.Ctor.cid + (componentOptions.tag ? ('::' + (componentOptions.tag)) : '') : vnode.key; if (this.cache[key]) { vnode.componentInstance = this.cache[key].componentInstance; } else { this.cache[key] = vnode; } vnode.data.keepAlive = true; } return vnode; }, }; const builtInComponents = { KeepAlive, }; /* */ function initGlobalAPI(Vue) { // config const configDef = {}; configDef.get = function() { return config; }; { configDef.set = function() { warn( 'Do not replace the Vue.config object, set individual fields instead.' ); }; } Object.defineProperty(Vue, 'config', configDef); // exposed util methods. // NOTE: these are not considered part of the public API - avoid relying on // them unless you are aware of the risk. Vue.util = { warn, extend, mergeOptions, defineReactive: defineReactive$$1, }; Vue.set = set; Vue.delete = del; Vue.nextTick = nextTick; Vue.options = Object.create(null); ASSET_TYPES.forEach(function(type) { Vue.options[type + 's'] = Object.create(null); }); // this is used to identify the "base" constructor to extend all plain-object // components with in Weex's multi-instance scenarios. Vue.options._base = Vue; extend(Vue.options.components, builtInComponents); initUse(Vue); initMixin$1(Vue); initExtend(Vue); initAssetRegisters(Vue); } initGlobalAPI(Vue$3); Object.defineProperty(Vue$3.prototype, '$isServer', { get: isServerRendering, }); Object.defineProperty(Vue$3.prototype, '$ssrContext', { get: function get() { /* istanbul ignore next */ return this.$vnode && this.$vnode.ssrContext; }, }); Vue$3.version = '2.4.0'; /* */ // these are reserved for web because they are directly compiled away // during template compilation const isReservedAttr = makeMap('style,class'); // attributes that should be using props for binding const acceptValue = makeMap('input,textarea,option,select'); const mustUseProp = function(tag, type, attr) { return ( (attr === 'value' && acceptValue(tag)) && type !== 'button' || (attr === 'selected' && tag === 'option') || (attr === 'checked' && tag === 'input') || (attr === 'muted' && tag === 'video') ); }; const isEnumeratedAttr = makeMap('contenteditable,draggable,spellcheck'); const isBooleanAttr = makeMap( 'allowfullscreen,async,autofocus,autoplay,checked,compact,controls,declare,' + 'default,defaultchecked,defaultmuted,defaultselected,defer,disabled,' + 'enabled,formnovalidate,hidden,indeterminate,inert,ismap,itemscope,loop,multiple,' + 'muted,nohref,noresize,noshade,novalidate,nowrap,open,pauseonexit,readonly,' + 'required,reversed,scoped,seamless,selected,sortable,translate,' + 'truespeed,typemustmatch,visible' ); const xlinkNS = 'http://www.w3.org/1999/xlink'; const isXlink = function(name) { return name.charAt(5) === ':' && name.slice(0, 5) === 'xlink'; }; const getXlinkProp = function(name) { return isXlink(name) ? name.slice(6, name.length) : ''; }; const isFalsyAttrValue = function(val) { return val == null || val === false; }; /* */ function genClassForVnode(vnode) { let data = vnode.data; let parentNode = vnode; let childNode = vnode; while (isDef(childNode.componentInstance)) { childNode = childNode.componentInstance._vnode; if (childNode.data) { data = mergeClassData(childNode.data, data); } } while (isDef(parentNode = parentNode.parent)) { if (parentNode.data) { data = mergeClassData(data, parentNode.data); } } return renderClass(data.staticClass, data.class); } function mergeClassData(child, parent) { return { staticClass: concat(child.staticClass, parent.staticClass), class: isDef(child.class) ? [ child.class, parent.class ] : parent.class, }; } function renderClass( staticClass, dynamicClass ) { if (isDef(staticClass) || isDef(dynamicClass)) { return concat(staticClass, stringifyClass(dynamicClass)); } /* istanbul ignore next */ return ''; } function concat(a, b) { return a ? b ? (a + ' ' + b) : a : (b || ''); } function stringifyClass(value) { if (Array.isArray(value)) { return stringifyArray(value); } if (isObject(value)) { return stringifyObject(value); } if (typeof value === 'string') { return value; } /* istanbul ignore next */ return ''; } function stringifyArray(value) { let res = ''; let stringified; for (let i = 0, l = value.length; i < l; i++) { if (isDef(stringified = stringifyClass(value[i])) && stringified !== '') { if (res) { res += ' '; } res += stringified; } } return res; } function stringifyObject(value) { let res = ''; for (const key in value) { if (value[key]) { if (res) { res += ' '; } res += key; } } return res; } /* */ const namespaceMap = { svg: 'http://www.w3.org/2000/svg', math: 'http://www.w3.org/1998/Math/MathML', }; const isHTMLTag = makeMap( 'html,body,base,head,link,meta,style,title,' + 'address,article,aside,footer,header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,' + 'div,dd,dl,dt,figcaption,figure,picture,hr,img,li,main,ol,p,pre,ul,' + 'a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,' + 's,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,' + 'embed,object,param,source,canvas,script,noscript,del,ins,' + 'caption,col,colgroup,table,thead,tbody,td,th,tr,' + 'button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,' + 'output,progress,select,textarea,' + 'details,dialog,menu,menuitem,summary,' + 'content,element,shadow,template,blockquote,iframe,tfoot' ); // this map is intentionally selective, only covering SVG elements that may // contain child elements. const isSVG = makeMap( 'svg,animate,circle,clippath,cursor,defs,desc,ellipse,filter,font-face,' + 'foreignObject,g,glyph,image,line,marker,mask,missing-glyph,path,pattern,' + 'polygon,polyline,rect,switch,symbol,text,textpath,tspan,use,view', true ); const isPreTag = function(tag) { return tag === 'pre'; }; const isReservedTag = function(tag) { return isHTMLTag(tag) || isSVG(tag); }; function getTagNamespace(tag) { if (isSVG(tag)) { return 'svg'; } // basic support for MathML // note it doesn't support other MathML elements being component roots if (tag === 'math') { return 'math'; } } const unknownElementCache = Object.create(null); function isUnknownElement(tag) { /* istanbul ignore if */ if (!inBrowser) { return true; } if (isReservedTag(tag)) { return false; } tag = tag.toLowerCase(); /* istanbul ignore if */ if (unknownElementCache[tag] != null) { return unknownElementCache[tag]; } const el = document.createElement(tag); if (tag.indexOf('-') > -1) { // http://stackoverflow.com/a/28210364/1070244 return (unknownElementCache[tag] = ( el.constructor === window.HTMLUnknownElement || el.constructor === window.HTMLElement )); } return (unknownElementCache[tag] = /HTMLUnknownElement/.test(el.toString())); } /* */ /** * Query an element selector if it's not an element already. */ function query(el) { if (typeof el === 'string') { const selected = document.querySelector(el); if (!selected) { 'development' !== 'production' && warn( 'Cannot find element: ' + el ); return document.createElement('div'); } return selected; } return el; } /* */ function createElement$1(tagName, vnode) { const elm = document.createElement(tagName); if (tagName !== 'select') { return elm; } // false or null will remove the attribute but undefined will not if (vnode.data && vnode.data.attrs && vnode.data.attrs.multiple !== undefined) { elm.setAttribute('multiple', 'multiple'); } return elm; } function createElementNS(namespace, tagName) { return document.createElementNS(namespaceMap[namespace], tagName); } function createTextNode(text) { return document.createTextNode(text); } function createComment(text) { return document.createComment(text); } function insertBefore(parentNode, newNode, referenceNode) { parentNode.insertBefore(newNode, referenceNode); } function removeChild(node, child) { node.removeChild(child); } function appendChild(node, child) { node.appendChild(child); } function parentNode(node) { return node.parentNode; } function nextSibling(node) { return node.nextSibling; } function tagName(node) { return node.tagName; } function setTextContent(node, text) { node.textContent = text; } function setAttribute(node, key, val) { node.setAttribute(key, val); } const nodeOps = Object.freeze({ createElement: createElement$1, createElementNS, createTextNode, createComment, insertBefore, removeChild, appendChild, parentNode, nextSibling, tagName, setTextContent, setAttribute, }); /* */ const ref = { create: function create(_, vnode) { registerRef(vnode); }, update: function update(oldVnode, vnode) { if (oldVnode.data.ref !== vnode.data.ref) { registerRef(oldVnode, true); registerRef(vnode); } }, destroy: function destroy(vnode) { registerRef(vnode, true); }, }; function registerRef(vnode, isRemoval) { const key = vnode.data.ref; if (!key) { return; } const vm = vnode.context; const ref = vnode.componentInstance || vnode.elm; const refs = vm.$refs; if (isRemoval) { if (Array.isArray(refs[key])) { remove(refs[key], ref); } else if (refs[key] === ref) { refs[key] = undefined; } } else { if (vnode.data.refInFor) { if (!Array.isArray(refs[key])) { refs[key] = [ ref ]; } else if (refs[key].indexOf(ref) < 0) { // $flow-disable-line refs[key].push(ref); } } else { refs[key] = ref; } } } /** * Virtual DOM patching algorithm based on Snabbdom by * Simon Friis Vindum (@paldepind) * Licensed under the MIT License * https://github.com/paldepind/snabbdom/blob/master/LICENSE * * modified by Evan You (@yyx990803) * /* * Not type-checking this because this file is perf-critical and the cost * of making flow understand it is not worth it. */ const emptyNode = new VNode('', {}, []); const hooks = [ 'create', 'activate', 'update', 'remove', 'destroy' ]; function sameVnode(a, b) { return ( a.key === b.key && ( ( a.tag === b.tag && a.isComment === b.isComment && isDef(a.data) === isDef(b.data) && sameInputType(a, b) ) || ( isTrue(a.isAsyncPlaceholder) && a.asyncFactory === b.asyncFactory && isUndef(b.asyncFactory.error) ) ) ); } // Some browsers do not support dynamically changing type for <input> // so they need to be treated as different nodes function sameInputType(a, b) { if (a.tag !== 'input') { return true; } let i; const typeA = isDef(i = a.data) && isDef(i = i.attrs) && i.type; const typeB = isDef(i = b.data) && isDef(i = i.attrs) && i.type; return typeA === typeB; } function createKeyToOldIdx(children, beginIdx, endIdx) { let i, key; const map = {}; for (i = beginIdx; i <= endIdx; ++i) { key = children[i].key; if (isDef(key)) { map[key] = i; } } return map; } function createPatchFunction(backend) { let i, j; const cbs = {}; const modules = backend.modules; const nodeOps = backend.nodeOps; for (i = 0; i < hooks.length; ++i) { cbs[hooks[i]] = []; for (j = 0; j < modules.length; ++j) { if (isDef(modules[j][hooks[i]])) { cbs[hooks[i]].push(modules[j][hooks[i]]); } } } function emptyNodeAt(elm) { return new VNode(nodeOps.tagName(elm).toLowerCase(), {}, [], undefined, elm); } function createRmCb(childElm, listeners) { function remove$$1() { if (--remove$$1.listeners === 0) { removeNode(childElm); } } remove$$1.listeners = listeners; return remove$$1; } function removeNode(el) { const parent = nodeOps.parentNode(el); // element may have already been removed due to v-html / v-text if (isDef(parent)) { nodeOps.removeChild(parent, el); } } let inPre = 0; function createElm(vnode, insertedVnodeQueue, parentElm, refElm, nested) { vnode.isRootInsert = !nested; // for transition enter check if (createComponent(vnode, insertedVnodeQueue, parentElm, refElm)) { return; } const data = vnode.data; const children = vnode.children; const tag = vnode.tag; if (isDef(tag)) { { if (data && data.pre) { inPre++; } if (!inPre && !vnode.ns && !(config.ignoredElements.length && config.ignoredElements.indexOf(tag) > -1) && config.isUnknownElement(tag) ) { warn( 'Unknown custom element: <' + tag + '> - did you ' + 'register the component correctly? For recursive components, ' + 'make sure to provide the "name" option.', vnode.context ); } } vnode.elm = vnode.ns ? nodeOps.createElementNS(vnode.ns, tag) : nodeOps.createElement(tag, vnode); setScope(vnode); /* istanbul ignore if */ { createChildren(vnode, children, insertedVnodeQueue); if (isDef(data)) { invokeCreateHooks(vnode, insertedVnodeQueue); } insert(parentElm, vnode.elm, refElm); } if ('development' !== 'production' && data && data.pre) { inPre--; } } else if (isTrue(vnode.isComment)) { vnode.elm = nodeOps.createComment(vnode.text); insert(parentElm, vnode.elm, refElm); } else { vnode.elm = nodeOps.createTextNode(vnode.text); insert(parentElm, vnode.elm, refElm); } } function createComponent(vnode, insertedVnodeQueue, parentElm, refElm) { let i = vnode.data; if (isDef(i)) { const isReactivated = isDef(vnode.componentInstance) && i.keepAlive; if (isDef(i = i.hook) && isDef(i = i.init)) { i(vnode, false /* hydrating */, parentElm, refElm); } // after calling the init hook, if the vnode is a child component // it should've created a child instance and mounted it. the child // component also has set the placeholder vnode's elm. // in that case we can just return the element and be done. if (isDef(vnode.componentInstance)) { initComponent(vnode, insertedVnodeQueue); if (isTrue(isReactivated)) { reactivateComponent(vnode, insertedVnodeQueue, parentElm, refElm); } return true; } } } function initComponent(vnode, insertedVnodeQueue) { if (isDef(vnode.data.pendingInsert)) { insertedVnodeQueue.push.apply(insertedVnodeQueue, vnode.data.pendingInsert); vnode.data.pendingInsert = null; } vnode.elm = vnode.componentInstance.$el; if (isPatchable(vnode)) { invokeCreateHooks(vnode, insertedVnodeQueue); setScope(vnode); } else { // empty component root. // skip all element-related modules except for ref (#3455) registerRef(vnode); // make sure to invoke the insert hook insertedVnodeQueue.push(vnode); } } function reactivateComponent(vnode, insertedVnodeQueue, parentElm, refElm) { let i; // hack for #4339: a reactivated component with inner transition // does not trigger because the inner node's created hooks are not called // again. It's not ideal to involve module-specific logic in here but // there doesn't seem to be a better way to do it. let innerNode = vnode; while (innerNode.componentInstance) { innerNode = innerNode.componentInstance._vnode; if (isDef(i = innerNode.data) && isDef(i = i.transition)) { for (i = 0; i < cbs.activate.length; ++i) { cbs.activate[i](emptyNode, innerNode); } insertedVnodeQueue.push(innerNode); break; } } // unlike a newly created component, // a reactivated keep-alive component doesn't insert itself insert(parentElm, vnode.elm, refElm); } function insert(parent, elm, ref$$1) { if (isDef(parent)) { if (isDef(ref$$1)) { if (ref$$1.parentNode === parent) { nodeOps.insertBefore(parent, elm, ref$$1); } } else { nodeOps.appendChild(parent, elm); } } } function createChildren(vnode, children, insertedVnodeQueue) { if (Array.isArray(children)) { for (let i = 0; i < children.length; ++i) { createElm(children[i], insertedVnodeQueue, vnode.elm, null, true); } } else if (isPrimitive(vnode.text)) { nodeOps.appendChild(vnode.elm, nodeOps.createTextNode(vnode.text)); } } function isPatchable(vnode) { while (vnode.componentInstance) { vnode = vnode.componentInstance._vnode; } return isDef(vnode.tag); } function invokeCreateHooks(vnode, insertedVnodeQueue) { for (let i$1 = 0; i$1 < cbs.create.length; ++i$1) { cbs.create[i$1](emptyNode, vnode); } i = vnode.data.hook; // Reuse variable if (isDef(i)) { if (isDef(i.create)) { i.create(emptyNode, vnode); } if (isDef(i.insert)) { insertedVnodeQueue.push(vnode); } } } // set scope id attribute for scoped CSS. // this is implemented as a special case to avoid the overhead // of going through the normal attribute patching process. function setScope(vnode) { let i; let ancestor = vnode; while (ancestor) { if (isDef(i = ancestor.context) && isDef(i = i.$options._scopeId)) { nodeOps.setAttribute(vnode.elm, i, ''); } ancestor = ancestor.parent; } // for slot content they should also get the scopeId from the host instance. if (isDef(i = activeInstance) && i !== vnode.context && isDef(i = i.$options._scopeId) ) { nodeOps.setAttribute(vnode.elm, i, ''); } } function addVnodes(parentElm, refElm, vnodes, startIdx, endIdx, insertedVnodeQueue) { for (; startIdx <= endIdx; ++startIdx) { createElm(vnodes[startIdx], insertedVnodeQueue, parentElm, refElm); } } function invokeDestroyHook(vnode) { let i, j; const data = vnode.data; if (isDef(data)) { if (isDef(i = data.hook) && isDef(i = i.destroy)) { i(vnode); } for (i = 0; i < cbs.destroy.length; ++i) { cbs.destroy[i](vnode); } } if (isDef(i = vnode.children)) { for (j = 0; j < vnode.children.length; ++j) { invokeDestroyHook(vnode.children[j]); } } } function removeVnodes(parentElm, vnodes, startIdx, endIdx) { for (; startIdx <= endIdx; ++startIdx) { const ch = vnodes[startIdx]; if (isDef(ch)) { if (isDef(ch.tag)) { removeAndInvokeRemoveHook(ch); invokeDestroyHook(ch); } else { // Text node removeNode(ch.elm); } } } } function removeAndInvokeRemoveHook(vnode, rm) { if (isDef(rm) || isDef(vnode.data)) { let i; const listeners = cbs.remove.length + 1; if (isDef(rm)) { // we have a recursively passed down rm callback // increase the listeners count rm.listeners += listeners; } else { // directly removing rm = createRmCb(vnode.elm, listeners); } // recursively invoke hooks on child component root node if (isDef(i = vnode.componentInstance) && isDef(i = i._vnode) && isDef(i.data)) { removeAndInvokeRemoveHook(i, rm); } for (i = 0; i < cbs.remove.length; ++i) { cbs.remove[i](vnode, rm); } if (isDef(i = vnode.data.hook) && isDef(i = i.remove)) { i(vnode, rm); } else { rm(); } } else { removeNode(vnode.elm); } } function updateChildren(parentElm, oldCh, newCh, insertedVnodeQueue, removeOnly) { let oldStartIdx = 0; let newStartIdx = 0; let oldEndIdx = oldCh.length - 1; let oldStartVnode = oldCh[0]; let oldEndVnode = oldCh[oldEndIdx]; let newEndIdx = newCh.length - 1; let newStartVnode = newCh[0]; let newEndVnode = newCh[newEndIdx]; let oldKeyToIdx, idxInOld, elmToMove, refElm; // removeOnly is a special flag used only by <transition-group> // to ensure removed elements stay in correct relative positions // during leaving transitions const canMove = !removeOnly; while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) { if (isUndef(oldStartVnode)) { oldStartVnode = oldCh[++oldStartIdx]; // Vnode has been moved left } else if (isUndef(oldEndVnode)) { oldEndVnode = oldCh[--oldEndIdx]; } else if (sameVnode(oldStartVnode, newStartVnode)) { patchVnode(oldStartVnode, newStartVnode, insertedVnodeQueue); oldStartVnode = oldCh[++oldStartIdx]; newStartVnode = newCh[++newStartIdx]; } else if (sameVnode(oldEndVnode, newEndVnode)) { patchVnode(oldEndVnode, newEndVnode, insertedVnodeQueue); oldEndVnode = oldCh[--oldEndIdx]; newEndVnode = newCh[--newEndIdx]; } else if (sameVnode(oldStartVnode, newEndVnode)) { // Vnode moved right patchVnode(oldStartVnode, newEndVnode, insertedVnodeQueue); canMove && nodeOps.insertBefore(parentElm, oldStartVnode.elm, nodeOps.nextSibling(oldEndVnode.elm)); oldStartVnode = oldCh[++oldStartIdx]; newEndVnode = newCh[--newEndIdx]; } else if (sameVnode(oldEndVnode, newStartVnode)) { // Vnode moved left patchVnode(oldEndVnode, newStartVnode, insertedVnodeQueue); canMove && nodeOps.insertBefore(parentElm, oldEndVnode.elm, oldStartVnode.elm); oldEndVnode = oldCh[--oldEndIdx]; newStartVnode = newCh[++newStartIdx]; } else { if (isUndef(oldKeyToIdx)) { oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx); } idxInOld = isDef(newStartVnode.key) ? oldKeyToIdx[newStartVnode.key] : null; if (isUndef(idxInOld)) { // New element createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm); newStartVnode = newCh[++newStartIdx]; } else { elmToMove = oldCh[idxInOld]; /* istanbul ignore if */ if ('development' !== 'production' && !elmToMove) { warn( 'It seems there are duplicate keys that is causing an update error. ' + 'Make sure each v-for item has a unique key.' ); } if (sameVnode(elmToMove, newStartVnode)) { patchVnode(elmToMove, newStartVnode, insertedVnodeQueue); oldCh[idxInOld] = undefined; canMove && nodeOps.insertBefore(parentElm, elmToMove.elm, oldStartVnode.elm); newStartVnode = newCh[++newStartIdx]; } else { // same key but different element. treat as new element createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm); newStartVnode = newCh[++newStartIdx]; } } } } if (oldStartIdx > oldEndIdx) { refElm = isUndef(newCh[newEndIdx + 1]) ? null : newCh[newEndIdx + 1].elm; addVnodes(parentElm, refElm, newCh, newStartIdx, newEndIdx, insertedVnodeQueue); } else if (newStartIdx > newEndIdx) { removeVnodes(parentElm, oldCh, oldStartIdx, oldEndIdx); } } function patchVnode(oldVnode, vnode, insertedVnodeQueue, removeOnly) { if (oldVnode === vnode) { return; } const elm = vnode.elm = oldVnode.elm; if (isTrue(oldVnode.isAsyncPlaceholder)) { if (isDef(vnode.asyncFactory.resolved)) { hydrate(oldVnode.elm, vnode, insertedVnodeQueue); } else { vnode.isAsyncPlaceholder = true; } return; } // reuse element for static trees. // note we only do this if the vnode is cloned - // if the new node is not cloned it means the render functions have been // reset by the hot-reload-api and we need to do a proper re-render. if (isTrue(vnode.isStatic) && isTrue(oldVnode.isStatic) && vnode.key === oldVnode.key && (isTrue(vnode.isCloned) || isTrue(vnode.isOnce)) ) { vnode.componentInstance = oldVnode.componentInstance; return; } let i; const data = vnode.data; if (isDef(data) && isDef(i = data.hook) && isDef(i = i.prepatch)) { i(oldVnode, vnode); } const oldCh = oldVnode.children; const ch = vnode.children; if (isDef(data) && isPatchable(vnode)) { for (i = 0; i < cbs.update.length; ++i) { cbs.update[i](oldVnode, vnode); } if (isDef(i = data.hook) && isDef(i = i.update)) { i(oldVnode, vnode); } } if (isUndef(vnode.text)) { if (isDef(oldCh) && isDef(ch)) { if (oldCh !== ch) { updateChildren(elm, oldCh, ch, insertedVnodeQueue, removeOnly); } } else if (isDef(ch)) { if (isDef(oldVnode.text)) { nodeOps.setTextContent(elm, ''); } addVnodes(elm, null, ch, 0, ch.length - 1, insertedVnodeQueue); } else if (isDef(oldCh)) { removeVnodes(elm, oldCh, 0, oldCh.length - 1); } else if (isDef(oldVnode.text)) { nodeOps.setTextContent(elm, ''); } } else if (oldVnode.text !== vnode.text) { nodeOps.setTextContent(elm, vnode.text); } if (isDef(data)) { if (isDef(i = data.hook) && isDef(i = i.postpatch)) { i(oldVnode, vnode); } } } function invokeInsertHook(vnode, queue, initial) { // delay insert hooks for component root nodes, invoke them after the // element is really inserted if (isTrue(initial) && isDef(vnode.parent)) { vnode.parent.data.pendingInsert = queue; } else { for (let i = 0; i < queue.length; ++i) { queue[i].data.hook.insert(queue[i]); } } } let bailed = false; // list of modules that can skip create hook during hydration because they // are already rendered on the client or has no need for initialization const isRenderedModule = makeMap('attrs,style,class,staticClass,staticStyle,key'); // Note: this is a browser-only function so we can assume elms are DOM nodes. function hydrate(elm, vnode, insertedVnodeQueue) { if (isTrue(vnode.isComment) && isDef(vnode.asyncFactory)) { vnode.elm = elm; vnode.isAsyncPlaceholder = true; return true; } { if (!assertNodeMatch(elm, vnode)) { return false; } } vnode.elm = elm; const tag = vnode.tag; const data = vnode.data; const children = vnode.children; if (isDef(data)) { if (isDef(i = data.hook) && isDef(i = i.init)) { i(vnode, true /* hydrating */); } if (isDef(i = vnode.componentInstance)) { // child component. it should have hydrated its own tree. initComponent(vnode, insertedVnodeQueue); return true; } } if (isDef(tag)) { if (isDef(children)) { // empty element, allow client to pick up and populate children if (!elm.hasChildNodes()) { createChildren(vnode, children, insertedVnodeQueue); } else { let childrenMatch = true; let childNode = elm.firstChild; for (let i$1 = 0; i$1 < children.length; i$1++) { if (!childNode || !hydrate(childNode, children[i$1], insertedVnodeQueue)) { childrenMatch = false; break; } childNode = childNode.nextSibling; } // if childNode is not null, it means the actual childNodes list is // longer than the virtual children list. if (!childrenMatch || childNode) { if ('development' !== 'production' && typeof console !== 'undefined' && !bailed ) { bailed = true; console.warn('Parent: ', elm); console.warn('Mismatching childNodes vs. VNodes: ', elm.childNodes, children); } return false; } } } if (isDef(data)) { for (const key in data) { if (!isRenderedModule(key)) { invokeCreateHooks(vnode, insertedVnodeQueue); break; } } } } else if (elm.data !== vnode.text) { elm.data = vnode.text; } return true; } function assertNodeMatch(node, vnode) { if (isDef(vnode.tag)) { return ( vnode.tag.indexOf('vue-component') === 0 || vnode.tag.toLowerCase() === (node.tagName && node.tagName.toLowerCase()) ); } return node.nodeType === (vnode.isComment ? 8 : 3); } return function patch(oldVnode, vnode, hydrating, removeOnly, parentElm, refElm) { if (isUndef(vnode)) { if (isDef(oldVnode)) { invokeDestroyHook(oldVnode); } return; } let isInitialPatch = false; const insertedVnodeQueue = []; if (isUndef(oldVnode)) { // empty mount (likely as component), create new root element isInitialPatch = true; createElm(vnode, insertedVnodeQueue, parentElm, refElm); } else { const isRealElement = isDef(oldVnode.nodeType); if (!isRealElement && sameVnode(oldVnode, vnode)) { // patch existing root node patchVnode(oldVnode, vnode, insertedVnodeQueue, removeOnly); } else { if (isRealElement) { // mounting to a real element // check if this is server-rendered content and if we can perform // a successful hydration. if (oldVnode.nodeType === 1 && oldVnode.hasAttribute(SSR_ATTR)) { oldVnode.removeAttribute(SSR_ATTR); hydrating = true; } if (isTrue(hydrating)) { if (hydrate(oldVnode, vnode, insertedVnodeQueue)) { invokeInsertHook(vnode, insertedVnodeQueue, true); return oldVnode; } warn( 'The client-side rendered virtual DOM tree is not matching ' + 'server-rendered content. This is likely caused by incorrect ' + 'HTML markup, for example nesting block-level elements inside ' + '<p>, or missing <tbody>. Bailing hydration and performing ' + 'full client-side render.' ); } // either not server-rendered, or hydration failed. // create an empty node and replace it oldVnode = emptyNodeAt(oldVnode); } // replacing existing element const oldElm = oldVnode.elm; const parentElm$1 = nodeOps.parentNode(oldElm); createElm( vnode, insertedVnodeQueue, // extremely rare edge case: do not insert if old element is in a // leaving transition. Only happens when combining transition + // keep-alive + HOCs. (#4590) oldElm._leaveCb ? null : parentElm$1, nodeOps.nextSibling(oldElm) ); if (isDef(vnode.parent)) { // component root element replaced. // update parent placeholder node element, recursively let ancestor = vnode.parent; while (ancestor) { ancestor.elm = vnode.elm; ancestor = ancestor.parent; } if (isPatchable(vnode)) { for (let i = 0; i < cbs.create.length; ++i) { cbs.create[i](emptyNode, vnode.parent); } } } if (isDef(parentElm$1)) { removeVnodes(parentElm$1, [ oldVnode ], 0, 0); } else if (isDef(oldVnode.tag)) { invokeDestroyHook(oldVnode); } } } invokeInsertHook(vnode, insertedVnodeQueue, isInitialPatch); return vnode.elm; }; } /* */ const directives = { create: updateDirectives, update: updateDirectives, destroy: function unbindDirectives(vnode) { updateDirectives(vnode, emptyNode); }, }; function updateDirectives(oldVnode, vnode) { if (oldVnode.data.directives || vnode.data.directives) { _update(oldVnode, vnode); } } function _update(oldVnode, vnode) { const isCreate = oldVnode === emptyNode; const isDestroy = vnode === emptyNode; const oldDirs = normalizeDirectives$1(oldVnode.data.directives, oldVnode.context); const newDirs = normalizeDirectives$1(vnode.data.directives, vnode.context); const dirsWithInsert = []; const dirsWithPostpatch = []; let key, oldDir, dir; for (key in newDirs) { oldDir = oldDirs[key]; dir = newDirs[key]; if (!oldDir) { // new directive, bind callHook$1(dir, 'bind', vnode, oldVnode); if (dir.def && dir.def.inserted) { dirsWithInsert.push(dir); } } else { // existing directive, update dir.oldValue = oldDir.value; callHook$1(dir, 'update', vnode, oldVnode); if (dir.def && dir.def.componentUpdated) { dirsWithPostpatch.push(dir); } } } if (dirsWithInsert.length) { const callInsert = function() { for (let i = 0; i < dirsWithInsert.length; i++) { callHook$1(dirsWithInsert[i], 'inserted', vnode, oldVnode); } }; if (isCreate) { mergeVNodeHook(vnode.data.hook || (vnode.data.hook = {}), 'insert', callInsert); } else { callInsert(); } } if (dirsWithPostpatch.length) { mergeVNodeHook(vnode.data.hook || (vnode.data.hook = {}), 'postpatch', function() { for (let i = 0; i < dirsWithPostpatch.length; i++) { callHook$1(dirsWithPostpatch[i], 'componentUpdated', vnode, oldVnode); } }); } if (!isCreate) { for (key in oldDirs) { if (!newDirs[key]) { // no longer present, unbind callHook$1(oldDirs[key], 'unbind', oldVnode, oldVnode, isDestroy); } } } } const emptyModifiers = Object.create(null); function normalizeDirectives$1( dirs, vm ) { const res = Object.create(null); if (!dirs) { return res; } let i, dir; for (i = 0; i < dirs.length; i++) { dir = dirs[i]; if (!dir.modifiers) { dir.modifiers = emptyModifiers; } res[getRawDirName(dir)] = dir; dir.def = resolveAsset(vm.$options, 'directives', dir.name, true); } return res; } function getRawDirName(dir) { return dir.rawName || ((dir.name) + '.' + (Object.keys(dir.modifiers || {}).join('.'))); } function callHook$1(dir, hook, vnode, oldVnode, isDestroy) { const fn = dir.def && dir.def[hook]; if (fn) { try { fn(vnode.elm, dir, vnode, oldVnode, isDestroy); } catch (e) { handleError(e, vnode.context, ('directive ' + (dir.name) + ' ' + hook + ' hook')); } } } const baseModules = [ ref, directives, ]; /* */ function updateAttrs(oldVnode, vnode) { const opts = vnode.componentOptions; if (isDef(opts) && opts.Ctor.options.inheritAttrs === false) { return; } if (isUndef(oldVnode.data.attrs) && isUndef(vnode.data.attrs)) { return; } let key, cur, old; const elm = vnode.elm; const oldAttrs = oldVnode.data.attrs || {}; let attrs = vnode.data.attrs || {}; // clone observed objects, as the user probably wants to mutate it if (isDef(attrs.__ob__)) { attrs = vnode.data.attrs = extend({}, attrs); } for (key in attrs) { cur = attrs[key]; old = oldAttrs[key]; if (old !== cur) { setAttr(elm, key, cur); } } // #4391: in IE9, setting type can reset value for input[type=radio] /* istanbul ignore if */ if (isIE9 && attrs.value !== oldAttrs.value) { setAttr(elm, 'value', attrs.value); } for (key in oldAttrs) { if (isUndef(attrs[key])) { if (isXlink(key)) { elm.removeAttributeNS(xlinkNS, getXlinkProp(key)); } else if (!isEnumeratedAttr(key)) { elm.removeAttribute(key); } } } } function setAttr(el, key, value) { if (isBooleanAttr(key)) { // set attribute for blank value // e.g. <option disabled>Select one</option> if (isFalsyAttrValue(value)) { el.removeAttribute(key); } else { el.setAttribute(key, key); } } else if (isEnumeratedAttr(key)) { el.setAttribute(key, isFalsyAttrValue(value) || value === 'false' ? 'false' : 'true'); } else if (isXlink(key)) { if (isFalsyAttrValue(value)) { el.removeAttributeNS(xlinkNS, getXlinkProp(key)); } else { el.setAttributeNS(xlinkNS, key, value); } } else { if (isFalsyAttrValue(value)) { el.removeAttribute(key); } else { el.setAttribute(key, value); } } } const attrs = { create: updateAttrs, update: updateAttrs, }; /* */ function updateClass(oldVnode, vnode) { const el = vnode.elm; const data = vnode.data; const oldData = oldVnode.data; if ( isUndef(data.staticClass) && isUndef(data.class) && ( isUndef(oldData) || ( isUndef(oldData.staticClass) && isUndef(oldData.class) ) ) ) { return; } let cls = genClassForVnode(vnode); // handle transition classes const transitionClass = el._transitionClasses; if (isDef(transitionClass)) { cls = concat(cls, stringifyClass(transitionClass)); } // set the class if (cls !== el._prevClass) { el.setAttribute('class', cls); el._prevClass = cls; } } const klass = { create: updateClass, update: updateClass, }; /* */ const validDivisionCharRE = /[\w).+\-_$\]]/; function parseFilters(exp) { let inSingle = false; let inDouble = false; let inTemplateString = false; let inRegex = false; let curly = 0; let square = 0; let paren = 0; let lastFilterIndex = 0; let c, prev, i, expression, filters; for (i = 0; i < exp.length; i++) { prev = c; c = exp.charCodeAt(i); if (inSingle) { if (c === 0x27 && prev !== 0x5C) { inSingle = false; } } else if (inDouble) { if (c === 0x22 && prev !== 0x5C) { inDouble = false; } } else if (inTemplateString) { if (c === 0x60 && prev !== 0x5C) { inTemplateString = false; } } else if (inRegex) { if (c === 0x2f && prev !== 0x5C) { inRegex = false; } } else if ( c === 0x7C && // pipe exp.charCodeAt(i + 1) !== 0x7C && exp.charCodeAt(i - 1) !== 0x7C && !curly && !square && !paren ) { if (expression === undefined) { // first filter, end of expression lastFilterIndex = i + 1; expression = exp.slice(0, i).trim(); } else { pushFilter(); } } else { switch (c) { case 0x22: inDouble = true; break; // " case 0x27: inSingle = true; break; // ' case 0x60: inTemplateString = true; break; // ` case 0x28: paren++; break; // ( case 0x29: paren--; break; // ) case 0x5B: square++; break; // [ case 0x5D: square--; break; // ] case 0x7B: curly++; break; // { case 0x7D: curly--; break; // } } if (c === 0x2f) { // / let j = i - 1; let p = (void 0); // find first non-whitespace prev char for (; j >= 0; j--) { p = exp.charAt(j); if (p !== ' ') { break; } } if (!p || !validDivisionCharRE.test(p)) { inRegex = true; } } } } if (expression === undefined) { expression = exp.slice(0, i).trim(); } else if (lastFilterIndex !== 0) { pushFilter(); } function pushFilter() { (filters || (filters = [])).push(exp.slice(lastFilterIndex, i).trim()); lastFilterIndex = i + 1; } if (filters) { for (i = 0; i < filters.length; i++) { expression = wrapFilter(expression, filters[i]); } } return expression; } function wrapFilter(exp, filter) { const i = filter.indexOf('('); if (i < 0) { // _f: resolveFilter return ('_f("' + filter + '")(' + exp + ')'); } const name = filter.slice(0, i); const args = filter.slice(i + 1); return ('_f("' + name + '")(' + exp + ',' + args); } /* */ function baseWarn(msg) { console.error(('[Vue compiler]: ' + msg)); } function pluckModuleFunction( modules, key ) { return modules ? modules.map(function(m) { return m[key]; }).filter(function(_) { return _; }) : []; } function addProp(el, name, value) { (el.props || (el.props = [])).push({ name, value, }); } function addAttr(el, name, value) { (el.attrs || (el.attrs = [])).push({ name, value, }); } function addDirective( el, name, rawName, value, arg, modifiers ) { (el.directives || (el.directives = [])).push({ name, rawName, value, arg, modifiers, }); } function addHandler( el, name, value, modifiers, important, warn ) { // warn prevent and passive modifier /* istanbul ignore if */ if ( 'development' !== 'production' && warn && modifiers && modifiers.prevent && modifiers.passive ) { warn( 'passive and prevent can\'t be used together. ' + 'Passive handler can\'t prevent default event.' ); } // check capture modifier if (modifiers && modifiers.capture) { delete modifiers.capture; name = '!' + name; // mark the event as captured } if (modifiers && modifiers.once) { delete modifiers.once; name = '~' + name; // mark the event as once } /* istanbul ignore if */ if (modifiers && modifiers.passive) { delete modifiers.passive; name = '&' + name; // mark the event as passive } let events; if (modifiers && modifiers.native) { delete modifiers.native; events = el.nativeEvents || (el.nativeEvents = {}); } else { events = el.events || (el.events = {}); } const newHandler = { value, modifiers, }; const handlers = events[name]; /* istanbul ignore if */ if (Array.isArray(handlers)) { important ? handlers.unshift(newHandler) : handlers.push(newHandler); } else if (handlers) { events[name] = important ? [ newHandler, handlers ] : [ handlers, newHandler ]; } else { events[name] = newHandler; } } function getBindingAttr( el, name, getStatic ) { const dynamicValue = getAndRemoveAttr(el, ':' + name) || getAndRemoveAttr(el, 'v-bind:' + name); if (dynamicValue != null) { return parseFilters(dynamicValue); } else if (getStatic !== false) { const staticValue = getAndRemoveAttr(el, name); if (staticValue != null) { return JSON.stringify(staticValue); } } } function getAndRemoveAttr(el, name) { let val; if ((val = el.attrsMap[name]) != null) { const list = el.attrsList; for (let i = 0, l = list.length; i < l; i++) { if (list[i].name === name) { list.splice(i, 1); break; } } } return val; } /* */ /** * Cross-platform code generation for component v-model */ function genComponentModel( el, value, modifiers ) { const ref = modifiers || {}; const number = ref.number; const trim = ref.trim; const baseValueExpression = '$$v'; let valueExpression = baseValueExpression; if (trim) { valueExpression = '(typeof ' + baseValueExpression + " === 'string'" + '? ' + baseValueExpression + '.trim()' + ': ' + baseValueExpression + ')'; } if (number) { valueExpression = '_n(' + valueExpression + ')'; } const assignment = genAssignmentCode(value, valueExpression); el.model = { value: ('(' + value + ')'), expression: ('"' + value + '"'), callback: ('function (' + baseValueExpression + ') {' + assignment + '}'), }; } /** * Cross-platform codegen helper for generating v-model value assignment code. */ function genAssignmentCode( value, assignment ) { const modelRs = parseModel(value); if (modelRs.idx === null) { return (value + '=' + assignment); } return ('$set(' + (modelRs.exp) + ', ' + (modelRs.idx) + ', ' + assignment + ')'); } /** * parse directive model to do the array update transform. a[idx] = val => $$a.splice($$idx, 1, val) * * for loop possible cases: * * - test * - test[idx] * - test[test1[idx]] * - test["a"][idx] * - xxx.test[a[a].test1[idx]] * - test.xxx.a["asa"][test1[idx]] * */ let len; let str; let chr; let index$1; let expressionPos; let expressionEndPos; function parseModel(val) { str = val; len = str.length; index$1 = expressionPos = expressionEndPos = 0; if (val.indexOf('[') < 0 || val.lastIndexOf(']') < len - 1) { return { exp: val, idx: null, }; } while (!eof()) { chr = next(); /* istanbul ignore if */ if (isStringStart(chr)) { parseString(chr); } else if (chr === 0x5B) { parseBracket(chr); } } return { exp: val.substring(0, expressionPos), idx: val.substring(expressionPos + 1, expressionEndPos), }; } function next() { return str.charCodeAt(++index$1); } function eof() { return index$1 >= len; } function isStringStart(chr) { return chr === 0x22 || chr === 0x27; } function parseBracket(chr) { let inBracket = 1; expressionPos = index$1; while (!eof()) { chr = next(); if (isStringStart(chr)) { parseString(chr); continue; } if (chr === 0x5B) { inBracket++; } if (chr === 0x5D) { inBracket--; } if (inBracket === 0) { expressionEndPos = index$1; break; } } } function parseString(chr) { const stringQuote = chr; while (!eof()) { chr = next(); if (chr === stringQuote) { break; } } } /* */ let warn$1; // in some cases, the event used has to be determined at runtime // so we used some reserved tokens during compile. const RANGE_TOKEN = '__r'; const CHECKBOX_RADIO_TOKEN = '__c'; function model( el, dir, _warn ) { warn$1 = _warn; const value = dir.value; const modifiers = dir.modifiers; const tag = el.tag; const type = el.attrsMap.type; { const dynamicType = el.attrsMap['v-bind:type'] || el.attrsMap[':type']; if (tag === 'input' && dynamicType) { warn$1( '<input :type="' + dynamicType + '" v-model="' + value + '">:\n' + 'v-model does not support dynamic input types. Use v-if branches instead.' ); } // inputs with type="file" are read only and setting the input's // value will throw an error. if (tag === 'input' && type === 'file') { warn$1( '<' + (el.tag) + ' v-model="' + value + '" type="file">:\n' + 'File inputs are read only. Use a v-on:change listener instead.' ); } } if (el.component) { genComponentModel(el, value, modifiers); // component v-model doesn't need extra runtime return false; } else if (tag === 'select') { genSelect(el, value, modifiers); } else if (tag === 'input' && type === 'checkbox') { genCheckboxModel(el, value, modifiers); } else if (tag === 'input' && type === 'radio') { genRadioModel(el, value, modifiers); } else if (tag === 'input' || tag === 'textarea') { genDefaultModel(el, value, modifiers); } else if (!config.isReservedTag(tag)) { genComponentModel(el, value, modifiers); // component v-model doesn't need extra runtime return false; } else { warn$1( '<' + (el.tag) + ' v-model="' + value + '">: ' + 'v-model is not supported on this element type. ' + 'If you are working with contenteditable, it\'s recommended to ' + 'wrap a library dedicated for that purpose inside a custom component.' ); } // ensure runtime directive metadata return true; } function genCheckboxModel( el, value, modifiers ) { const number = modifiers && modifiers.number; const valueBinding = getBindingAttr(el, 'value') || 'null'; const trueValueBinding = getBindingAttr(el, 'true-value') || 'true'; const falseValueBinding = getBindingAttr(el, 'false-value') || 'false'; addProp(el, 'checked', 'Array.isArray(' + value + ')' + '?_i(' + value + ',' + valueBinding + ')>-1' + ( trueValueBinding === 'true' ? (':(' + value + ')') : (':_q(' + value + ',' + trueValueBinding + ')') ) ); addHandler(el, CHECKBOX_RADIO_TOKEN, 'var $$a=' + value + ',' + '$$el=$event.target,' + '$$c=$$el.checked?(' + trueValueBinding + '):(' + falseValueBinding + ');' + 'if(Array.isArray($$a)){' + 'var $$v=' + (number ? '_n(' + valueBinding + ')' : valueBinding) + ',' + '$$i=_i($$a,$$v);' + 'if($$c){$$i<0&&(' + value + '=$$a.concat($$v))}' + 'else{$$i>-1&&(' + value + '=$$a.slice(0,$$i).concat($$a.slice($$i+1)))}' + '}else{' + (genAssignmentCode(value, '$$c')) + '}', null, true ); } function genRadioModel( el, value, modifiers ) { const number = modifiers && modifiers.number; let valueBinding = getBindingAttr(el, 'value') || 'null'; valueBinding = number ? ('_n(' + valueBinding + ')') : valueBinding; addProp(el, 'checked', ('_q(' + value + ',' + valueBinding + ')')); addHandler(el, CHECKBOX_RADIO_TOKEN, genAssignmentCode(value, valueBinding), null, true); } function genSelect( el, value, modifiers ) { const number = modifiers && modifiers.number; const selectedVal = 'Array.prototype.filter' + '.call($event.target.options,function(o){return o.selected})' + '.map(function(o){var val = "_value" in o ? o._value : o.value;' + 'return ' + (number ? '_n(val)' : 'val') + '})'; const assignment = '$event.target.multiple ? $$selectedVal : $$selectedVal[0]'; let code = 'var $$selectedVal = ' + selectedVal + ';'; code = code + ' ' + (genAssignmentCode(value, assignment)); addHandler(el, 'change', code, null, true); } function genDefaultModel( el, value, modifiers ) { const type = el.attrsMap.type; const ref = modifiers || {}; const lazy = ref.lazy; const number = ref.number; const trim = ref.trim; const needCompositionGuard = !lazy && type !== 'range'; const event = lazy ? 'change' : type === 'range' ? RANGE_TOKEN : 'input'; let valueExpression = '$event.target.value'; if (trim) { valueExpression = '$event.target.value.trim()'; } if (number) { valueExpression = '_n(' + valueExpression + ')'; } let code = genAssignmentCode(value, valueExpression); if (needCompositionGuard) { code = 'if($event.target.composing)return;' + code; } addProp(el, 'value', ('(' + value + ')')); addHandler(el, event, code, null, true); if (trim || number) { addHandler(el, 'blur', '$forceUpdate()'); } } /* */ // normalize v-model event tokens that can only be determined at runtime. // it's important to place the event as the first in the array because // the whole point is ensuring the v-model callback gets called before // user-attached handlers. function normalizeEvents(on) { let event; /* istanbul ignore if */ if (isDef(on[RANGE_TOKEN])) { // IE input[type=range] only supports `change` event event = isIE ? 'change' : 'input'; on[event] = [].concat(on[RANGE_TOKEN], on[event] || []); delete on[RANGE_TOKEN]; } if (isDef(on[CHECKBOX_RADIO_TOKEN])) { // Chrome fires microtasks in between click/change, leads to #4521 event = isChrome ? 'click' : 'change'; on[event] = [].concat(on[CHECKBOX_RADIO_TOKEN], on[event] || []); delete on[CHECKBOX_RADIO_TOKEN]; } } let target$1; function add$1( event, handler, once$$1, capture, passive ) { if (once$$1) { const oldHandler = handler; const _target = target$1; // save current target element in closure handler = function(ev) { const res = arguments.length === 1 ? oldHandler(ev) : oldHandler.apply(null, arguments); if (res !== null) { remove$2(event, handler, capture, _target); } }; } target$1.addEventListener( event, handler, supportsPassive ? { capture, passive, } : capture ); } function remove$2( event, handler, capture, _target ) { (_target || target$1).removeEventListener(event, handler, capture); } function updateDOMListeners(oldVnode, vnode) { const isComponentRoot = isDef(vnode.componentOptions); let oldOn = isComponentRoot ? oldVnode.data.nativeOn : oldVnode.data.on; let on = isComponentRoot ? vnode.data.nativeOn : vnode.data.on; if (isUndef(oldOn) && isUndef(on)) { return; } on = on || {}; oldOn = oldOn || {}; target$1 = vnode.elm; normalizeEvents(on); updateListeners(on, oldOn, add$1, remove$2, vnode.context); } const events = { create: updateDOMListeners, update: updateDOMListeners, }; /* */ function updateDOMProps(oldVnode, vnode) { if (isUndef(oldVnode.data.domProps) && isUndef(vnode.data.domProps)) { return; } let key, cur; const elm = vnode.elm; const oldProps = oldVnode.data.domProps || {}; let props = vnode.data.domProps || {}; // clone observed objects, as the user probably wants to mutate it if (isDef(props.__ob__)) { props = vnode.data.domProps = extend({}, props); } for (key in oldProps) { if (isUndef(props[key])) { elm[key] = ''; } } for (key in props) { cur = props[key]; // ignore children if the node has textContent or innerHTML, // as these will throw away existing DOM nodes and cause removal errors // on subsequent patches (#3360) if (key === 'textContent' || key === 'innerHTML') { if (vnode.children) { vnode.children.length = 0; } if (cur === oldProps[key]) { continue; } } if (key === 'value') { // store value as _value as well since // non-string values will be stringified elm._value = cur; // avoid resetting cursor position when value is the same const strCur = isUndef(cur) ? '' : String(cur); if (shouldUpdateValue(elm, vnode, strCur)) { elm.value = strCur; } } else { elm[key] = cur; } } } // check platforms/web/util/attrs.js acceptValue function shouldUpdateValue( elm, vnode, checkVal ) { return (!elm.composing && ( vnode.tag === 'option' || isDirty(elm, checkVal) || isInputChanged(elm, checkVal) )); } function isDirty(elm, checkVal) { // return true when textbox (.number and .trim) loses focus and its value is // not equal to the updated value return document.activeElement !== elm && elm.value !== checkVal; } function isInputChanged(elm, newVal) { const value = elm.value; const modifiers = elm._vModifiers; // injected by v-model runtime if (isDef(modifiers) && modifiers.number) { return toNumber(value) !== toNumber(newVal); } if (isDef(modifiers) && modifiers.trim) { return value.trim() !== newVal.trim(); } return value !== newVal; } const domProps = { create: updateDOMProps, update: updateDOMProps, }; /* */ const parseStyleText = cached(function(cssText) { const res = {}; const listDelimiter = /;(?![^(]*\))/g; const propertyDelimiter = /:(.+)/; cssText.split(listDelimiter).forEach(function(item) { if (item) { const tmp = item.split(propertyDelimiter); tmp.length > 1 && (res[tmp[0].trim()] = tmp[1].trim()); } }); return res; }); // merge static and dynamic style data on the same vnode function normalizeStyleData(data) { const style = normalizeStyleBinding(data.style); // static style is pre-processed into an object during compilation // and is always a fresh object, so it's safe to merge into it return data.staticStyle ? extend(data.staticStyle, style) : style; } // normalize possible array / string values into Object function normalizeStyleBinding(bindingStyle) { if (Array.isArray(bindingStyle)) { return toObject(bindingStyle); } if (typeof bindingStyle === 'string') { return parseStyleText(bindingStyle); } return bindingStyle; } /** * parent component style should be after child's * so that parent component's style could override it */ function getStyle(vnode, checkChild) { const res = {}; let styleData; if (checkChild) { let childNode = vnode; while (childNode.componentInstance) { childNode = childNode.componentInstance._vnode; if (childNode.data && (styleData = normalizeStyleData(childNode.data))) { extend(res, styleData); } } } if ((styleData = normalizeStyleData(vnode.data))) { extend(res, styleData); } let parentNode = vnode; while ((parentNode = parentNode.parent)) { if (parentNode.data && (styleData = normalizeStyleData(parentNode.data))) { extend(res, styleData); } } return res; } /* */ const cssVarRE = /^--/; const importantRE = /\s*!important$/; const setProp = function(el, name, val) { /* istanbul ignore if */ if (cssVarRE.test(name)) { el.style.setProperty(name, val); } else if (importantRE.test(val)) { el.style.setProperty(name, val.replace(importantRE, ''), 'important'); } else { const normalizedName = normalize(name); if (Array.isArray(val)) { // Support values array created by autoprefixer, e.g. // {display: ["-webkit-box", "-ms-flexbox", "flex"]} // Set them one by one, and the browser will only set those it can recognize for (let i = 0, len = val.length; i < len; i++) { el.style[normalizedName] = val[i]; } } else { el.style[normalizedName] = val; } } }; const vendorNames = [ 'Webkit', 'Moz', 'ms' ]; let emptyStyle; var normalize = cached(function(prop) { emptyStyle = emptyStyle || document.createElement('div').style; prop = camelize(prop); if (prop !== 'filter' && (prop in emptyStyle)) { return prop; } const capName = prop.charAt(0).toUpperCase() + prop.slice(1); for (let i = 0; i < vendorNames.length; i++) { const name = vendorNames[i] + capName; if (name in emptyStyle) { return name; } } }); function updateStyle(oldVnode, vnode) { const data = vnode.data; const oldData = oldVnode.data; if (isUndef(data.staticStyle) && isUndef(data.style) && isUndef(oldData.staticStyle) && isUndef(oldData.style) ) { return; } let cur, name; const el = vnode.elm; const oldStaticStyle = oldData.staticStyle; const oldStyleBinding = oldData.normalizedStyle || oldData.style || {}; // if static style exists, stylebinding already merged into it when doing normalizeStyleData const oldStyle = oldStaticStyle || oldStyleBinding; const style = normalizeStyleBinding(vnode.data.style) || {}; // store normalized style under a different key for next diff // make sure to clone it if it's reactive, since the user likley wants // to mutate it. vnode.data.normalizedStyle = isDef(style.__ob__) ? extend({}, style) : style; const newStyle = getStyle(vnode, true); for (name in oldStyle) { if (isUndef(newStyle[name])) { setProp(el, name, ''); } } for (name in newStyle) { cur = newStyle[name]; if (cur !== oldStyle[name]) { // ie9 setting to null has no effect, must use empty string setProp(el, name, cur == null ? '' : cur); } } } const style = { create: updateStyle, update: updateStyle, }; /* */ /** * Add class with compatibility for SVG since classList is not supported on * SVG elements in IE */ function addClass(el, cls) { /* istanbul ignore if */ if (!cls || !(cls = cls.trim())) { return; } /* istanbul ignore else */ if (el.classList) { if (cls.indexOf(' ') > -1) { cls.split(/\s+/).forEach(function(c) { return el.classList.add(c); }); } else { el.classList.add(cls); } } else { const cur = ' ' + (el.getAttribute('class') || '') + ' '; if (cur.indexOf(' ' + cls + ' ') < 0) { el.setAttribute('class', (cur + cls).trim()); } } } /** * Remove class with compatibility for SVG since classList is not supported on * SVG elements in IE */ function removeClass(el, cls) { /* istanbul ignore if */ if (!cls || !(cls = cls.trim())) { return; } /* istanbul ignore else */ if (el.classList) { if (cls.indexOf(' ') > -1) { cls.split(/\s+/).forEach(function(c) { return el.classList.remove(c); }); } else { el.classList.remove(cls); } if (!el.classList.length) { el.removeAttribute('class'); } } else { let cur = ' ' + (el.getAttribute('class') || '') + ' '; const tar = ' ' + cls + ' '; while (cur.indexOf(tar) >= 0) { cur = cur.replace(tar, ' '); } cur = cur.trim(); if (cur) { el.setAttribute('class', cur); } else { el.removeAttribute('class'); } } } /* */ function resolveTransition(def$$1) { if (!def$$1) { return; } /* istanbul ignore else */ if (typeof def$$1 === 'object') { const res = {}; if (def$$1.css !== false) { extend(res, autoCssTransition(def$$1.name || 'v')); } extend(res, def$$1); return res; } else if (typeof def$$1 === 'string') { return autoCssTransition(def$$1); } } var autoCssTransition = cached(function(name) { return { enterClass: (name + '-enter'), enterToClass: (name + '-enter-to'), enterActiveClass: (name + '-enter-active'), leaveClass: (name + '-leave'), leaveToClass: (name + '-leave-to'), leaveActiveClass: (name + '-leave-active'), }; }); const hasTransition = inBrowser && !isIE9; const TRANSITION = 'transition'; const ANIMATION = 'animation'; // Transition property/event sniffing let transitionProp = 'transition'; let transitionEndEvent = 'transitionend'; let animationProp = 'animation'; let animationEndEvent = 'animationend'; if (hasTransition) { /* istanbul ignore if */ if (window.ontransitionend === undefined && window.onwebkittransitionend !== undefined ) { transitionProp = 'WebkitTransition'; transitionEndEvent = 'webkitTransitionEnd'; } if (window.onanimationend === undefined && window.onwebkitanimationend !== undefined ) { animationProp = 'WebkitAnimation'; animationEndEvent = 'webkitAnimationEnd'; } } // binding to window is necessary to make hot reload work in IE in strict mode const raf = inBrowser && window.requestAnimationFrame ? window.requestAnimationFrame.bind(window) : setTimeout; function nextFrame(fn) { raf(function() { raf(fn); }); } function addTransitionClass(el, cls) { const transitionClasses = el._transitionClasses || (el._transitionClasses = []); if (transitionClasses.indexOf(cls) < 0) { transitionClasses.push(cls); addClass(el, cls); } } function removeTransitionClass(el, cls) { if (el._transitionClasses) { remove(el._transitionClasses, cls); } removeClass(el, cls); } function whenTransitionEnds( el, expectedType, cb ) { const ref = getTransitionInfo(el, expectedType); const type = ref.type; const timeout = ref.timeout; const propCount = ref.propCount; if (!type) { return cb(); } const event = type === TRANSITION ? transitionEndEvent : animationEndEvent; let ended = 0; const end = function() { el.removeEventListener(event, onEnd); cb(); }; var onEnd = function(e) { if (e.target === el) { if (++ended >= propCount) { end(); } } }; setTimeout(function() { if (ended < propCount) { end(); } }, timeout + 1); el.addEventListener(event, onEnd); } const transformRE = /\b(transform|all)(,|$)/; function getTransitionInfo(el, expectedType) { const styles = window.getComputedStyle(el); const transitionDelays = styles[transitionProp + 'Delay'].split(', '); const transitionDurations = styles[transitionProp + 'Duration'].split(', '); const transitionTimeout = getTimeout(transitionDelays, transitionDurations); const animationDelays = styles[animationProp + 'Delay'].split(', '); const animationDurations = styles[animationProp + 'Duration'].split(', '); const animationTimeout = getTimeout(animationDelays, animationDurations); let type; let timeout = 0; let propCount = 0; /* istanbul ignore if */ if (expectedType === TRANSITION) { if (transitionTimeout > 0) { type = TRANSITION; timeout = transitionTimeout; propCount = transitionDurations.length; } } else if (expectedType === ANIMATION) { if (animationTimeout > 0) { type = ANIMATION; timeout = animationTimeout; propCount = animationDurations.length; } } else { timeout = Math.max(transitionTimeout, animationTimeout); type = timeout > 0 ? transitionTimeout > animationTimeout ? TRANSITION : ANIMATION : null; propCount = type ? type === TRANSITION ? transitionDurations.length : animationDurations.length : 0; } const hasTransform = type === TRANSITION && transformRE.test(styles[transitionProp + 'Property']); return { type, timeout, propCount, hasTransform, }; } function getTimeout(delays, durations) { /* istanbul ignore next */ while (delays.length < durations.length) { delays = delays.concat(delays); } return Math.max.apply(null, durations.map(function(d, i) { return toMs(d) + toMs(delays[i]); })); } function toMs(s) { return Number(s.slice(0, -1)) * 1000; } /* */ function enter(vnode, toggleDisplay) { const el = vnode.elm; // call leave callback now if (isDef(el._leaveCb)) { el._leaveCb.cancelled = true; el._leaveCb(); } const data = resolveTransition(vnode.data.transition); if (isUndef(data)) { return; } /* istanbul ignore if */ if (isDef(el._enterCb) || el.nodeType !== 1) { return; } const css = data.css; const type = data.type; const enterClass = data.enterClass; const enterToClass = data.enterToClass; const enterActiveClass = data.enterActiveClass; const appearClass = data.appearClass; const appearToClass = data.appearToClass; const appearActiveClass = data.appearActiveClass; const beforeEnter = data.beforeEnter; const enter = data.enter; const afterEnter = data.afterEnter; const enterCancelled = data.enterCancelled; const beforeAppear = data.beforeAppear; const appear = data.appear; const afterAppear = data.afterAppear; const appearCancelled = data.appearCancelled; const duration = data.duration; // activeInstance will always be the <transition> component managing this // transition. One edge case to check is when the <transition> is placed // as the root node of a child component. In that case we need to check // <transition>'s parent for appear check. let context = activeInstance; let transitionNode = activeInstance.$vnode; while (transitionNode && transitionNode.parent) { transitionNode = transitionNode.parent; context = transitionNode.context; } const isAppear = !context._isMounted || !vnode.isRootInsert; if (isAppear && !appear && appear !== '') { return; } const startClass = isAppear && appearClass ? appearClass : enterClass; const activeClass = isAppear && appearActiveClass ? appearActiveClass : enterActiveClass; const toClass = isAppear && appearToClass ? appearToClass : enterToClass; const beforeEnterHook = isAppear ? (beforeAppear || beforeEnter) : beforeEnter; const enterHook = isAppear ? (typeof appear === 'function' ? appear : enter) : enter; const afterEnterHook = isAppear ? (afterAppear || afterEnter) : afterEnter; const enterCancelledHook = isAppear ? (appearCancelled || enterCancelled) : enterCancelled; const explicitEnterDuration = toNumber( isObject(duration) ? duration.enter : duration ); if ('development' !== 'production' && explicitEnterDuration != null) { checkDuration(explicitEnterDuration, 'enter', vnode); } const expectsCSS = css !== false && !isIE9; const userWantsControl = getHookArgumentsLength(enterHook); var cb = el._enterCb = once(function() { if (expectsCSS) { removeTransitionClass(el, toClass); removeTransitionClass(el, activeClass); } if (cb.cancelled) { if (expectsCSS) { removeTransitionClass(el, startClass); } enterCancelledHook && enterCancelledHook(el); } else { afterEnterHook && afterEnterHook(el); } el._enterCb = null; }); if (!vnode.data.show) { // remove pending leave element on enter by injecting an insert hook mergeVNodeHook(vnode.data.hook || (vnode.data.hook = {}), 'insert', function() { const parent = el.parentNode; const pendingNode = parent && parent._pending && parent._pending[vnode.key]; if (pendingNode && pendingNode.tag === vnode.tag && pendingNode.elm._leaveCb ) { pendingNode.elm._leaveCb(); } enterHook && enterHook(el, cb); }); } // start enter transition beforeEnterHook && beforeEnterHook(el); if (expectsCSS) { addTransitionClass(el, startClass); addTransitionClass(el, activeClass); nextFrame(function() { addTransitionClass(el, toClass); removeTransitionClass(el, startClass); if (!cb.cancelled && !userWantsControl) { if (isValidDuration(explicitEnterDuration)) { setTimeout(cb, explicitEnterDuration); } else { whenTransitionEnds(el, type, cb); } } }); } if (vnode.data.show) { toggleDisplay && toggleDisplay(); enterHook && enterHook(el, cb); } if (!expectsCSS && !userWantsControl) { cb(); } } function leave(vnode, rm) { const el = vnode.elm; // call enter callback now if (isDef(el._enterCb)) { el._enterCb.cancelled = true; el._enterCb(); } const data = resolveTransition(vnode.data.transition); if (isUndef(data)) { return rm(); } /* istanbul ignore if */ if (isDef(el._leaveCb) || el.nodeType !== 1) { return; } const css = data.css; const type = data.type; const leaveClass = data.leaveClass; const leaveToClass = data.leaveToClass; const leaveActiveClass = data.leaveActiveClass; const beforeLeave = data.beforeLeave; const leave = data.leave; const afterLeave = data.afterLeave; const leaveCancelled = data.leaveCancelled; const delayLeave = data.delayLeave; const duration = data.duration; const expectsCSS = css !== false && !isIE9; const userWantsControl = getHookArgumentsLength(leave); const explicitLeaveDuration = toNumber( isObject(duration) ? duration.leave : duration ); if ('development' !== 'production' && isDef(explicitLeaveDuration)) { checkDuration(explicitLeaveDuration, 'leave', vnode); } var cb = el._leaveCb = once(function() { if (el.parentNode && el.parentNode._pending) { el.parentNode._pending[vnode.key] = null; } if (expectsCSS) { removeTransitionClass(el, leaveToClass); removeTransitionClass(el, leaveActiveClass); } if (cb.cancelled) { if (expectsCSS) { removeTransitionClass(el, leaveClass); } leaveCancelled && leaveCancelled(el); } else { rm(); afterLeave && afterLeave(el); } el._leaveCb = null; }); if (delayLeave) { delayLeave(performLeave); } else { performLeave(); } function performLeave() { // the delayed leave may have already been cancelled if (cb.cancelled) { return; } // record leaving element if (!vnode.data.show) { (el.parentNode._pending || (el.parentNode._pending = {}))[(vnode.key)] = vnode; } beforeLeave && beforeLeave(el); if (expectsCSS) { addTransitionClass(el, leaveClass); addTransitionClass(el, leaveActiveClass); nextFrame(function() { addTransitionClass(el, leaveToClass); removeTransitionClass(el, leaveClass); if (!cb.cancelled && !userWantsControl) { if (isValidDuration(explicitLeaveDuration)) { setTimeout(cb, explicitLeaveDuration); } else { whenTransitionEnds(el, type, cb); } } }); } leave && leave(el, cb); if (!expectsCSS && !userWantsControl) { cb(); } } } // only used in dev mode function checkDuration(val, name, vnode) { if (typeof val !== 'number') { warn( '<transition> explicit ' + name + ' duration is not a valid number - ' + 'got ' + (JSON.stringify(val)) + '.', vnode.context ); } else if (isNaN(val)) { warn( '<transition> explicit ' + name + ' duration is NaN - ' + 'the duration expression might be incorrect.', vnode.context ); } } function isValidDuration(val) { return typeof val === 'number' && !isNaN(val); } /** * Normalize a transition hook's argument length. The hook may be: * - a merged hook (invoker) with the original in .fns * - a wrapped component method (check ._length) * - a plain function (.length) */ function getHookArgumentsLength(fn) { if (isUndef(fn)) { return false; } const invokerFns = fn.fns; if (isDef(invokerFns)) { // invoker return getHookArgumentsLength( Array.isArray(invokerFns) ? invokerFns[0] : invokerFns ); } return (fn._length || fn.length) > 1; } function _enter(_, vnode) { if (vnode.data.show !== true) { enter(vnode); } } const transition = inBrowser ? { create: _enter, activate: _enter, remove: function remove$$1(vnode, rm) { /* istanbul ignore else */ if (vnode.data.show !== true) { leave(vnode, rm); } else { rm(); } }, } : {}; const platformModules = [ attrs, klass, events, domProps, style, transition, ]; /* */ // the directive module should be applied last, after all // built-in modules have been applied. const modules = platformModules.concat(baseModules); const patch = createPatchFunction({ nodeOps, modules, }); /** * Not type checking this file because flow doesn't like attaching * properties to Elements. */ const isTextInputType = makeMap('text,number,password,search,email,tel,url'); /* istanbul ignore if */ if (isIE9) { // http://www.matts411.com/post/internet-explorer-9-oninput/ document.addEventListener('selectionchange', function() { const el = document.activeElement; if (el && el.vmodel) { trigger(el, 'input'); } }); } const model$1 = { inserted: function inserted(el, binding, vnode) { if (vnode.tag === 'select') { const cb = function() { setSelected(el, binding, vnode.context); }; cb(); /* istanbul ignore if */ if (isIE || isEdge) { setTimeout(cb, 0); } } else if (vnode.tag === 'textarea' || isTextInputType(el.type)) { el._vModifiers = binding.modifiers; if (!binding.modifiers.lazy) { // Safari < 10.2 & UIWebView doesn't fire compositionend when // switching focus before confirming composition choice // this also fixes the issue where some browsers e.g. iOS Chrome // fires "change" instead of "input" on autocomplete. el.addEventListener('change', onCompositionEnd); if (!isAndroid) { el.addEventListener('compositionstart', onCompositionStart); el.addEventListener('compositionend', onCompositionEnd); } /* istanbul ignore if */ if (isIE9) { el.vmodel = true; } } } }, componentUpdated: function componentUpdated(el, binding, vnode) { if (vnode.tag === 'select') { setSelected(el, binding, vnode.context); // in case the options rendered by v-for have changed, // it's possible that the value is out-of-sync with the rendered options. // detect such cases and filter out values that no longer has a matching // option in the DOM. const needReset = el.multiple ? binding.value.some(function(v) { return hasNoMatchingOption(v, el.options); }) : binding.value !== binding.oldValue && hasNoMatchingOption(binding.value, el.options); if (needReset) { trigger(el, 'change'); } } }, }; function setSelected(el, binding, vm) { const value = binding.value; const isMultiple = el.multiple; if (isMultiple && !Array.isArray(value)) { 'development' !== 'production' && warn( '<select multiple v-model="' + (binding.expression) + '"> ' + 'expects an Array value for its binding, but got ' + (Object.prototype.toString.call(value).slice(8, -1)), vm ); return; } let selected, option; for (let i = 0, l = el.options.length; i < l; i++) { option = el.options[i]; if (isMultiple) { selected = looseIndexOf(value, getValue(option)) > -1; if (option.selected !== selected) { option.selected = selected; } } else { if (looseEqual(getValue(option), value)) { if (el.selectedIndex !== i) { el.selectedIndex = i; } return; } } } if (!isMultiple) { el.selectedIndex = -1; } } function hasNoMatchingOption(value, options) { for (let i = 0, l = options.length; i < l; i++) { if (looseEqual(getValue(options[i]), value)) { return false; } } return true; } function getValue(option) { return '_value' in option ? option._value : option.value; } function onCompositionStart(e) { e.target.composing = true; } function onCompositionEnd(e) { // prevent triggering an input event for no reason if (!e.target.composing) { return; } e.target.composing = false; trigger(e.target, 'input'); } function trigger(el, type) { const e = document.createEvent('HTMLEvents'); e.initEvent(type, true, true); el.dispatchEvent(e); } /* */ // recursively search for possible transition defined inside the component root function locateNode(vnode) { return vnode.componentInstance && (!vnode.data || !vnode.data.transition) ? locateNode(vnode.componentInstance._vnode) : vnode; } const show = { bind: function bind(el, ref, vnode) { const value = ref.value; vnode = locateNode(vnode); const transition$$1 = vnode.data && vnode.data.transition; const originalDisplay = el.__vOriginalDisplay = el.style.display === 'none' ? '' : el.style.display; if (value && transition$$1 && !isIE9) { vnode.data.show = true; enter(vnode, function() { el.style.display = originalDisplay; }); } else { el.style.display = value ? originalDisplay : 'none'; } }, update: function update(el, ref, vnode) { const value = ref.value; const oldValue = ref.oldValue; /* istanbul ignore if */ if (value === oldValue) { return; } vnode = locateNode(vnode); const transition$$1 = vnode.data && vnode.data.transition; if (transition$$1 && !isIE9) { vnode.data.show = true; if (value) { enter(vnode, function() { el.style.display = el.__vOriginalDisplay; }); } else { leave(vnode, function() { el.style.display = 'none'; }); } } else { el.style.display = value ? el.__vOriginalDisplay : 'none'; } }, unbind: function unbind( el, binding, vnode, oldVnode, isDestroy ) { if (!isDestroy) { el.style.display = el.__vOriginalDisplay; } }, }; const platformDirectives = { model: model$1, show, }; /* */ // Provides transition support for a single element/component. // supports transition mode (out-in / in-out) const transitionProps = { name: String, appear: Boolean, css: Boolean, mode: String, type: String, enterClass: String, leaveClass: String, enterToClass: String, leaveToClass: String, enterActiveClass: String, leaveActiveClass: String, appearClass: String, appearActiveClass: String, appearToClass: String, duration: [ Number, String, Object ], }; // in case the child is also an abstract component, e.g. <keep-alive> // we want to recursively retrieve the real component to be rendered function getRealChild(vnode) { const compOptions = vnode && vnode.componentOptions; if (compOptions && compOptions.Ctor.options.abstract) { return getRealChild(getFirstComponentChild(compOptions.children)); } return vnode; } function extractTransitionData(comp) { const data = {}; const options = comp.$options; // props for (const key in options.propsData) { data[key] = comp[key]; } // events. // extract listeners and pass them directly to the transition methods const listeners = options._parentListeners; for (const key$1 in listeners) { data[camelize(key$1)] = listeners[key$1]; } return data; } function placeholder(h, rawChild) { if (/\d-keep-alive$/.test(rawChild.tag)) { return h('keep-alive', { props: rawChild.componentOptions.propsData, }); } } function hasParentTransition(vnode) { while ((vnode = vnode.parent)) { if (vnode.data.transition) { return true; } } } function isSameChild(child, oldChild) { return oldChild.key === child.key && oldChild.tag === child.tag; } function isAsyncPlaceholder(node) { return node.isComment && node.asyncFactory; } const Transition = { name: 'transition', props: transitionProps, abstract: true, render: function render(h) { const this$1 = this; let children = this.$options._renderChildren; if (!children) { return; } // filter out text nodes (possible whitespaces) children = children.filter(function(c) { return c.tag || isAsyncPlaceholder(c); }); /* istanbul ignore if */ if (!children.length) { return; } // warn multiple elements if ('development' !== 'production' && children.length > 1) { warn( '<transition> can only be used on a single element. Use ' + '<transition-group> for lists.', this.$parent ); } const mode = this.mode; // warn invalid mode if ('development' !== 'production' && mode && mode !== 'in-out' && mode !== 'out-in' ) { warn( 'invalid <transition> mode: ' + mode, this.$parent ); } const rawChild = children[0]; // if this is a component root node and the component's // parent container node also has transition, skip. if (hasParentTransition(this.$vnode)) { return rawChild; } // apply transition data to child // use getRealChild() to ignore abstract components e.g. keep-alive const child = getRealChild(rawChild); /* istanbul ignore if */ if (!child) { return rawChild; } if (this._leaving) { return placeholder(h, rawChild); } // ensure a key that is unique to the vnode type and to this transition // component instance. This key will be used to remove pending leaving nodes // during entering. const id = '__transition-' + (this._uid) + '-'; child.key = child.key == null ? child.isComment ? id + 'comment' : id + child.tag : isPrimitive(child.key) ? (String(child.key).indexOf(id) === 0 ? child.key : id + child.key) : child.key; const data = (child.data || (child.data = {})).transition = extractTransitionData(this); const oldRawChild = this._vnode; const oldChild = getRealChild(oldRawChild); // mark v-show // so that the transition module can hand over the control to the directive if (child.data.directives && child.data.directives.some(function(d) { return d.name === 'show'; })) { child.data.show = true; } if ( oldChild && oldChild.data && !isSameChild(child, oldChild) && !isAsyncPlaceholder(oldChild) ) { // replace old child transition data with fresh one // important for dynamic transitions! const oldData = oldChild && (oldChild.data.transition = extend({}, data)); // handle transition mode if (mode === 'out-in') { // return placeholder node and queue update when leave finishes this._leaving = true; mergeVNodeHook(oldData, 'afterLeave', function() { this$1._leaving = false; this$1.$forceUpdate(); }); return placeholder(h, rawChild); } else if (mode === 'in-out') { if (isAsyncPlaceholder(child)) { return oldRawChild; } let delayedLeave; const performLeave = function() { delayedLeave(); }; mergeVNodeHook(data, 'afterEnter', performLeave); mergeVNodeHook(data, 'enterCancelled', performLeave); mergeVNodeHook(oldData, 'delayLeave', function(leave) { delayedLeave = leave; }); } } return rawChild; }, }; /* */ // Provides transition support for list items. // supports move transitions using the FLIP technique. // Because the vdom's children update algorithm is "unstable" - i.e. // it doesn't guarantee the relative positioning of removed elements, // we force transition-group to update its children into two passes: // in the first pass, we remove all nodes that need to be removed, // triggering their leaving transition; in the second pass, we insert/move // into the final desired state. This way in the second pass removed // nodes will remain where they should be. const props = extend({ tag: String, moveClass: String, }, transitionProps); delete props.mode; const TransitionGroup = { props, render: function render(h) { const tag = this.tag || this.$vnode.data.tag || 'span'; const map = Object.create(null); const prevChildren = this.prevChildren = this.children; const rawChildren = this.$slots.default || []; const children = this.children = []; const transitionData = extractTransitionData(this); for (let i = 0; i < rawChildren.length; i++) { const c = rawChildren[i]; if (c.tag) { if (c.key != null && String(c.key).indexOf('__vlist') !== 0) { children.push(c); map[c.key] = c; (c.data || (c.data = {})).transition = transitionData; } else { const opts = c.componentOptions; const name = opts ? (opts.Ctor.options.name || opts.tag || '') : c.tag; warn(('<transition-group> children must be keyed: <' + name + '>')); } } } if (prevChildren) { const kept = []; const removed = []; for (let i$1 = 0; i$1 < prevChildren.length; i$1++) { const c$1 = prevChildren[i$1]; c$1.data.transition = transitionData; c$1.data.pos = c$1.elm.getBoundingClientRect(); if (map[c$1.key]) { kept.push(c$1); } else { removed.push(c$1); } } this.kept = h(tag, null, kept); this.removed = removed; } return h(tag, null, children); }, beforeUpdate: function beforeUpdate() { // force removing pass this.__patch__( this._vnode, this.kept, false, // hydrating true // removeOnly (!important, avoids unnecessary moves) ); this._vnode = this.kept; }, updated: function updated() { const children = this.prevChildren; const moveClass = this.moveClass || ((this.name || 'v') + '-move'); if (!children.length || !this.hasMove(children[0].elm, moveClass)) { return; } // we divide the work into three loops to avoid mixing DOM reads and writes // in each iteration - which helps prevent layout thrashing. children.forEach(callPendingCbs); children.forEach(recordPosition); children.forEach(applyTranslation); // force reflow to put everything in position const body = document.body; var f = body.offsetHeight; // eslint-disable-line children.forEach(function(c) { if (c.data.moved) { const el = c.elm; const s = el.style; addTransitionClass(el, moveClass); s.transform = s.WebkitTransform = s.transitionDuration = ''; el.addEventListener(transitionEndEvent, el._moveCb = function cb(e) { if (!e || /transform$/.test(e.propertyName)) { el.removeEventListener(transitionEndEvent, cb); el._moveCb = null; removeTransitionClass(el, moveClass); } }); } }); }, methods: { hasMove: function hasMove(el, moveClass) { /* istanbul ignore if */ if (!hasTransition) { return false; } /* istanbul ignore if */ if (this._hasMove) { return this._hasMove; } // Detect whether an element with the move class applied has // CSS transitions. Since the element may be inside an entering // transition at this very moment, we make a clone of it and remove // all other transition classes applied to ensure only the move class // is applied. const clone = el.cloneNode(); if (el._transitionClasses) { el._transitionClasses.forEach(function(cls) { removeClass(clone, cls); }); } addClass(clone, moveClass); clone.style.display = 'none'; this.$el.appendChild(clone); const info = getTransitionInfo(clone); this.$el.removeChild(clone); return (this._hasMove = info.hasTransform); }, }, }; function callPendingCbs(c) { /* istanbul ignore if */ if (c.elm._moveCb) { c.elm._moveCb(); } /* istanbul ignore if */ if (c.elm._enterCb) { c.elm._enterCb(); } } function recordPosition(c) { c.data.newPos = c.elm.getBoundingClientRect(); } function applyTranslation(c) { const oldPos = c.data.pos; const newPos = c.data.newPos; const dx = oldPos.left - newPos.left; const dy = oldPos.top - newPos.top; if (dx || dy) { c.data.moved = true; const s = c.elm.style; s.transform = s.WebkitTransform = 'translate(' + dx + 'px,' + dy + 'px)'; s.transitionDuration = '0s'; } } const platformComponents = { Transition, TransitionGroup, }; /* */ // install platform specific utils Vue$3.config.mustUseProp = mustUseProp; Vue$3.config.isReservedTag = isReservedTag; Vue$3.config.isReservedAttr = isReservedAttr; Vue$3.config.getTagNamespace = getTagNamespace; Vue$3.config.isUnknownElement = isUnknownElement; // install platform runtime directives & components extend(Vue$3.options.directives, platformDirectives); extend(Vue$3.options.components, platformComponents); // install platform patch function Vue$3.prototype.__patch__ = inBrowser ? patch : noop; // public mount method Vue$3.prototype.$mount = function( el, hydrating ) { el = el && inBrowser ? query(el) : undefined; return mountComponent(this, el, hydrating); }; // devtools global hook /* istanbul ignore next */ setTimeout(function() { if (config.devtools) { if (devtools) { devtools.emit('init', Vue$3); } else if ('development' !== 'production' && isChrome) { console[console.info ? 'info' : 'log']( 'Download the Vue Devtools extension for a better development experience:\n' + 'https://github.com/vuejs/vue-devtools' ); } } if ('development' !== 'production' && config.productionTip !== false && inBrowser && typeof console !== 'undefined' ) { console[console.info ? 'info' : 'log']( 'You are running Vue in development mode.\n' + 'Make sure to turn on production mode when deploying for production.\n' + 'See more tips at https://vuejs.org/guide/deployment.html' ); } }, 0); /* */ // check whether current browser encodes a char inside attribute values function shouldDecode(content, encoded) { const div = document.createElement('div'); div.innerHTML = '<div a="' + content + '"/>'; return div.innerHTML.indexOf(encoded) > 0; } // #3663 // IE encodes newlines inside attribute values while other browsers don't const shouldDecodeNewlines = inBrowser ? shouldDecode('\n', '&#10;') : false; /* */ const defaultTagRE = /\{\{((?:.|\n)+?)\}\}/g; const regexEscapeRE = /[-.*+?^${}()|[\]\/\\]/g; const buildRegex = cached(function(delimiters) { const open = delimiters[0].replace(regexEscapeRE, '\\$&'); const close = delimiters[1].replace(regexEscapeRE, '\\$&'); return new RegExp(open + '((?:.|\\n)+?)' + close, 'g'); }); function parseText( text, delimiters ) { const tagRE = delimiters ? buildRegex(delimiters) : defaultTagRE; if (!tagRE.test(text)) { return; } const tokens = []; let lastIndex = tagRE.lastIndex = 0; let match, index; while ((match = tagRE.exec(text))) { index = match.index; // push text token if (index > lastIndex) { tokens.push(JSON.stringify(text.slice(lastIndex, index))); } // tag token const exp = parseFilters(match[1].trim()); tokens.push(('_s(' + exp + ')')); lastIndex = index + match[0].length; } if (lastIndex < text.length) { tokens.push(JSON.stringify(text.slice(lastIndex))); } return tokens.join('+'); } /* */ function transformNode(el, options) { const warn = options.warn || baseWarn; const staticClass = getAndRemoveAttr(el, 'class'); if ('development' !== 'production' && staticClass) { const expression = parseText(staticClass, options.delimiters); if (expression) { warn( 'class="' + staticClass + '": ' + 'Interpolation inside attributes has been removed. ' + 'Use v-bind or the colon shorthand instead. For example, ' + 'instead of <div class="{{ val }}">, use <div :class="val">.' ); } } if (staticClass) { el.staticClass = JSON.stringify(staticClass); } const classBinding = getBindingAttr(el, 'class', false /* getStatic */); if (classBinding) { el.classBinding = classBinding; } } function genData(el) { let data = ''; if (el.staticClass) { data += 'staticClass:' + (el.staticClass) + ','; } if (el.classBinding) { data += 'class:' + (el.classBinding) + ','; } return data; } const klass$1 = { staticKeys: [ 'staticClass' ], transformNode, genData, }; /* */ function transformNode$1(el, options) { const warn = options.warn || baseWarn; const staticStyle = getAndRemoveAttr(el, 'style'); if (staticStyle) { /* istanbul ignore if */ { const expression = parseText(staticStyle, options.delimiters); if (expression) { warn( 'style="' + staticStyle + '": ' + 'Interpolation inside attributes has been removed. ' + 'Use v-bind or the colon shorthand instead. For example, ' + 'instead of <div style="{{ val }}">, use <div :style="val">.' ); } } el.staticStyle = JSON.stringify(parseStyleText(staticStyle)); } const styleBinding = getBindingAttr(el, 'style', false /* getStatic */); if (styleBinding) { el.styleBinding = styleBinding; } } function genData$1(el) { let data = ''; if (el.staticStyle) { data += 'staticStyle:' + (el.staticStyle) + ','; } if (el.styleBinding) { data += 'style:(' + (el.styleBinding) + '),'; } return data; } const style$1 = { staticKeys: [ 'staticStyle' ], transformNode: transformNode$1, genData: genData$1, }; const modules$1 = [ klass$1, style$1, ]; /* */ function text(el, dir) { if (dir.value) { addProp(el, 'textContent', ('_s(' + (dir.value) + ')')); } } /* */ function html(el, dir) { if (dir.value) { addProp(el, 'innerHTML', ('_s(' + (dir.value) + ')')); } } const directives$1 = { model, text, html, }; /* */ const isUnaryTag = makeMap( 'area,base,br,col,embed,frame,hr,img,input,isindex,keygen,' + 'link,meta,param,source,track,wbr' ); // Elements that you can, intentionally, leave open // (and which close themselves) const canBeLeftOpenTag = makeMap( 'colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr,source' ); // HTML5 tags https://html.spec.whatwg.org/multipage/indices.html#elements-3 // Phrasing Content https://html.spec.whatwg.org/multipage/dom.html#phrasing-content const isNonPhrasingTag = makeMap( 'address,article,aside,base,blockquote,body,caption,col,colgroup,dd,' + 'details,dialog,div,dl,dt,fieldset,figcaption,figure,footer,form,' + 'h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,legend,li,menuitem,meta,' + 'optgroup,option,param,rp,rt,source,style,summary,tbody,td,tfoot,th,thead,' + 'title,tr,track' ); /* */ const baseOptions = { expectHTML: true, modules: modules$1, directives: directives$1, isPreTag, isUnaryTag, mustUseProp, canBeLeftOpenTag, isReservedTag, getTagNamespace, staticKeys: genStaticKeys(modules$1), }; /* */ let decoder; const he = { decode: function decode(html) { decoder = decoder || document.createElement('div'); decoder.innerHTML = html; return decoder.textContent; }, }; /** * Not type-checking this file because it's mostly vendor code. */ /* ! * HTML Parser By John Resig (ejohn.org) * Modified by Juriy "kangax" Zaytsev * Original code by Erik Arvidsson, Mozilla Public License * http://erik.eae.net/simplehtmlparser/simplehtmlparser.js */ // Regular Expressions for parsing tags and attributes const singleAttrIdentifier = /([^\s"'<>/=]+)/; const singleAttrAssign = /(?:=)/; const singleAttrValues = [ // attr value double quotes /"([^"]*)"+/.source, // attr value, single quotes /'([^']*)'+/.source, // attr value, no quotes /([^\s"'=<>`]+)/.source, ]; const attribute = new RegExp( '^\\s*' + singleAttrIdentifier.source + '(?:\\s*(' + singleAttrAssign.source + ')' + '\\s*(?:' + singleAttrValues.join('|') + '))?' ); // could use https://www.w3.org/TR/1999/REC-xml-names-19990114/#NT-QName // but for Vue templates we can enforce a simple charset const ncname = '[a-zA-Z_][\\w\\-\\.]*'; const qnameCapture = '((?:' + ncname + '\\:)?' + ncname + ')'; const startTagOpen = new RegExp('^<' + qnameCapture); const startTagClose = /^\s*(\/?)>/; const endTag = new RegExp('^<\\/' + qnameCapture + '[^>]*>'); const doctype = /^<!DOCTYPE [^>]+>/i; const comment = /^<!--/; const conditionalComment = /^<!\[/; let IS_REGEX_CAPTURING_BROKEN = false; 'x'.replace(/x(.)?/g, function(m, g) { IS_REGEX_CAPTURING_BROKEN = g === ''; }); // Special Elements (can contain anything) const isPlainTextElement = makeMap('script,style,textarea', true); const reCache = {}; const decodingMap = { '&lt;': '<', '&gt;': '>', '&quot;': '"', '&amp;': '&', '&#10;': '\n', }; const encodedAttr = /&(?:lt|gt|quot|amp);/g; const encodedAttrWithNewLines = /&(?:lt|gt|quot|amp|#10);/g; // #5992 const isIgnoreNewlineTag = makeMap('pre,textarea', true); const shouldIgnoreFirstNewline = function(tag, html) { return tag && isIgnoreNewlineTag(tag) && html[0] === '\n'; }; function decodeAttr(value, shouldDecodeNewlines) { const re = shouldDecodeNewlines ? encodedAttrWithNewLines : encodedAttr; return value.replace(re, function(match) { return decodingMap[match]; }); } function parseHTML(html, options) { const stack = []; const expectHTML = options.expectHTML; const isUnaryTag$$1 = options.isUnaryTag || no; const canBeLeftOpenTag$$1 = options.canBeLeftOpenTag || no; let index = 0; let last, lastTag; while (html) { last = html; // Make sure we're not in a plaintext content element like script/style if (!lastTag || !isPlainTextElement(lastTag)) { if (shouldIgnoreFirstNewline(lastTag, html)) { advance(1); } let textEnd = html.indexOf('<'); if (textEnd === 0) { // Comment: if (comment.test(html)) { const commentEnd = html.indexOf('-->'); if (commentEnd >= 0) { if (options.shouldKeepComment) { options.comment(html.substring(4, commentEnd)); } advance(commentEnd + 3); continue; } } // http://en.wikipedia.org/wiki/Conditional_comment#Downlevel-revealed_conditional_comment if (conditionalComment.test(html)) { const conditionalEnd = html.indexOf(']>'); if (conditionalEnd >= 0) { advance(conditionalEnd + 2); continue; } } // Doctype: const doctypeMatch = html.match(doctype); if (doctypeMatch) { advance(doctypeMatch[0].length); continue; } // End tag: const endTagMatch = html.match(endTag); if (endTagMatch) { const curIndex = index; advance(endTagMatch[0].length); parseEndTag(endTagMatch[1], curIndex, index); continue; } // Start tag: const startTagMatch = parseStartTag(); if (startTagMatch) { handleStartTag(startTagMatch); continue; } } let text = (void 0), rest = (void 0), next = (void 0); if (textEnd >= 0) { rest = html.slice(textEnd); while (!endTag.test(rest) && !startTagOpen.test(rest) && !comment.test(rest) && !conditionalComment.test(rest) ) { // < in plain text, be forgiving and treat it as text next = rest.indexOf('<', 1); if (next < 0) { break; } textEnd += next; rest = html.slice(textEnd); } text = html.substring(0, textEnd); advance(textEnd); } if (textEnd < 0) { text = html; html = ''; } if (options.chars && text) { options.chars(text); } } else { var endTagLength = 0; var stackedTag = lastTag.toLowerCase(); const reStackedTag = reCache[stackedTag] || (reCache[stackedTag] = new RegExp('([\\s\\S]*?)(</' + stackedTag + '[^>]*>)', 'i')); const rest$1 = html.replace(reStackedTag, function(all, text, endTag) { endTagLength = endTag.length; if (!isPlainTextElement(stackedTag) && stackedTag !== 'noscript') { text = text .replace(/<!--([\s\S]*?)-->/g, '$1') .replace(/<!\[CDATA\[([\s\S]*?)]]>/g, '$1'); } if (shouldIgnoreFirstNewline(stackedTag, text)) { text = text.slice(1); } if (options.chars) { options.chars(text); } return ''; }); index += html.length - rest$1.length; html = rest$1; parseEndTag(stackedTag, index - endTagLength, index); } if (html === last) { options.chars && options.chars(html); if ('development' !== 'production' && !stack.length && options.warn) { options.warn(('Mal-formatted tag at end of template: "' + html + '"')); } break; } } // Clean up any remaining tags parseEndTag(); function advance(n) { index += n; html = html.substring(n); } function parseStartTag() { const start = html.match(startTagOpen); if (start) { const match = { tagName: start[1], attrs: [], start: index, }; advance(start[0].length); let end, attr; while (!(end = html.match(startTagClose)) && (attr = html.match(attribute))) { advance(attr[0].length); match.attrs.push(attr); } if (end) { match.unarySlash = end[1]; advance(end[0].length); match.end = index; return match; } } } function handleStartTag(match) { const tagName = match.tagName; const unarySlash = match.unarySlash; if (expectHTML) { if (lastTag === 'p' && isNonPhrasingTag(tagName)) { parseEndTag(lastTag); } if (canBeLeftOpenTag$$1(tagName) && lastTag === tagName) { parseEndTag(tagName); } } const unary = isUnaryTag$$1(tagName) || !!unarySlash; const l = match.attrs.length; const attrs = new Array(l); for (let i = 0; i < l; i++) { const args = match.attrs[i]; // hackish work around FF bug https://bugzilla.mozilla.org/show_bug.cgi?id=369778 if (IS_REGEX_CAPTURING_BROKEN && args[0].indexOf('""') === -1) { if (args[3] === '') { delete args[3]; } if (args[4] === '') { delete args[4]; } if (args[5] === '') { delete args[5]; } } const value = args[3] || args[4] || args[5] || ''; attrs[i] = { name: args[1], value: decodeAttr( value, options.shouldDecodeNewlines ), }; } if (!unary) { stack.push({ tag: tagName, lowerCasedTag: tagName.toLowerCase(), attrs, }); lastTag = tagName; } if (options.start) { options.start(tagName, attrs, unary, match.start, match.end); } } function parseEndTag(tagName, start, end) { let pos, lowerCasedTagName; if (start == null) { start = index; } if (end == null) { end = index; } if (tagName) { lowerCasedTagName = tagName.toLowerCase(); } // Find the closest opened tag of the same type if (tagName) { for (pos = stack.length - 1; pos >= 0; pos--) { if (stack[pos].lowerCasedTag === lowerCasedTagName) { break; } } } else { // If no tag name is provided, clean shop pos = 0; } if (pos >= 0) { // Close all the open elements, up the stack for (let i = stack.length - 1; i >= pos; i--) { if ('development' !== 'production' && (i > pos || !tagName) && options.warn ) { options.warn( ('tag <' + (stack[i].tag) + '> has no matching end tag.') ); } if (options.end) { options.end(stack[i].tag, start, end); } } // Remove the open elements from the stack stack.length = pos; lastTag = pos && stack[pos - 1].tag; } else if (lowerCasedTagName === 'br') { if (options.start) { options.start(tagName, [], true, start, end); } } else if (lowerCasedTagName === 'p') { if (options.start) { options.start(tagName, [], false, start, end); } if (options.end) { options.end(tagName, start, end); } } } } /* */ const onRE = /^@|^v-on:/; const dirRE = /^v-|^@|^:/; const forAliasRE = /(.*?)\s+(?:in|of)\s+(.*)/; const forIteratorRE = /\((\{[^}]*\}|[^,]*),([^,]*)(?:,([^,]*))?\)/; const argRE = /:(.*)$/; const bindRE = /^:|^v-bind:/; const modifierRE = /\.[^.]+/g; const decodeHTMLCached = cached(he.decode); // configurable state let warn$2; let delimiters; let transforms; let preTransforms; let postTransforms; let platformIsPreTag; let platformMustUseProp; let platformGetTagNamespace; /** * Convert HTML string to AST. */ function parse( template, options ) { warn$2 = options.warn || baseWarn; platformIsPreTag = options.isPreTag || no; platformMustUseProp = options.mustUseProp || no; platformGetTagNamespace = options.getTagNamespace || no; transforms = pluckModuleFunction(options.modules, 'transformNode'); preTransforms = pluckModuleFunction(options.modules, 'preTransformNode'); postTransforms = pluckModuleFunction(options.modules, 'postTransformNode'); delimiters = options.delimiters; const stack = []; const preserveWhitespace = options.preserveWhitespace !== false; let root; let currentParent; let inVPre = false; let inPre = false; let warned = false; function warnOnce(msg) { if (!warned) { warned = true; warn$2(msg); } } function endPre(element) { // check pre state if (element.pre) { inVPre = false; } if (platformIsPreTag(element.tag)) { inPre = false; } } parseHTML(template, { warn: warn$2, expectHTML: options.expectHTML, isUnaryTag: options.isUnaryTag, canBeLeftOpenTag: options.canBeLeftOpenTag, shouldDecodeNewlines: options.shouldDecodeNewlines, shouldKeepComment: options.comments, start: function start(tag, attrs, unary) { // check namespace. // inherit parent ns if there is one const ns = (currentParent && currentParent.ns) || platformGetTagNamespace(tag); // handle IE svg bug /* istanbul ignore if */ if (isIE && ns === 'svg') { attrs = guardIESVGBug(attrs); } const element = { type: 1, tag, attrsList: attrs, attrsMap: makeAttrsMap(attrs), parent: currentParent, children: [], }; if (ns) { element.ns = ns; } if (isForbiddenTag(element) && !isServerRendering()) { element.forbidden = true; 'development' !== 'production' && warn$2( 'Templates should only be responsible for mapping the state to the ' + 'UI. Avoid placing tags with side-effects in your templates, such as ' + '<' + tag + '>' + ', as they will not be parsed.' ); } // apply pre-transforms for (let i = 0; i < preTransforms.length; i++) { preTransforms[i](element, options); } if (!inVPre) { processPre(element); if (element.pre) { inVPre = true; } } if (platformIsPreTag(element.tag)) { inPre = true; } if (inVPre) { processRawAttrs(element); } else { processFor(element); processIf(element); processOnce(element); processKey(element); // determine whether this is a plain element after // removing structural attributes element.plain = !element.key && !attrs.length; processRef(element); processSlot(element); processComponent(element); for (let i$1 = 0; i$1 < transforms.length; i$1++) { transforms[i$1](element, options); } processAttrs(element); } function checkRootConstraints(el) { { if (el.tag === 'slot' || el.tag === 'template') { warnOnce( 'Cannot use <' + (el.tag) + '> as component root element because it may ' + 'contain multiple nodes.' ); } if (el.attrsMap.hasOwnProperty('v-for')) { warnOnce( 'Cannot use v-for on stateful component root element because ' + 'it renders multiple elements.' ); } } } // tree management if (!root) { root = element; checkRootConstraints(root); } else if (!stack.length) { // allow root elements with v-if, v-else-if and v-else if (root.if && (element.elseif || element.else)) { checkRootConstraints(element); addIfCondition(root, { exp: element.elseif, block: element, }); } else { warnOnce( 'Component template should contain exactly one root element. ' + 'If you are using v-if on multiple elements, ' + 'use v-else-if to chain them instead.' ); } } if (currentParent && !element.forbidden) { if (element.elseif || element.else) { processIfConditions(element, currentParent); } else if (element.slotScope) { // scoped slot currentParent.plain = false; const name = element.slotTarget || '"default"'; (currentParent.scopedSlots || (currentParent.scopedSlots = {}))[name] = element; } else { currentParent.children.push(element); element.parent = currentParent; } } if (!unary) { currentParent = element; stack.push(element); } else { endPre(element); } // apply post-transforms for (let i$2 = 0; i$2 < postTransforms.length; i$2++) { postTransforms[i$2](element, options); } }, end: function end() { // remove trailing whitespace const element = stack[stack.length - 1]; const lastNode = element.children[element.children.length - 1]; if (lastNode && lastNode.type === 3 && lastNode.text === ' ' && !inPre) { element.children.pop(); } // pop stack stack.length -= 1; currentParent = stack[stack.length - 1]; endPre(element); }, chars: function chars(text) { if (!currentParent) { { if (text === template) { warnOnce( 'Component template requires a root element, rather than just text.' ); } else if ((text = text.trim())) { warnOnce( ('text "' + text + '" outside root element will be ignored.') ); } } return; } // IE textarea placeholder bug /* istanbul ignore if */ if (isIE && currentParent.tag === 'textarea' && currentParent.attrsMap.placeholder === text ) { return; } const children = currentParent.children; text = inPre || text.trim() ? isTextTag(currentParent) ? text : decodeHTMLCached(text) // only preserve whitespace if its not right after a starting tag : preserveWhitespace && children.length ? ' ' : ''; if (text) { let expression; if (!inVPre && text !== ' ' && (expression = parseText(text, delimiters))) { children.push({ type: 2, expression, text, }); } else if (text !== ' ' || !children.length || children[children.length - 1].text !== ' ') { children.push({ type: 3, text, }); } } }, comment: function comment(text) { currentParent.children.push({ type: 3, text, isComment: true, }); }, }); return root; } function processPre(el) { if (getAndRemoveAttr(el, 'v-pre') != null) { el.pre = true; } } function processRawAttrs(el) { const l = el.attrsList.length; if (l) { const attrs = el.attrs = new Array(l); for (let i = 0; i < l; i++) { attrs[i] = { name: el.attrsList[i].name, value: JSON.stringify(el.attrsList[i].value), }; } } else if (!el.pre) { // non root node in pre blocks with no attributes el.plain = true; } } function processKey(el) { const exp = getBindingAttr(el, 'key'); if (exp) { if ('development' !== 'production' && el.tag === 'template') { warn$2('<template> cannot be keyed. Place the key on real elements instead.'); } el.key = exp; } } function processRef(el) { const ref = getBindingAttr(el, 'ref'); if (ref) { el.ref = ref; el.refInFor = checkInFor(el); } } function processFor(el) { let exp; if ((exp = getAndRemoveAttr(el, 'v-for'))) { const inMatch = exp.match(forAliasRE); if (!inMatch) { 'development' !== 'production' && warn$2( ('Invalid v-for expression: ' + exp) ); return; } el.for = inMatch[2].trim(); const alias = inMatch[1].trim(); const iteratorMatch = alias.match(forIteratorRE); if (iteratorMatch) { el.alias = iteratorMatch[1].trim(); el.iterator1 = iteratorMatch[2].trim(); if (iteratorMatch[3]) { el.iterator2 = iteratorMatch[3].trim(); } } else { el.alias = alias; } } } function processIf(el) { const exp = getAndRemoveAttr(el, 'v-if'); if (exp) { el.if = exp; addIfCondition(el, { exp, block: el, }); } else { if (getAndRemoveAttr(el, 'v-else') != null) { el.else = true; } const elseif = getAndRemoveAttr(el, 'v-else-if'); if (elseif) { el.elseif = elseif; } } } function processIfConditions(el, parent) { const prev = findPrevElement(parent.children); if (prev && prev.if) { addIfCondition(prev, { exp: el.elseif, block: el, }); } else { warn$2( 'v-' + (el.elseif ? ('else-if="' + el.elseif + '"') : 'else') + ' ' + 'used on element <' + (el.tag) + '> without corresponding v-if.' ); } } function findPrevElement(children) { let i = children.length; while (i--) { if (children[i].type === 1) { return children[i]; } if ('development' !== 'production' && children[i].text !== ' ') { warn$2( 'text "' + (children[i].text.trim()) + '" between v-if and v-else(-if) ' + 'will be ignored.' ); } children.pop(); } } function addIfCondition(el, condition) { if (!el.ifConditions) { el.ifConditions = []; } el.ifConditions.push(condition); } function processOnce(el) { const once$$1 = getAndRemoveAttr(el, 'v-once'); if (once$$1 != null) { el.once = true; } } function processSlot(el) { if (el.tag === 'slot') { el.slotName = getBindingAttr(el, 'name'); if ('development' !== 'production' && el.key) { warn$2( '`key` does not work on <slot> because slots are abstract outlets ' + 'and can possibly expand into multiple elements. ' + 'Use the key on a wrapping element instead.' ); } } else { const slotTarget = getBindingAttr(el, 'slot'); if (slotTarget) { el.slotTarget = slotTarget === '""' ? '"default"' : slotTarget; } if (el.tag === 'template') { el.slotScope = getAndRemoveAttr(el, 'scope'); } } } function processComponent(el) { let binding; if ((binding = getBindingAttr(el, 'is'))) { el.component = binding; } if (getAndRemoveAttr(el, 'inline-template') != null) { el.inlineTemplate = true; } } function processAttrs(el) { const list = el.attrsList; let i, l, name, rawName, value, modifiers, isProp; for (i = 0, l = list.length; i < l; i++) { name = rawName = list[i].name; value = list[i].value; if (dirRE.test(name)) { // mark element as dynamic el.hasBindings = true; // modifiers modifiers = parseModifiers(name); if (modifiers) { name = name.replace(modifierRE, ''); } if (bindRE.test(name)) { // v-bind name = name.replace(bindRE, ''); value = parseFilters(value); isProp = false; if (modifiers) { if (modifiers.prop) { isProp = true; name = camelize(name); if (name === 'innerHtml') { name = 'innerHTML'; } } if (modifiers.camel) { name = camelize(name); } if (modifiers.sync) { addHandler( el, ('update:' + (camelize(name))), genAssignmentCode(value, '$event') ); } } if (!el.component && ( isProp || platformMustUseProp(el.tag, el.attrsMap.type, name) )) { addProp(el, name, value); } else { addAttr(el, name, value); } } else if (onRE.test(name)) { // v-on name = name.replace(onRE, ''); addHandler(el, name, value, modifiers, false, warn$2); } else { // normal directives name = name.replace(dirRE, ''); // parse arg const argMatch = name.match(argRE); const arg = argMatch && argMatch[1]; if (arg) { name = name.slice(0, -(arg.length + 1)); } addDirective(el, name, rawName, value, arg, modifiers); if ('development' !== 'production' && name === 'model') { checkForAliasModel(el, value); } } } else { // literal attribute { const expression = parseText(value, delimiters); if (expression) { warn$2( name + '="' + value + '": ' + 'Interpolation inside attributes has been removed. ' + 'Use v-bind or the colon shorthand instead. For example, ' + 'instead of <div id="{{ val }}">, use <div :id="val">.' ); } } addAttr(el, name, JSON.stringify(value)); } } } function checkInFor(el) { let parent = el; while (parent) { if (parent.for !== undefined) { return true; } parent = parent.parent; } return false; } function parseModifiers(name) { const match = name.match(modifierRE); if (match) { const ret = {}; match.forEach(function(m) { ret[m.slice(1)] = true; }); return ret; } } function makeAttrsMap(attrs) { const map = {}; for (let i = 0, l = attrs.length; i < l; i++) { if ( 'development' !== 'production' && map[attrs[i].name] && !isIE && !isEdge ) { warn$2('duplicate attribute: ' + attrs[i].name); } map[attrs[i].name] = attrs[i].value; } return map; } // for script (e.g. type="x/template") or style, do not decode content function isTextTag(el) { return el.tag === 'script' || el.tag === 'style'; } function isForbiddenTag(el) { return ( el.tag === 'style' || (el.tag === 'script' && (!el.attrsMap.type || el.attrsMap.type === 'text/javascript' )) ); } const ieNSBug = /^xmlns:NS\d+/; const ieNSPrefix = /^NS\d+:/; /* istanbul ignore next */ function guardIESVGBug(attrs) { const res = []; for (let i = 0; i < attrs.length; i++) { const attr = attrs[i]; if (!ieNSBug.test(attr.name)) { attr.name = attr.name.replace(ieNSPrefix, ''); res.push(attr); } } return res; } function checkForAliasModel(el, value) { let _el = el; while (_el) { if (_el.for && _el.alias === value) { warn$2( '<' + (el.tag) + ' v-model="' + value + '">: ' + 'You are binding v-model directly to a v-for iteration alias. ' + 'This will not be able to modify the v-for source array because ' + 'writing to the alias is like modifying a function local variable. ' + 'Consider using an array of objects and use v-model on an object property instead.' ); } _el = _el.parent; } } /* */ let isStaticKey; let isPlatformReservedTag; const genStaticKeysCached = cached(genStaticKeys$1); /** * Goal of the optimizer: walk the generated template AST tree * and detect sub-trees that are purely static, i.e. parts of * the DOM that never needs to change. * * Once we detect these sub-trees, we can: * * 1. Hoist them into constants, so that we no longer need to * create fresh nodes for them on each re-render; * 2. Completely skip them in the patching process. */ function optimize(root, options) { if (!root) { return; } isStaticKey = genStaticKeysCached(options.staticKeys || ''); isPlatformReservedTag = options.isReservedTag || no; // first pass: mark all non-static nodes. markStatic$1(root); // second pass: mark static roots. markStaticRoots(root, false); } function genStaticKeys$1(keys) { return makeMap( 'type,tag,attrsList,attrsMap,plain,parent,children,attrs' + (keys ? ',' + keys : '') ); } function markStatic$1(node) { node.static = isStatic(node); if (node.type === 1) { // do not make component slot content static. this avoids // 1. components not able to mutate slot nodes // 2. static slot content fails for hot-reloading if (!isPlatformReservedTag(node.tag) && node.tag !== 'slot' && node.attrsMap['inline-template'] == null ) { return; } for (let i = 0, l = node.children.length; i < l; i++) { const child = node.children[i]; markStatic$1(child); if (!child.static) { node.static = false; } } if (node.ifConditions) { for (let i$1 = 1, l$1 = node.ifConditions.length; i$1 < l$1; i$1++) { const block = node.ifConditions[i$1].block; markStatic$1(block); if (!block.static) { node.static = false; } } } } } function markStaticRoots(node, isInFor) { if (node.type === 1) { if (node.static || node.once) { node.staticInFor = isInFor; } // For a node to qualify as a static root, it should have children that // are not just static text. Otherwise the cost of hoisting out will // outweigh the benefits and it's better off to just always render it fresh. if (node.static && node.children.length && !( node.children.length === 1 && node.children[0].type === 3 )) { node.staticRoot = true; return; } node.staticRoot = false; if (node.children) { for (let i = 0, l = node.children.length; i < l; i++) { markStaticRoots(node.children[i], isInFor || !!node.for); } } if (node.ifConditions) { for (let i$1 = 1, l$1 = node.ifConditions.length; i$1 < l$1; i$1++) { markStaticRoots(node.ifConditions[i$1].block, isInFor); } } } } function isStatic(node) { if (node.type === 2) { // expression return false; } if (node.type === 3) { // text return true; } return !!(node.pre || (!node.hasBindings && // no dynamic bindings !node.if && !node.for && // not v-if or v-for or v-else !isBuiltInTag(node.tag) && // not a built-in isPlatformReservedTag(node.tag) && // not a component !isDirectChildOfTemplateFor(node) && Object.keys(node).every(isStaticKey) )); } function isDirectChildOfTemplateFor(node) { while (node.parent) { node = node.parent; if (node.tag !== 'template') { return false; } if (node.for) { return true; } } return false; } /* */ const fnExpRE = /^\s*([\w$_]+|\([^)]*?\))\s*=>|^function\s*\(/; const simplePathRE = /^\s*[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\['.*?']|\[".*?"]|\[\d+]|\[[A-Za-z_$][\w$]*])*\s*$/; // keyCode aliases const keyCodes = { esc: 27, tab: 9, enter: 13, space: 32, up: 38, left: 37, right: 39, down: 40, delete: [ 8, 46 ], }; // #4868: modifiers that prevent the execution of the listener // need to explicitly return null so that we can determine whether to remove // the listener for .once const genGuard = function(condition) { return ('if(' + condition + ')return null;'); }; const modifierCode = { stop: '$event.stopPropagation();', prevent: '$event.preventDefault();', self: genGuard('$event.target !== $event.currentTarget'), ctrl: genGuard('!$event.ctrlKey'), shift: genGuard('!$event.shiftKey'), alt: genGuard('!$event.altKey'), meta: genGuard('!$event.metaKey'), left: genGuard("'button' in $event && $event.button !== 0"), middle: genGuard("'button' in $event && $event.button !== 1"), right: genGuard("'button' in $event && $event.button !== 2"), }; function genHandlers( events, isNative, warn ) { let res = isNative ? 'nativeOn:{' : 'on:{'; for (const name in events) { const handler = events[name]; // #5330: warn click.right, since right clicks do not actually fire click events. if ('development' !== 'production' && name === 'click' && handler && handler.modifiers && handler.modifiers.right ) { warn( 'Use "contextmenu" instead of "click.right" since right clicks ' + 'do not actually fire "click" events.' ); } res += '"' + name + '":' + (genHandler(name, handler)) + ','; } return res.slice(0, -1) + '}'; } function genHandler( name, handler ) { if (!handler) { return 'function(){}'; } if (Array.isArray(handler)) { return ('[' + (handler.map(function(handler) { return genHandler(name, handler); }).join(',')) + ']'); } const isMethodPath = simplePathRE.test(handler.value); const isFunctionExpression = fnExpRE.test(handler.value); if (!handler.modifiers) { return isMethodPath || isFunctionExpression ? handler.value : ('function($event){' + (handler.value) + '}'); // inline statement } let code = ''; let genModifierCode = ''; const keys = []; for (const key in handler.modifiers) { if (modifierCode[key]) { genModifierCode += modifierCode[key]; // left/right if (keyCodes[key]) { keys.push(key); } } else { keys.push(key); } } if (keys.length) { code += genKeyFilter(keys); } // Make sure modifiers like prevent and stop get executed after key filtering if (genModifierCode) { code += genModifierCode; } const handlerCode = isMethodPath ? handler.value + '($event)' : isFunctionExpression ? ('(' + (handler.value) + ')($event)') : handler.value; return ('function($event){' + code + handlerCode + '}'); } function genKeyFilter(keys) { return ("if(!('button' in $event)&&" + (keys.map(genFilterCode).join('&&')) + ')return null;'); } function genFilterCode(key) { const keyVal = parseInt(key, 10); if (keyVal) { return ('$event.keyCode!==' + keyVal); } const alias = keyCodes[key]; return ('_k($event.keyCode,' + (JSON.stringify(key)) + (alias ? ',' + JSON.stringify(alias) : '') + ')'); } /* */ function on(el, dir) { if ('development' !== 'production' && dir.modifiers) { warn('v-on without argument does not support modifiers.'); } el.wrapListeners = function(code) { return ('_g(' + code + ',' + (dir.value) + ')'); }; } /* */ function bind$1(el, dir) { el.wrapData = function(code) { return ('_b(' + code + ",'" + (el.tag) + "'," + (dir.value) + ',' + (dir.modifiers && dir.modifiers.prop ? 'true' : 'false') + (dir.modifiers && dir.modifiers.sync ? ',true' : '') + ')'); }; } /* */ const baseDirectives = { on, bind: bind$1, cloak: noop, }; /* */ const CodegenState = function CodegenState(options) { this.options = options; this.warn = options.warn || baseWarn; this.transforms = pluckModuleFunction(options.modules, 'transformCode'); this.dataGenFns = pluckModuleFunction(options.modules, 'genData'); this.directives = extend(extend({}, baseDirectives), options.directives); const isReservedTag = options.isReservedTag || no; this.maybeComponent = function(el) { return !isReservedTag(el.tag); }; this.onceId = 0; this.staticRenderFns = []; }; function generate( ast, options ) { const state = new CodegenState(options); const code = ast ? genElement(ast, state) : '_c("div")'; return { render: ('with(this){return ' + code + '}'), staticRenderFns: state.staticRenderFns, }; } function genElement(el, state) { if (el.staticRoot && !el.staticProcessed) { return genStatic(el, state); } else if (el.once && !el.onceProcessed) { return genOnce(el, state); } else if (el.for && !el.forProcessed) { return genFor(el, state); } else if (el.if && !el.ifProcessed) { return genIf(el, state); } else if (el.tag === 'template' && !el.slotTarget) { return genChildren(el, state) || 'void 0'; } else if (el.tag === 'slot') { return genSlot(el, state); } // component or element let code; if (el.component) { code = genComponent(el.component, el, state); } else { const data = el.plain ? undefined : genData$2(el, state); const children = el.inlineTemplate ? null : genChildren(el, state, true); code = "_c('" + (el.tag) + "'" + (data ? (',' + data) : '') + (children ? (',' + children) : '') + ')'; } // module transforms for (let i = 0; i < state.transforms.length; i++) { code = state.transforms[i](el, code); } return code; } // hoist static sub-trees out function genStatic(el, state) { el.staticProcessed = true; state.staticRenderFns.push(('with(this){return ' + (genElement(el, state)) + '}')); return ('_m(' + (state.staticRenderFns.length - 1) + (el.staticInFor ? ',true' : '') + ')'); } // v-once function genOnce(el, state) { el.onceProcessed = true; if (el.if && !el.ifProcessed) { return genIf(el, state); } else if (el.staticInFor) { let key = ''; let parent = el.parent; while (parent) { if (parent.for) { key = parent.key; break; } parent = parent.parent; } if (!key) { 'development' !== 'production' && state.warn( 'v-once can only be used inside v-for that is keyed. ' ); return genElement(el, state); } return ('_o(' + (genElement(el, state)) + ',' + (state.onceId++) + (key ? (',' + key) : '') + ')'); } return genStatic(el, state); } function genIf( el, state, altGen, altEmpty ) { el.ifProcessed = true; // avoid recursion return genIfConditions(el.ifConditions.slice(), state, altGen, altEmpty); } function genIfConditions( conditions, state, altGen, altEmpty ) { if (!conditions.length) { return altEmpty || '_e()'; } const condition = conditions.shift(); if (condition.exp) { return ('(' + (condition.exp) + ')?' + (genTernaryExp(condition.block)) + ':' + (genIfConditions(conditions, state, altGen, altEmpty))); } return ('' + (genTernaryExp(condition.block))); // v-if with v-once should generate code like (a)?_m(0):_m(1) function genTernaryExp(el) { return altGen ? altGen(el, state) : el.once ? genOnce(el, state) : genElement(el, state); } } function genFor( el, state, altGen, altHelper ) { const exp = el.for; const alias = el.alias; const iterator1 = el.iterator1 ? (',' + (el.iterator1)) : ''; const iterator2 = el.iterator2 ? (',' + (el.iterator2)) : ''; if ('development' !== 'production' && state.maybeComponent(el) && el.tag !== 'slot' && el.tag !== 'template' && !el.key ) { state.warn( '<' + (el.tag) + ' v-for="' + alias + ' in ' + exp + '">: component lists rendered with ' + 'v-for should have explicit keys. ' + 'See https://vuejs.org/guide/list.html#key for more info.', true /* tip */ ); } el.forProcessed = true; // avoid recursion return (altHelper || '_l') + '((' + exp + '),' + 'function(' + alias + iterator1 + iterator2 + '){' + 'return ' + ((altGen || genElement)(el, state)) + '})'; } function genData$2(el, state) { let data = '{'; // directives first. // directives may mutate the el's other properties before they are generated. const dirs = genDirectives(el, state); if (dirs) { data += dirs + ','; } // key if (el.key) { data += 'key:' + (el.key) + ','; } // ref if (el.ref) { data += 'ref:' + (el.ref) + ','; } if (el.refInFor) { data += 'refInFor:true,'; } // pre if (el.pre) { data += 'pre:true,'; } // record original tag name for components using "is" attribute if (el.component) { data += 'tag:"' + (el.tag) + '",'; } // module data generation functions for (let i = 0; i < state.dataGenFns.length; i++) { data += state.dataGenFns[i](el); } // attributes if (el.attrs) { data += 'attrs:{' + (genProps(el.attrs)) + '},'; } // DOM props if (el.props) { data += 'domProps:{' + (genProps(el.props)) + '},'; } // event handlers if (el.events) { data += (genHandlers(el.events, false, state.warn)) + ','; } if (el.nativeEvents) { data += (genHandlers(el.nativeEvents, true, state.warn)) + ','; } // slot target if (el.slotTarget) { data += 'slot:' + (el.slotTarget) + ','; } // scoped slots if (el.scopedSlots) { data += (genScopedSlots(el.scopedSlots, state)) + ','; } // component v-model if (el.model) { data += 'model:{value:' + (el.model.value) + ',callback:' + (el.model.callback) + ',expression:' + (el.model.expression) + '},'; } // inline-template if (el.inlineTemplate) { const inlineTemplate = genInlineTemplate(el, state); if (inlineTemplate) { data += inlineTemplate + ','; } } data = data.replace(/,$/, '') + '}'; // v-bind data wrap if (el.wrapData) { data = el.wrapData(data); } // v-on data wrap if (el.wrapListeners) { data = el.wrapListeners(data); } return data; } function genDirectives(el, state) { const dirs = el.directives; if (!dirs) { return; } let res = 'directives:['; let hasRuntime = false; let i, l, dir, needRuntime; for (i = 0, l = dirs.length; i < l; i++) { dir = dirs[i]; needRuntime = true; const gen = state.directives[dir.name]; if (gen) { // compile-time directive that manipulates AST. // returns true if it also needs a runtime counterpart. needRuntime = !!gen(el, dir, state.warn); } if (needRuntime) { hasRuntime = true; res += '{name:"' + (dir.name) + '",rawName:"' + (dir.rawName) + '"' + (dir.value ? (',value:(' + (dir.value) + '),expression:' + (JSON.stringify(dir.value))) : '') + (dir.arg ? (',arg:"' + (dir.arg) + '"') : '') + (dir.modifiers ? (',modifiers:' + (JSON.stringify(dir.modifiers))) : '') + '},'; } } if (hasRuntime) { return res.slice(0, -1) + ']'; } } function genInlineTemplate(el, state) { const ast = el.children[0]; if ('development' !== 'production' && ( el.children.length > 1 || ast.type !== 1 )) { state.warn('Inline-template components must have exactly one child element.'); } if (ast.type === 1) { const inlineRenderFns = generate(ast, state.options); return ('inlineTemplate:{render:function(){' + (inlineRenderFns.render) + '},staticRenderFns:[' + (inlineRenderFns.staticRenderFns.map(function(code) { return ('function(){' + code + '}'); }).join(',')) + ']}'); } } function genScopedSlots( slots, state ) { return ('scopedSlots:_u([' + (Object.keys(slots).map(function(key) { return genScopedSlot(key, slots[key], state); }).join(',')) + '])'); } function genScopedSlot( key, el, state ) { if (el.for && !el.forProcessed) { return genForScopedSlot(key, el, state); } return '{key:' + key + ',fn:function(' + (String(el.attrsMap.scope)) + '){' + 'return ' + (el.tag === 'template' ? genChildren(el, state) || 'void 0' : genElement(el, state)) + '}}'; } function genForScopedSlot( key, el, state ) { const exp = el.for; const alias = el.alias; const iterator1 = el.iterator1 ? (',' + (el.iterator1)) : ''; const iterator2 = el.iterator2 ? (',' + (el.iterator2)) : ''; el.forProcessed = true; // avoid recursion return '_l((' + exp + '),' + 'function(' + alias + iterator1 + iterator2 + '){' + 'return ' + (genScopedSlot(key, el, state)) + '})'; } function genChildren( el, state, checkSkip, altGenElement, altGenNode ) { const children = el.children; if (children.length) { const el$1 = children[0]; // optimize single v-for if (children.length === 1 && el$1.for && el$1.tag !== 'template' && el$1.tag !== 'slot' ) { return (altGenElement || genElement)(el$1, state); } const normalizationType = checkSkip ? getNormalizationType(children, state.maybeComponent) : 0; const gen = altGenNode || genNode; return ('[' + (children.map(function(c) { return gen(c, state); }).join(',')) + ']' + (normalizationType ? (',' + normalizationType) : '')); } } // determine the normalization needed for the children array. // 0: no normalization needed // 1: simple normalization needed (possible 1-level deep nested array) // 2: full normalization needed function getNormalizationType( children, maybeComponent ) { let res = 0; for (let i = 0; i < children.length; i++) { const el = children[i]; if (el.type !== 1) { continue; } if (needsNormalization(el) || (el.ifConditions && el.ifConditions.some(function(c) { return needsNormalization(c.block); }))) { res = 2; break; } if (maybeComponent(el) || (el.ifConditions && el.ifConditions.some(function(c) { return maybeComponent(c.block); }))) { res = 1; } } return res; } function needsNormalization(el) { return el.for !== undefined || el.tag === 'template' || el.tag === 'slot'; } function genNode(node, state) { if (node.type === 1) { return genElement(node, state); } if (node.type === 3 && node.isComment) { return genComment(node); } return genText(node); } function genText(text) { return ('_v(' + (text.type === 2 ? text.expression // no need for () because already wrapped in _s() : transformSpecialNewlines(JSON.stringify(text.text))) + ')'); } function genComment(comment) { return ("_e('" + (comment.text) + "')"); } function genSlot(el, state) { const slotName = el.slotName || '"default"'; const children = genChildren(el, state); let res = '_t(' + slotName + (children ? (',' + children) : ''); const attrs = el.attrs && ('{' + (el.attrs.map(function(a) { return ((camelize(a.name)) + ':' + (a.value)); }).join(',')) + '}'); const bind$$1 = el.attrsMap['v-bind']; if ((attrs || bind$$1) && !children) { res += ',null'; } if (attrs) { res += ',' + attrs; } if (bind$$1) { res += (attrs ? '' : ',null') + ',' + bind$$1; } return res + ')'; } // componentName is el.component, take it as argument to shun flow's pessimistic refinement function genComponent( componentName, el, state ) { const children = el.inlineTemplate ? null : genChildren(el, state, true); return ('_c(' + componentName + ',' + (genData$2(el, state)) + (children ? (',' + children) : '') + ')'); } function genProps(props) { let res = ''; for (let i = 0; i < props.length; i++) { const prop = props[i]; res += '"' + (prop.name) + '":' + (transformSpecialNewlines(prop.value)) + ','; } return res.slice(0, -1); } // #3895, #4268 function transformSpecialNewlines(text) { return text .replace(/\u2028/g, '\\u2028') .replace(/\u2029/g, '\\u2029'); } /* */ // these keywords should not appear inside expressions, but operators like // typeof, instanceof and in are allowed const prohibitedKeywordRE = new RegExp('\\b' + ( 'do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,' + 'super,throw,while,yield,delete,export,import,return,switch,default,' + 'extends,finally,continue,debugger,function,arguments' ).split(',').join('\\b|\\b') + '\\b'); // these unary operators should not be used as property/method names const unaryOperatorsRE = new RegExp('\\b' + ( 'delete,typeof,void' ).split(',').join('\\s*\\([^\\)]*\\)|\\b') + '\\s*\\([^\\)]*\\)'); // check valid identifier for v-for const identRE = /[A-Za-z_$][\w$]*/; // strip strings in expressions const stripStringRE = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g; // detect problematic expressions in a template function detectErrors(ast) { const errors = []; if (ast) { checkNode(ast, errors); } return errors; } function checkNode(node, errors) { if (node.type === 1) { for (const name in node.attrsMap) { if (dirRE.test(name)) { const value = node.attrsMap[name]; if (value) { if (name === 'v-for') { checkFor(node, ('v-for="' + value + '"'), errors); } else if (onRE.test(name)) { checkEvent(value, (name + '="' + value + '"'), errors); } else { checkExpression(value, (name + '="' + value + '"'), errors); } } } } if (node.children) { for (let i = 0; i < node.children.length; i++) { checkNode(node.children[i], errors); } } } else if (node.type === 2) { checkExpression(node.expression, node.text, errors); } } function checkEvent(exp, text, errors) { const stipped = exp.replace(stripStringRE, ''); const keywordMatch = stipped.match(unaryOperatorsRE); if (keywordMatch && stipped.charAt(keywordMatch.index - 1) !== '$') { errors.push( 'avoid using JavaScript unary operator as property name: ' + '"' + (keywordMatch[0]) + '" in expression ' + (text.trim()) ); } checkExpression(exp, text, errors); } function checkFor(node, text, errors) { checkExpression(node.for || '', text, errors); checkIdentifier(node.alias, 'v-for alias', text, errors); checkIdentifier(node.iterator1, 'v-for iterator', text, errors); checkIdentifier(node.iterator2, 'v-for iterator', text, errors); } function checkIdentifier(ident, type, text, errors) { if (typeof ident === 'string' && !identRE.test(ident)) { errors.push(('invalid ' + type + ' "' + ident + '" in expression: ' + (text.trim()))); } } function checkExpression(exp, text, errors) { try { new Function(('return ' + exp)); } catch (e) { const keywordMatch = exp.replace(stripStringRE, '').match(prohibitedKeywordRE); if (keywordMatch) { errors.push( 'avoid using JavaScript keyword as property name: ' + '"' + (keywordMatch[0]) + '" in expression ' + (text.trim()) ); } else { errors.push(('invalid expression: ' + (text.trim()))); } } } /* */ function createFunction(code, errors) { try { return new Function(code); } catch (err) { errors.push({ err, code, }); return noop; } } function createCompileToFunctionFn(compile) { const cache = Object.create(null); return function compileToFunctions( template, options, vm ) { options = options || {}; /* istanbul ignore if */ { // detect possible CSP restriction try { new Function('return 1'); } catch (e) { if (e.toString().match(/unsafe-eval|CSP/)) { warn( 'It seems you are using the standalone build of Vue.js in an ' + 'environment with Content Security Policy that prohibits unsafe-eval. ' + 'The template compiler cannot work in this environment. Consider ' + 'relaxing the policy to allow unsafe-eval or pre-compiling your ' + 'templates into render functions.' ); } } } // check cache const key = options.delimiters ? String(options.delimiters) + template : template; if (cache[key]) { return cache[key]; } // compile const compiled = compile(template, options); // check compilation errors/tips { if (compiled.errors && compiled.errors.length) { warn( 'Error compiling template:\n\n' + template + '\n\n' + compiled.errors.map(function(e) { return ('- ' + e); }).join('\n') + '\n', vm ); } if (compiled.tips && compiled.tips.length) { compiled.tips.forEach(function(msg) { return tip(msg, vm); }); } } // turn code into functions const res = {}; const fnGenErrors = []; res.render = createFunction(compiled.render, fnGenErrors); res.staticRenderFns = compiled.staticRenderFns.map(function(code) { return createFunction(code, fnGenErrors); }); // check function generation errors. // this should only happen if there is a bug in the compiler itself. // mostly for codegen development use /* istanbul ignore if */ { if ((!compiled.errors || !compiled.errors.length) && fnGenErrors.length) { warn( 'Failed to generate render function:\n\n' + fnGenErrors.map(function(ref) { const err = ref.err; const code = ref.code; return ((err.toString()) + ' in\n\n' + code + '\n'); }).join('\n'), vm ); } } return (cache[key] = res); }; } /* */ function createCompilerCreator(baseCompile) { return function createCompiler(baseOptions) { function compile( template, options ) { const finalOptions = Object.create(baseOptions); const errors = []; const tips = []; finalOptions.warn = function(msg, tip) { (tip ? tips : errors).push(msg); }; if (options) { // merge custom modules if (options.modules) { finalOptions.modules = (baseOptions.modules || []).concat(options.modules); } // merge custom directives if (options.directives) { finalOptions.directives = extend( Object.create(baseOptions.directives), options.directives ); } // copy other options for (const key in options) { if (key !== 'modules' && key !== 'directives') { finalOptions[key] = options[key]; } } } const compiled = baseCompile(template, finalOptions); { errors.push.apply(errors, detectErrors(compiled.ast)); } compiled.errors = errors; compiled.tips = tips; return compiled; } return { compile, compileToFunctions: createCompileToFunctionFn(compile), }; }; } /* */ // `createCompilerCreator` allows creating compilers that use alternative // parser/optimizer/codegen, e.g the SSR optimizing compiler. // Here we just export a default compiler using the default parts. const createCompiler = createCompilerCreator(function baseCompile( template, options ) { const ast = parse(template.trim(), options); optimize(ast, options); const code = generate(ast, options); return { ast, render: code.render, staticRenderFns: code.staticRenderFns, }; }); /* */ const ref$1 = createCompiler(baseOptions); const compileToFunctions = ref$1.compileToFunctions; /* */ const idToTemplate = cached(function(id) { const el = query(id); return el && el.innerHTML; }); const mount = Vue$3.prototype.$mount; Vue$3.prototype.$mount = function( el, hydrating ) { el = el && query(el); /* istanbul ignore if */ if (el === document.body || el === document.documentElement) { 'development' !== 'production' && warn( 'Do not mount Vue to <html> or <body> - mount to normal elements instead.' ); return this; } const options = this.$options; // resolve template/el and convert to render function if (!options.render) { let template = options.template; if (template) { if (typeof template === 'string') { if (template.charAt(0) === '#') { template = idToTemplate(template); /* istanbul ignore if */ if ('development' !== 'production' && !template) { warn( ('Template element not found or is empty: ' + (options.template)), this ); } } } else if (template.nodeType) { template = template.innerHTML; } else { { warn('invalid template option:' + template, this); } return this; } } else if (el) { template = getOuterHTML(el); } if (template) { /* istanbul ignore if */ if ('development' !== 'production' && config.performance && mark) { mark('compile'); } const ref = compileToFunctions(template, { shouldDecodeNewlines, delimiters: options.delimiters, comments: options.comments, }, this); const render = ref.render; const staticRenderFns = ref.staticRenderFns; options.render = render; options.staticRenderFns = staticRenderFns; /* istanbul ignore if */ if ('development' !== 'production' && config.performance && mark) { mark('compile end'); measure(((this._name) + ' compile'), 'compile', 'compile end'); } } } return mount.call(this, el, hydrating); }; /** * Get outerHTML of elements, taking care * of SVG elements in IE as well. */ function getOuterHTML(el) { if (el.outerHTML) { return el.outerHTML; } const container = document.createElement('div'); container.appendChild(el.cloneNode(true)); return container.innerHTML; } Vue$3.compile = compileToFunctions; return Vue$3; }));
{ "content_hash": "59102d649aa1e4dcd523bbf86c805e93", "timestamp": "", "source": "github", "line_count": 10402, "max_line_length": 302, "avg_line_length": 28.67756200730629, "alnum_prop": 0.5319238092683973, "repo_name": "xixixida/egg-vue-blog", "id": "cb9d010b725ef1b8074a9f425aa30da80b1e5a43", "size": "298304", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/public/js/vue.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "2554" }, { "name": "JavaScript", "bytes": "1432502" }, { "name": "Vue", "bytes": "7694" } ], "symlink_target": "" }
UCLASS(ClassGroup = (Custom), meta = (BlueprintSpawnableComponent)) class S05_TESTINGGROUNDS_API UGrassComponent : public UHierarchicalInstancedStaticMeshComponent { GENERATED_BODY() public: // Sets default values for this component's properties UGrassComponent(); UPROPERTY(EditDefaultsOnly, Category = Spawning) FBox SpawningExtents; UPROPERTY(EditDefaultsOnly, Category = Spawning) int SpawnCount; protected: // Called when the game starts virtual void BeginPlay() override; public: // Called every frame virtual void TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override; private: void SpawnGrass(); };
{ "content_hash": "c36bbaaf0feac99aa6e3b558f6ae9692", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 122, "avg_line_length": 26.153846153846153, "alnum_prop": 0.7970588235294118, "repo_name": "professionaljones/S05_TestingGrounds", "id": "2254cba601cff5dc74a5e102bc2392963ef002a1", "size": "878", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Source/S05_TestingGrounds/Terrain/GrassComponent.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "389" }, { "name": "C#", "bytes": "1073" }, { "name": "C++", "bytes": "59128" } ], "symlink_target": "" }
<?php declare(strict_types=1); namespace Sylius\Bundle\UiBundle\Block; use Sonata\BlockBundle\Event\BlockEvent; use Sonata\BlockBundle\Model\Block; /** * @deprecated */ final class BlockEventListener { public function __construct(private string $template) { @trigger_error( sprintf('Using "%s" to add blocks to the templates is deprecated since Sylius 1.7 and will be removed in Sylius 2.0. Use "sylius_ui" configuration instead.', self::class), \E_USER_DEPRECATED, ); } public function onBlockEvent(BlockEvent $event): void { $block = new Block(); $block->setId(uniqid('', true)); $block->setSettings(array_replace($event->getSettings(), [ 'template' => $this->template, ])); $block->setType('sonata.block.service.template'); $event->addBlock($block); } }
{ "content_hash": "4d78f933e9446a7b66f8955d00684679", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 183, "avg_line_length": 24.75, "alnum_prop": 0.6251402918069585, "repo_name": "Sylius/Sylius", "id": "22abf98c9d55dc765fe5ddd4f9014f1502c042c5", "size": "1102", "binary": false, "copies": "2", "ref": "refs/heads/1.13", "path": "src/Sylius/Bundle/UiBundle/Block/BlockEventListener.php", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "674" }, { "name": "Gherkin", "bytes": "1269548" }, { "name": "JavaScript", "bytes": "102771" }, { "name": "Makefile", "bytes": "1478" }, { "name": "PHP", "bytes": "8145147" }, { "name": "SCSS", "bytes": "53880" }, { "name": "Shell", "bytes": "11411" }, { "name": "Twig", "bytes": "446530" } ], "symlink_target": "" }
package temple.multiplayer.net.bluetooth.device; import android.bluetooth.BluetoothSocket; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import temple.multiplayer.net.common.service.ServiceMessageKeys; import temple.multiplayer.net.common.service.ServiceMessageType; /** * This thread runs during a connection with a remote device. * It handles all incoming and outgoing transmissions. */ public class BluetoothCommunicationThread extends Thread { private static final String TAG = BluetoothCommunicationThread.class.getSimpleName(); private final BluetoothSocket _socket; private final InputStream _inputStream; private final OutputStream _outputStream; private String _deviceAddress; private final Handler _handler; private ConnectionLostListener _connectionLostListener; private boolean _debug; private String _splitter; public BluetoothCommunicationThread(BluetoothSocket socket, String deviceAddress, Handler handler) { this(socket, deviceAddress, handler, false); } public BluetoothCommunicationThread(BluetoothSocket socket, String deviceAddress, Handler handler, boolean debug) { _debug = debug; if (_debug) Log.d(TAG, "BluetoothCommunicationThread: created"); _deviceAddress = deviceAddress; _handler = handler; _socket = socket; byte[] splitChar = {0}; _splitter = new String(splitChar, 0, 1); InputStream inputStream = null; OutputStream outputStream = null; // Get the BluetoothSocket input and output streams try { inputStream = socket.getInputStream(); outputStream = socket.getOutputStream(); } catch (IOException e) { Log.e(TAG, "BluetoothCommunicationThread: streams not created"); e.printStackTrace(); } _inputStream = inputStream; _outputStream = outputStream; } public void run() { byte[] buffer = new byte[1024]; int byteCount; String messages = ""; boolean eof; if (_debug) Log.d(TAG, "run: starting to listen to socket"); // Keep listening to the InputStream while connected while (true) { try { if (_debug) Log.d(TAG, "run: starting to read, messages = '" + messages + "'"); // Read from the InputStream byteCount = _inputStream.read(buffer); eof = (buffer[byteCount - 1] == 0); if (_debug) Log.d(TAG, "run: first read, " + byteCount + " bytes received, last char = " + buffer[byteCount - 1] + ", eof = " + eof); int size = eof ? byteCount - 1 : byteCount; if (size > 0) { messages += new String(buffer, 0, eof ? byteCount - 1 : byteCount); } if (_debug) Log.d(TAG, "run: first: messages = " + messages); if (eof) { if (_debug) Log.d(TAG, "run: eof, sending messages"); String[] messageParts = messages.split(_splitter); if (_debug) Log.d(TAG, "run: " + messageParts.length + " message parts found"); for (String messagePart : messageParts) { if (messagePart.length() > 0) { if (_debug) Log.d(TAG, "run: sending message: " + messagePart); // Send the obtained bytes to the UI Activity Message message = _handler.obtainMessage(ServiceMessageType.MESSAGE_READ.ordinal(), messagePart.length(), -1, messagePart.getBytes()); Bundle bundle = new Bundle(); bundle.putString(ServiceMessageKeys.DEVICE_ADDRESS, _deviceAddress); message.setData(bundle); message.sendToTarget(); } } if (_debug) Log.d(TAG, "run: clearing messages"); messages = ""; } } catch (IOException e) { Log.e(TAG, "run: failed to read, disconnected"); if (_connectionLostListener != null) { _connectionLostListener.onConnectionLost(); } break; } } } /** * Write to the connected OutStream. * * @param buffer The bytes to write */ public void write(byte[] buffer) { if (_debug) Log.d(TAG, "write: " + buffer.length + " bytes to write"); try { _outputStream.write(buffer); _outputStream.write(0); } catch (IOException e) { Log.e(TAG, "Exception during write", e); } } public void cancel() { try { _socket.close(); } catch (IOException e) { Log.e(TAG, "cancel: close failed"); e.printStackTrace(); } } public void setDebug(boolean debug) { _debug = debug; } public interface ConnectionLostListener { void onConnectionLost(); } public void setConnectionLostListener(ConnectionLostListener listener) { _connectionLostListener = listener; } }
{ "content_hash": "bf604fecf3c8efff8cb6962fbee671d8", "timestamp": "", "source": "github", "line_count": 158, "max_line_length": 162, "avg_line_length": 34.28481012658228, "alnum_prop": 0.57282628761307, "repo_name": "MediaMonks/tilt-game-android", "id": "be4ba7593d93653d9df83a8dd42e88e8928d3654", "size": "5417", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "temple_multiplayer/src/main/java/temple/multiplayer/net/bluetooth/device/BluetoothCommunicationThread.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "716" }, { "name": "C", "bytes": "38728" }, { "name": "C++", "bytes": "521627" }, { "name": "IDL", "bytes": "9203" }, { "name": "Java", "bytes": "3520599" }, { "name": "Makefile", "bytes": "5933" }, { "name": "Ruby", "bytes": "1977" }, { "name": "Shell", "bytes": "3942" } ], "symlink_target": "" }
"""The type mappings for the ``simplejson``-like API. In particular, this module provides the extension to native Python data types with particulars of the Ion data model. """ # Python 2/3 compatibility from __future__ import absolute_import from __future__ import division from __future__ import print_function from decimal import Decimal from collections import MutableMapping import six from amazon.ion.symbols import SymbolToken from .core import TIMESTAMP_PRECISION_FIELD from .core import Multimap, Timestamp, IonEvent, IonType, TIMESTAMP_FRACTION_PRECISION_FIELD, TimestampPrecision, \ MICROSECOND_PRECISION, TIMESTAMP_FRACTIONAL_SECONDS_FIELD class _IonNature(object): """Mix-in for Ion related properties. Attributes: ion_event (Optional[IonEvent]): The event, if any associated with the value. ion_type (IonType): The Ion type for the value. ion_annotations (Sequence[unicode]): The annotations associated with the value. Notes: There is no ``field_name`` attribute as that is generally modeled as a property of the container. The ``ion_event`` field is only provided if the value was derived from a low-level event. User constructed values will generally not set this field. """ def __init__(self, *args, **kwargs): self.ion_type = None self.ion_annotations = () def _copy(self): """Copies this instance. Its IonEvent (if any) is not preserved. Keeping this protected until/unless we decide there's use for it publicly. """ args, kwargs = self._to_constructor_args(self) value = self.__class__(*args, **kwargs) value.ion_type = self.ion_type value.ion_annotations = self.ion_annotations return value @staticmethod def _to_constructor_args(value): return (value, ), {} @classmethod def from_event(cls, ion_event): """Constructs the given native extension from the properties of an event. Args: ion_event (IonEvent): The event to construct the native value from. """ if ion_event.value is not None: args, kwargs = cls._to_constructor_args(ion_event.value) else: # if value is None (i.e. this is a container event), args must be empty or initialization of the # underlying container will fail. args, kwargs = (), {} value = cls(*args, **kwargs) value.ion_type = ion_event.ion_type value.ion_annotations = ion_event.annotations return value @classmethod def from_value(cls, ion_type, value, annotations=()): """Constructs a value as a copy with an associated Ion type and annotations. Args: ion_type (IonType): The associated Ion type. value (Any): The value to construct from, generally of type ``cls``. annotations (Sequence[unicode]): The sequence Unicode strings decorating this value. """ if value is None: value = IonPyNull() else: args, kwargs = cls._to_constructor_args(value) value = cls(*args, **kwargs) value.ion_type = ion_type value.ion_annotations = annotations return value def to_event(self, event_type, field_name=None, in_struct=False, depth=None): """Constructs an IonEvent from this _IonNature value. Args: event_type (IonEventType): The type of the resulting event. field_name (Optional[text]): The field name associated with this value, if any. When ``None`` is specified and ``in_struct`` is ``True``, the returned event's ``field_name`` will represent symbol zero (a ``SymbolToken`` with text=None and sid=0). in_struct (Optional[True|False]): When ``True``, indicates the returned event ``field_name`` will be populated. When ``False``, ``field_name`` will be ``None``. depth (Optional[int]): The depth of this value. Returns: An IonEvent with the properties from this value. """ value = self if isinstance(self, IonPyNull) or self.ion_type.is_container: value = None if in_struct: if not isinstance(field_name, SymbolToken): field_name = SymbolToken(field_name, 0 if field_name is None else None) else: field_name = None return IonEvent(event_type, ion_type=self.ion_type, value=value, field_name=field_name, annotations=self.ion_annotations, depth=depth) def _ion_type_for(name, base_cls): class IonPyValueType(base_cls, _IonNature): def __init__(self, *args, **kwargs): super(IonPyValueType, self).__init__(*args, **kwargs) IonPyValueType.__name__ = name IonPyValueType.__qualname__ = name return IonPyValueType if six.PY2: IonPyInt = _ion_type_for('IonPyInt', long) else: IonPyInt = _ion_type_for('IonPyInt', int) IonPyBool = IonPyInt IonPyFloat = _ion_type_for('IonPyFloat', float) IonPyDecimal = _ion_type_for('IonPyDecimal', Decimal) IonPyText = _ion_type_for('IonPyText', six.text_type) IonPyBytes = _ion_type_for('IonPyBytes', six.binary_type) class IonPySymbol(SymbolToken, _IonNature): def __init__(self, *args, **kwargs): super(IonPySymbol, self).__init__(*args, **kwargs) @staticmethod def _to_constructor_args(st): try: args = (st.text, st.sid, st.location) except AttributeError: args = (st, None, None) kwargs = {} return args, kwargs class IonPyTimestamp(Timestamp, _IonNature): def __init__(self, *args, **kwargs): super(IonPyTimestamp, self).__init__(*args, **kwargs) @staticmethod def _to_constructor_args(ts): if isinstance(ts, Timestamp): args = (ts.year, ts.month, ts.day, ts.hour, ts.minute, ts.second, None, ts.tzinfo) fractional_seconds = getattr(ts, TIMESTAMP_FRACTIONAL_SECONDS_FIELD, None) precision = getattr(ts, TIMESTAMP_PRECISION_FIELD, TimestampPrecision.SECOND) kwargs = {TIMESTAMP_PRECISION_FIELD: precision, TIMESTAMP_FRACTIONAL_SECONDS_FIELD: fractional_seconds} else: args = (ts.year, ts.month, ts.day, ts.hour, ts.minute, ts.second, ts.microsecond, ts.tzinfo) kwargs = {TIMESTAMP_PRECISION_FIELD: TimestampPrecision.SECOND} return args, kwargs class IonPyNull(_IonNature): """Representation of ``null``. Notes: ``None`` is a singleton and cannot be sub-classed, so we have our own value type for it. The function ``is_null`` is the best way to test for ``null``-ness or ``None``-ness. """ def __init__(self, *args, **kwargs): super(IonPyNull, self).__init__(*args, **kwargs) def __nonzero__(self): return False def __bool__(self): return False @staticmethod def _to_constructor_args(value): return (), {} def is_null(value): """A mechanism to determine if a value is ``None`` or an Ion ``null``.""" return value is None or isinstance(value, IonPyNull) IonPyList = _ion_type_for('IonPyList', list) IonPyDict = _ion_type_for('IonPyDict', Multimap)
{ "content_hash": "c945eee0dafd18235b42e8665ee9c161", "timestamp": "", "source": "github", "line_count": 205, "max_line_length": 115, "avg_line_length": 35.78536585365854, "alnum_prop": 0.629907306434024, "repo_name": "almann/ion-python", "id": "9db902da13cc3d7944ff53dcc3aaf033ca784602", "size": "7904", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "amazon/ion/simple_types.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "537096" } ], "symlink_target": "" }
package android.graphics.drawable; import android.annotation.NonNull; import android.content.res.ColorStateList; import android.content.res.Resources; import android.content.res.Resources.Theme; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.BitmapShader; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.Insets; import android.graphics.Matrix; import android.graphics.Outline; import android.graphics.Paint; import android.graphics.PixelFormat; import android.graphics.PorterDuff; import android.graphics.PorterDuff.Mode; import android.graphics.PorterDuffColorFilter; import android.graphics.Rect; import android.graphics.Shader; import android.graphics.Xfermode; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.util.LayoutDirection; import android.view.Gravity; import com.android.internal.R; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.util.Collection; /** * A Drawable that wraps a bitmap and can be tiled, stretched, or aligned. You can create a * BitmapDrawable from a file path, an input stream, through XML inflation, or from * a {@link android.graphics.Bitmap} object. * <p>It can be defined in an XML file with the <code>&lt;bitmap></code> element. For more * information, see the guide to <a * href="{@docRoot}guide/topics/resources/drawable-resource.html">Drawable Resources</a>.</p> * <p> * Also see the {@link android.graphics.Bitmap} class, which handles the management and * transformation of raw bitmap graphics, and should be used when drawing to a * {@link android.graphics.Canvas}. * </p> * * @attr ref android.R.styleable#BitmapDrawable_src * @attr ref android.R.styleable#BitmapDrawable_antialias * @attr ref android.R.styleable#BitmapDrawable_filter * @attr ref android.R.styleable#BitmapDrawable_dither * @attr ref android.R.styleable#BitmapDrawable_gravity * @attr ref android.R.styleable#BitmapDrawable_mipMap * @attr ref android.R.styleable#BitmapDrawable_tileMode */ public class BitmapDrawable extends Drawable { private static final int DEFAULT_PAINT_FLAGS = Paint.FILTER_BITMAP_FLAG | Paint.DITHER_FLAG; // Constants for {@link android.R.styleable#BitmapDrawable_tileMode}. private static final int TILE_MODE_UNDEFINED = -2; private static final int TILE_MODE_DISABLED = -1; private static final int TILE_MODE_CLAMP = 0; private static final int TILE_MODE_REPEAT = 1; private static final int TILE_MODE_MIRROR = 2; private final Rect mDstRect = new Rect(); // #updateDstRectAndInsetsIfDirty() sets this private BitmapState mBitmapState; private PorterDuffColorFilter mTintFilter; private int mTargetDensity = DisplayMetrics.DENSITY_DEFAULT; private boolean mDstRectAndInsetsDirty = true; private boolean mMutated; // These are scaled to match the target density. private int mBitmapWidth; private int mBitmapHeight; /** Optical insets due to gravity. */ private Insets mOpticalInsets = Insets.NONE; // Mirroring matrix for using with Shaders private Matrix mMirrorMatrix; /** * Create an empty drawable, not dealing with density. * @deprecated Use {@link #BitmapDrawable(android.content.res.Resources, android.graphics.Bitmap)} * instead to specify a bitmap to draw with and ensure the correct density is set. */ @Deprecated public BitmapDrawable() { mBitmapState = new BitmapState((Bitmap) null); } /** * Create an empty drawable, setting initial target density based on * the display metrics of the resources. * * @deprecated Use {@link #BitmapDrawable(android.content.res.Resources, android.graphics.Bitmap)} * instead to specify a bitmap to draw with. */ @SuppressWarnings("unused") @Deprecated public BitmapDrawable(Resources res) { mBitmapState = new BitmapState((Bitmap) null); mBitmapState.mTargetDensity = mTargetDensity; } /** * Create drawable from a bitmap, not dealing with density. * @deprecated Use {@link #BitmapDrawable(Resources, Bitmap)} to ensure * that the drawable has correctly set its target density. */ @Deprecated public BitmapDrawable(Bitmap bitmap) { this(new BitmapState(bitmap), null); } /** * Create drawable from a bitmap, setting initial target density based on * the display metrics of the resources. */ public BitmapDrawable(Resources res, Bitmap bitmap) { this(new BitmapState(bitmap), res); mBitmapState.mTargetDensity = mTargetDensity; } /** * Create a drawable by opening a given file path and decoding the bitmap. * @deprecated Use {@link #BitmapDrawable(Resources, String)} to ensure * that the drawable has correctly set its target density. */ @Deprecated public BitmapDrawable(String filepath) { this(new BitmapState(BitmapFactory.decodeFile(filepath)), null); if (mBitmapState.mBitmap == null) { android.util.Log.w("BitmapDrawable", "BitmapDrawable cannot decode " + filepath); } } /** * Create a drawable by opening a given file path and decoding the bitmap. */ @SuppressWarnings("unused") public BitmapDrawable(Resources res, String filepath) { this(new BitmapState(BitmapFactory.decodeFile(filepath)), null); mBitmapState.mTargetDensity = mTargetDensity; if (mBitmapState.mBitmap == null) { android.util.Log.w("BitmapDrawable", "BitmapDrawable cannot decode " + filepath); } } /** * Create a drawable by decoding a bitmap from the given input stream. * @deprecated Use {@link #BitmapDrawable(Resources, java.io.InputStream)} to ensure * that the drawable has correctly set its target density. */ @Deprecated public BitmapDrawable(java.io.InputStream is) { this(new BitmapState(BitmapFactory.decodeStream(is)), null); if (mBitmapState.mBitmap == null) { android.util.Log.w("BitmapDrawable", "BitmapDrawable cannot decode " + is); } } /** * Create a drawable by decoding a bitmap from the given input stream. */ @SuppressWarnings("unused") public BitmapDrawable(Resources res, java.io.InputStream is) { this(new BitmapState(BitmapFactory.decodeStream(is)), null); mBitmapState.mTargetDensity = mTargetDensity; if (mBitmapState.mBitmap == null) { android.util.Log.w("BitmapDrawable", "BitmapDrawable cannot decode " + is); } } /** * Returns the paint used to render this drawable. */ public final Paint getPaint() { return mBitmapState.mPaint; } /** * Returns the bitmap used by this drawable to render. May be null. */ public final Bitmap getBitmap() { return mBitmapState.mBitmap; } private void computeBitmapSize() { final Bitmap bitmap = mBitmapState.mBitmap; if (bitmap != null) { mBitmapWidth = bitmap.getScaledWidth(mTargetDensity); mBitmapHeight = bitmap.getScaledHeight(mTargetDensity); } else { mBitmapWidth = mBitmapHeight = -1; } } /** @hide */ protected void setBitmap(Bitmap bitmap) { if (mBitmapState.mBitmap != bitmap) { mBitmapState.mBitmap = bitmap; computeBitmapSize(); invalidateSelf(); } } /** * Set the density scale at which this drawable will be rendered. This * method assumes the drawable will be rendered at the same density as the * specified canvas. * * @param canvas The Canvas from which the density scale must be obtained. * * @see android.graphics.Bitmap#setDensity(int) * @see android.graphics.Bitmap#getDensity() */ public void setTargetDensity(Canvas canvas) { setTargetDensity(canvas.getDensity()); } /** * Set the density scale at which this drawable will be rendered. * * @param metrics The DisplayMetrics indicating the density scale for this drawable. * * @see android.graphics.Bitmap#setDensity(int) * @see android.graphics.Bitmap#getDensity() */ public void setTargetDensity(DisplayMetrics metrics) { setTargetDensity(metrics.densityDpi); } /** * Set the density at which this drawable will be rendered. * * @param density The density scale for this drawable. * * @see android.graphics.Bitmap#setDensity(int) * @see android.graphics.Bitmap#getDensity() */ public void setTargetDensity(int density) { if (mTargetDensity != density) { mTargetDensity = density == 0 ? DisplayMetrics.DENSITY_DEFAULT : density; if (mBitmapState.mBitmap != null) { computeBitmapSize(); } invalidateSelf(); } } /** Get the gravity used to position/stretch the bitmap within its bounds. * See android.view.Gravity * @return the gravity applied to the bitmap */ public int getGravity() { return mBitmapState.mGravity; } /** Set the gravity used to position/stretch the bitmap within its bounds. See android.view.Gravity * @param gravity the gravity */ public void setGravity(int gravity) { if (mBitmapState.mGravity != gravity) { mBitmapState.mGravity = gravity; mDstRectAndInsetsDirty = true; invalidateSelf(); } } /** * Enables or disables the mipmap hint for this drawable's bitmap. * See {@link Bitmap#setHasMipMap(boolean)} for more information. * * If the bitmap is null calling this method has no effect. * * @param mipMap True if the bitmap should use mipmaps, false otherwise. * * @see #hasMipMap() */ public void setMipMap(boolean mipMap) { if (mBitmapState.mBitmap != null) { mBitmapState.mBitmap.setHasMipMap(mipMap); invalidateSelf(); } } /** * Indicates whether the mipmap hint is enabled on this drawable's bitmap. * * @return True if the mipmap hint is set, false otherwise. If the bitmap * is null, this method always returns false. * * @see #setMipMap(boolean) * @attr ref android.R.styleable#BitmapDrawable_mipMap */ public boolean hasMipMap() { return mBitmapState.mBitmap != null && mBitmapState.mBitmap.hasMipMap(); } /** * Enables or disables anti-aliasing for this drawable. Anti-aliasing affects * the edges of the bitmap only so it applies only when the drawable is rotated. * * @param aa True if the bitmap should be anti-aliased, false otherwise. * * @see #hasAntiAlias() */ public void setAntiAlias(boolean aa) { mBitmapState.mPaint.setAntiAlias(aa); invalidateSelf(); } /** * Indicates whether anti-aliasing is enabled for this drawable. * * @return True if anti-aliasing is enabled, false otherwise. * * @see #setAntiAlias(boolean) */ public boolean hasAntiAlias() { return mBitmapState.mPaint.isAntiAlias(); } @Override public void setFilterBitmap(boolean filter) { mBitmapState.mPaint.setFilterBitmap(filter); invalidateSelf(); } @Override public boolean isFilterBitmap() { return mBitmapState.mPaint.isFilterBitmap(); } @Override public void setDither(boolean dither) { mBitmapState.mPaint.setDither(dither); invalidateSelf(); } /** * Indicates the repeat behavior of this drawable on the X axis. * * @return {@link android.graphics.Shader.TileMode#CLAMP} if the bitmap does not repeat, * {@link android.graphics.Shader.TileMode#REPEAT} or * {@link android.graphics.Shader.TileMode#MIRROR} otherwise. */ public Shader.TileMode getTileModeX() { return mBitmapState.mTileModeX; } /** * Indicates the repeat behavior of this drawable on the Y axis. * * @return {@link android.graphics.Shader.TileMode#CLAMP} if the bitmap does not repeat, * {@link android.graphics.Shader.TileMode#REPEAT} or * {@link android.graphics.Shader.TileMode#MIRROR} otherwise. */ public Shader.TileMode getTileModeY() { return mBitmapState.mTileModeY; } /** * Sets the repeat behavior of this drawable on the X axis. By default, the drawable * does not repeat its bitmap. Using {@link android.graphics.Shader.TileMode#REPEAT} or * {@link android.graphics.Shader.TileMode#MIRROR} the bitmap can be repeated (or tiled) * if the bitmap is smaller than this drawable. * * @param mode The repeat mode for this drawable. * * @see #setTileModeY(android.graphics.Shader.TileMode) * @see #setTileModeXY(android.graphics.Shader.TileMode, android.graphics.Shader.TileMode) * @attr ref android.R.styleable#BitmapDrawable_tileModeX */ public void setTileModeX(Shader.TileMode mode) { setTileModeXY(mode, mBitmapState.mTileModeY); } /** * Sets the repeat behavior of this drawable on the Y axis. By default, the drawable * does not repeat its bitmap. Using {@link android.graphics.Shader.TileMode#REPEAT} or * {@link android.graphics.Shader.TileMode#MIRROR} the bitmap can be repeated (or tiled) * if the bitmap is smaller than this drawable. * * @param mode The repeat mode for this drawable. * * @see #setTileModeX(android.graphics.Shader.TileMode) * @see #setTileModeXY(android.graphics.Shader.TileMode, android.graphics.Shader.TileMode) * @attr ref android.R.styleable#BitmapDrawable_tileModeY */ public final void setTileModeY(Shader.TileMode mode) { setTileModeXY(mBitmapState.mTileModeX, mode); } /** * Sets the repeat behavior of this drawable on both axis. By default, the drawable * does not repeat its bitmap. Using {@link android.graphics.Shader.TileMode#REPEAT} or * {@link android.graphics.Shader.TileMode#MIRROR} the bitmap can be repeated (or tiled) * if the bitmap is smaller than this drawable. * * @param xmode The X repeat mode for this drawable. * @param ymode The Y repeat mode for this drawable. * * @see #setTileModeX(android.graphics.Shader.TileMode) * @see #setTileModeY(android.graphics.Shader.TileMode) */ public void setTileModeXY(Shader.TileMode xmode, Shader.TileMode ymode) { final BitmapState state = mBitmapState; if (state.mTileModeX != xmode || state.mTileModeY != ymode) { state.mTileModeX = xmode; state.mTileModeY = ymode; state.mRebuildShader = true; mDstRectAndInsetsDirty = true; invalidateSelf(); } } @Override public void setAutoMirrored(boolean mirrored) { if (mBitmapState.mAutoMirrored != mirrored) { mBitmapState.mAutoMirrored = mirrored; invalidateSelf(); } } @Override public final boolean isAutoMirrored() { return mBitmapState.mAutoMirrored; } @Override public int getChangingConfigurations() { return super.getChangingConfigurations() | mBitmapState.getChangingConfigurations(); } private boolean needMirroring() { return isAutoMirrored() && getLayoutDirection() == LayoutDirection.RTL; } private void updateMirrorMatrix(float dx) { if (mMirrorMatrix == null) { mMirrorMatrix = new Matrix(); } mMirrorMatrix.setTranslate(dx, 0); mMirrorMatrix.preScale(-1.0f, 1.0f); } @Override protected void onBoundsChange(Rect bounds) { mDstRectAndInsetsDirty = true; final Shader shader = mBitmapState.mPaint.getShader(); if (shader != null) { if (needMirroring()) { updateMirrorMatrix(bounds.right - bounds.left); shader.setLocalMatrix(mMirrorMatrix); mBitmapState.mPaint.setShader(shader); } else { if (mMirrorMatrix != null) { mMirrorMatrix = null; shader.setLocalMatrix(Matrix.IDENTITY_MATRIX); mBitmapState.mPaint.setShader(shader); } } } } @Override public void draw(Canvas canvas) { final Bitmap bitmap = mBitmapState.mBitmap; if (bitmap == null) { return; } final BitmapState state = mBitmapState; final Paint paint = state.mPaint; if (state.mRebuildShader) { final Shader.TileMode tmx = state.mTileModeX; final Shader.TileMode tmy = state.mTileModeY; if (tmx == null && tmy == null) { paint.setShader(null); } else { paint.setShader(new BitmapShader(bitmap, tmx == null ? Shader.TileMode.CLAMP : tmx, tmy == null ? Shader.TileMode.CLAMP : tmy)); } state.mRebuildShader = false; } final int restoreAlpha; if (state.mBaseAlpha != 1.0f) { final Paint p = getPaint(); restoreAlpha = p.getAlpha(); p.setAlpha((int) (restoreAlpha * state.mBaseAlpha + 0.5f)); } else { restoreAlpha = -1; } final boolean clearColorFilter; if (mTintFilter != null && paint.getColorFilter() == null) { paint.setColorFilter(mTintFilter); clearColorFilter = true; } else { clearColorFilter = false; } updateDstRectAndInsetsIfDirty(); final Shader shader = paint.getShader(); final boolean needMirroring = needMirroring(); if (shader == null) { if (needMirroring) { canvas.save(); // Mirror the bitmap canvas.translate(mDstRect.right - mDstRect.left, 0); canvas.scale(-1.0f, 1.0f); } canvas.drawBitmap(bitmap, null, mDstRect, paint); if (needMirroring) { canvas.restore(); } } else { if (needMirroring) { // Mirror the bitmap updateMirrorMatrix(mDstRect.right - mDstRect.left); shader.setLocalMatrix(mMirrorMatrix); paint.setShader(shader); } else { if (mMirrorMatrix != null) { mMirrorMatrix = null; shader.setLocalMatrix(Matrix.IDENTITY_MATRIX); paint.setShader(shader); } } canvas.drawRect(mDstRect, paint); } if (clearColorFilter) { paint.setColorFilter(null); } if (restoreAlpha >= 0) { paint.setAlpha(restoreAlpha); } } private void updateDstRectAndInsetsIfDirty() { if (mDstRectAndInsetsDirty) { if (mBitmapState.mTileModeX == null && mBitmapState.mTileModeY == null) { final Rect bounds = getBounds(); final int layoutDirection = getLayoutDirection(); Gravity.apply(mBitmapState.mGravity, mBitmapWidth, mBitmapHeight, bounds, mDstRect, layoutDirection); final int left = mDstRect.left - bounds.left; final int top = mDstRect.top - bounds.top; final int right = bounds.right - mDstRect.right; final int bottom = bounds.bottom - mDstRect.bottom; mOpticalInsets = Insets.of(left, top, right, bottom); } else { copyBounds(mDstRect); mOpticalInsets = Insets.NONE; } } mDstRectAndInsetsDirty = false; } /** * @hide */ @Override public Insets getOpticalInsets() { updateDstRectAndInsetsIfDirty(); return mOpticalInsets; } @Override public void getOutline(@NonNull Outline outline) { updateDstRectAndInsetsIfDirty(); outline.setRect(mDstRect); // Only opaque Bitmaps can report a non-0 alpha, // since only they are guaranteed to fill their bounds boolean opaqueOverShape = mBitmapState.mBitmap != null && !mBitmapState.mBitmap.hasAlpha(); outline.setAlpha(opaqueOverShape ? getAlpha() / 255.0f : 0.0f); } @Override public void setAlpha(int alpha) { final int oldAlpha = mBitmapState.mPaint.getAlpha(); if (alpha != oldAlpha) { mBitmapState.mPaint.setAlpha(alpha); invalidateSelf(); } } @Override public int getAlpha() { return mBitmapState.mPaint.getAlpha(); } @Override public void setColorFilter(ColorFilter colorFilter) { mBitmapState.mPaint.setColorFilter(colorFilter); invalidateSelf(); } @Override public ColorFilter getColorFilter() { return mBitmapState.mPaint.getColorFilter(); } @Override public void setTintList(ColorStateList tint) { mBitmapState.mTint = tint; mTintFilter = updateTintFilter(mTintFilter, tint, mBitmapState.mTintMode); invalidateSelf(); } @Override public void setTintMode(PorterDuff.Mode tintMode) { mBitmapState.mTintMode = tintMode; mTintFilter = updateTintFilter(mTintFilter, mBitmapState.mTint, tintMode); invalidateSelf(); } /** * @hide only needed by a hack within ProgressBar */ public ColorStateList getTint() { return mBitmapState.mTint; } /** * @hide only needed by a hack within ProgressBar */ public Mode getTintMode() { return mBitmapState.mTintMode; } /** * @hide Candidate for future API inclusion */ @Override public void setXfermode(Xfermode xfermode) { mBitmapState.mPaint.setXfermode(xfermode); invalidateSelf(); } /** * A mutable BitmapDrawable still shares its Bitmap with any other Drawable * that comes from the same resource. * * @return This drawable. */ @Override public Drawable mutate() { if (!mMutated && super.mutate() == this) { mBitmapState = new BitmapState(mBitmapState); mMutated = true; } return this; } /** * @hide */ public void clearMutated() { super.clearMutated(); mMutated = false; } @Override protected boolean onStateChange(int[] stateSet) { final BitmapState state = mBitmapState; if (state.mTint != null && state.mTintMode != null) { mTintFilter = updateTintFilter(mTintFilter, state.mTint, state.mTintMode); return true; } return false; } @Override public boolean isStateful() { return (mBitmapState.mTint != null && mBitmapState.mTint.isStateful()) || super.isStateful(); } @Override public void inflate(Resources r, XmlPullParser parser, AttributeSet attrs, Theme theme) throws XmlPullParserException, IOException { super.inflate(r, parser, attrs, theme); final TypedArray a = obtainAttributes(r, theme, attrs, R.styleable.BitmapDrawable); updateStateFromTypedArray(a); verifyRequiredAttributes(a); a.recycle(); // Update local properties. updateLocalState(r); } /** * Ensures all required attributes are set. * * @throws XmlPullParserException if any required attributes are missing */ private void verifyRequiredAttributes(TypedArray a) throws XmlPullParserException { // If we're not waiting on a theme, verify required attributes. final BitmapState state = mBitmapState; if (state.mBitmap == null && (state.mThemeAttrs == null || state.mThemeAttrs[R.styleable.BitmapDrawable_src] == 0)) { throw new XmlPullParserException(a.getPositionDescription() + ": <bitmap> requires a valid 'src' attribute"); } } /** * Updates the constant state from the values in the typed array. */ private void updateStateFromTypedArray(TypedArray a) throws XmlPullParserException { final Resources r = a.getResources(); final BitmapState state = mBitmapState; // Account for any configuration changes. state.mChangingConfigurations |= a.getChangingConfigurations(); // Extract the theme attributes, if any. state.mThemeAttrs = a.extractThemeAttrs(); final int srcResId = a.getResourceId(R.styleable.BitmapDrawable_src, 0); if (srcResId != 0) { final Bitmap bitmap = BitmapFactory.decodeResource(r, srcResId); if (bitmap == null) { throw new XmlPullParserException(a.getPositionDescription() + ": <bitmap> requires a valid 'src' attribute"); } state.mBitmap = bitmap; } state.mTargetDensity = r.getDisplayMetrics().densityDpi; final boolean defMipMap = state.mBitmap != null ? state.mBitmap.hasMipMap() : false; setMipMap(a.getBoolean(R.styleable.BitmapDrawable_mipMap, defMipMap)); state.mAutoMirrored = a.getBoolean( R.styleable.BitmapDrawable_autoMirrored, state.mAutoMirrored); state.mBaseAlpha = a.getFloat(R.styleable.BitmapDrawable_alpha, state.mBaseAlpha); final int tintMode = a.getInt(R.styleable.BitmapDrawable_tintMode, -1); if (tintMode != -1) { state.mTintMode = Drawable.parseTintMode(tintMode, Mode.SRC_IN); } final ColorStateList tint = a.getColorStateList(R.styleable.BitmapDrawable_tint); if (tint != null) { state.mTint = tint; } final Paint paint = mBitmapState.mPaint; paint.setAntiAlias(a.getBoolean( R.styleable.BitmapDrawable_antialias, paint.isAntiAlias())); paint.setFilterBitmap(a.getBoolean( R.styleable.BitmapDrawable_filter, paint.isFilterBitmap())); paint.setDither(a.getBoolean(R.styleable.BitmapDrawable_dither, paint.isDither())); setGravity(a.getInt(R.styleable.BitmapDrawable_gravity, state.mGravity)); final int tileMode = a.getInt(R.styleable.BitmapDrawable_tileMode, TILE_MODE_UNDEFINED); if (tileMode != TILE_MODE_UNDEFINED) { final Shader.TileMode mode = parseTileMode(tileMode); setTileModeXY(mode, mode); } final int tileModeX = a.getInt(R.styleable.BitmapDrawable_tileModeX, TILE_MODE_UNDEFINED); if (tileModeX != TILE_MODE_UNDEFINED) { setTileModeX(parseTileMode(tileModeX)); } final int tileModeY = a.getInt(R.styleable.BitmapDrawable_tileModeY, TILE_MODE_UNDEFINED); if (tileModeY != TILE_MODE_UNDEFINED) { setTileModeY(parseTileMode(tileModeY)); } final int densityDpi = r.getDisplayMetrics().densityDpi; state.mTargetDensity = densityDpi == 0 ? DisplayMetrics.DENSITY_DEFAULT : densityDpi; } @Override public void applyTheme(Theme t) { super.applyTheme(t); final BitmapState state = mBitmapState; if (state == null) { return; } if (state.mThemeAttrs != null) { final TypedArray a = t.resolveAttributes(state.mThemeAttrs, R.styleable.BitmapDrawable); try { updateStateFromTypedArray(a); } catch (XmlPullParserException e) { throw new RuntimeException(e); } finally { a.recycle(); } } // Apply theme to contained color state list. if (state.mTint != null && state.mTint.canApplyTheme()) { state.mTint = state.mTint.obtainForTheme(t); } // Update local properties. updateLocalState(t.getResources()); } private static Shader.TileMode parseTileMode(int tileMode) { switch (tileMode) { case TILE_MODE_CLAMP: return Shader.TileMode.CLAMP; case TILE_MODE_REPEAT: return Shader.TileMode.REPEAT; case TILE_MODE_MIRROR: return Shader.TileMode.MIRROR; default: return null; } } @Override public boolean canApplyTheme() { return mBitmapState != null && mBitmapState.canApplyTheme(); } @Override public int getIntrinsicWidth() { return mBitmapWidth; } @Override public int getIntrinsicHeight() { return mBitmapHeight; } @Override public int getOpacity() { if (mBitmapState.mGravity != Gravity.FILL) { return PixelFormat.TRANSLUCENT; } final Bitmap bitmap = mBitmapState.mBitmap; return (bitmap == null || bitmap.hasAlpha() || mBitmapState.mPaint.getAlpha() < 255) ? PixelFormat.TRANSLUCENT : PixelFormat.OPAQUE; } @Override public final ConstantState getConstantState() { mBitmapState.mChangingConfigurations |= getChangingConfigurations(); return mBitmapState; } final static class BitmapState extends ConstantState { final Paint mPaint; // Values loaded during inflation. int[] mThemeAttrs = null; Bitmap mBitmap = null; ColorStateList mTint = null; Mode mTintMode = DEFAULT_TINT_MODE; int mGravity = Gravity.FILL; float mBaseAlpha = 1.0f; Shader.TileMode mTileModeX = null; Shader.TileMode mTileModeY = null; int mTargetDensity = DisplayMetrics.DENSITY_DEFAULT; boolean mAutoMirrored = false; int mChangingConfigurations; boolean mRebuildShader; BitmapState(Bitmap bitmap) { mBitmap = bitmap; mPaint = new Paint(DEFAULT_PAINT_FLAGS); } BitmapState(BitmapState bitmapState) { mBitmap = bitmapState.mBitmap; mTint = bitmapState.mTint; mTintMode = bitmapState.mTintMode; mThemeAttrs = bitmapState.mThemeAttrs; mChangingConfigurations = bitmapState.mChangingConfigurations; mGravity = bitmapState.mGravity; mTileModeX = bitmapState.mTileModeX; mTileModeY = bitmapState.mTileModeY; mTargetDensity = bitmapState.mTargetDensity; mBaseAlpha = bitmapState.mBaseAlpha; mPaint = new Paint(bitmapState.mPaint); mRebuildShader = bitmapState.mRebuildShader; mAutoMirrored = bitmapState.mAutoMirrored; } @Override public boolean canApplyTheme() { return mThemeAttrs != null || mTint != null && mTint.canApplyTheme(); } @Override public int addAtlasableBitmaps(Collection<Bitmap> atlasList) { if (isAtlasable(mBitmap) && atlasList.add(mBitmap)) { return mBitmap.getWidth() * mBitmap.getHeight(); } return 0; } @Override public Drawable newDrawable() { return new BitmapDrawable(this, null); } @Override public Drawable newDrawable(Resources res) { return new BitmapDrawable(this, res); } @Override public int getChangingConfigurations() { return mChangingConfigurations | (mTint != null ? mTint.getChangingConfigurations() : 0); } } /** * The one constructor to rule them all. This is called by all public * constructors to set the state and initialize local properties. */ private BitmapDrawable(BitmapState state, Resources res) { mBitmapState = state; updateLocalState(res); } /** * Initializes local dynamic properties from state. This should be called * after significant state changes, e.g. from the One True Constructor and * after inflating or applying a theme. */ private void updateLocalState(Resources res) { if (res != null) { final int densityDpi = res.getDisplayMetrics().densityDpi; mTargetDensity = densityDpi == 0 ? DisplayMetrics.DENSITY_DEFAULT : densityDpi; } else { mTargetDensity = mBitmapState.mTargetDensity; } mTintFilter = updateTintFilter(mTintFilter, mBitmapState.mTint, mBitmapState.mTintMode); computeBitmapSize(); } }
{ "content_hash": "7e56bdd61ff4f0f09134cc632000b6b1", "timestamp": "", "source": "github", "line_count": 974, "max_line_length": 102, "avg_line_length": 33.91581108829569, "alnum_prop": 0.6295634800508567, "repo_name": "Ant-Droid/android_frameworks_base_OLD", "id": "cf91be1ea364c4bcbd6d8834f05a91c201376940", "size": "33653", "binary": false, "copies": "3", "ref": "refs/heads/mm600", "path": "graphics/java/android/graphics/drawable/BitmapDrawable.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "167132" }, { "name": "C++", "bytes": "7099875" }, { "name": "GLSL", "bytes": "20654" }, { "name": "HTML", "bytes": "224185" }, { "name": "Java", "bytes": "79415679" }, { "name": "Makefile", "bytes": "419370" }, { "name": "Python", "bytes": "42309" }, { "name": "RenderScript", "bytes": "153826" }, { "name": "Shell", "bytes": "21079" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "1bccaed33e7697cf5813d6ce813c0560", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "7a38e0b67cd14c570956bd60d6230e4b88388c68", "size": "176", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Boraginales/Boraginaceae/Amsinckia/Amsinckia hispidula/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package edu.hnu.webapp.conf; import com.jfinal.config.Routes; /** * APP端Routes配置 * @author simon * */ public class ApiRoutes extends Routes{ @Override public void config() { } }
{ "content_hash": "ad74010e24fa817507c1823cc100198c", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 38, "avg_line_length": 11.294117647058824, "alnum_prop": 0.6770833333333334, "repo_name": "xgl1999/hnudemo", "id": "f187970555677f07a59efc0e9cd8d878f6a34d8e", "size": "825", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/edu/hnu/webapp/conf/ApiRoutes.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1586632" }, { "name": "Java", "bytes": "569627" }, { "name": "JavaScript", "bytes": "2528190" } ], "symlink_target": "" }
module HasOffers.API.Affiliate.BrandDesign where import Data.Text import GHC.Generics import Data.Aeson import Control.Applicative import Network.HTTP.Client import qualified Data.ByteString.Char8 as BS import HasOffers.API.Common --------------------------------------------------------------------------------
{ "content_hash": "8c7aa7223409ba26adc4c00aa7488be9", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 80, "avg_line_length": 24.76923076923077, "alnum_prop": 0.6149068322981367, "repo_name": "kelecorix/api-hasoffers", "id": "94f3d4975f65c82e61b67dffa1962ba07be982d9", "size": "322", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/HasOffers/API/Affiliate/BrandDesign.hs", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
@charset "utf-8"; /*css reset*/ body,dd,dl,dt,h1,h2,h3,h4,h5,ul,ol,li,p,form,select,input{margin:0;padding:0} ul,li {list-style:none;} img {border: none;} input,select{font-family: "Arial","Microsoft YaHei"} input[type="checkbox"], input[type="radio"] {margin: 0;vertical-align: middle;margin-right: 2px;margin-top: -2px;border:none;} :focus{outline:0} form,fieldset{margin:0; padding:0; word-wrap:break-word; word-break:normal} button::-moz-focus-inner,input[type=reset]::-moz-focus-inner,input[type=button]::-moz-focus-inner,input[type=submit]::-moz-focus-inner,input[type=file]>input[type=button]::-moz-focus-inner{border:0;padding:0} h1,h2,h3,h4,h5{font-family:"Arial","Microsoft YaHei";font-weight:400;font-size:12px} button,input[type=button],input[type=submit],input[type=reset],input[type=file]{cursor:pointer} em,i{font-style:normal} table{border-collapse:collapse;border-spacing:0;width:100%} th{font-weight:400;text-align:left} /*states*/ .block{display:block} .inline{display:inline} .inline-b{display:inline-block} .none{display:none} .relative{position:relative} .absolute{position:absolute} .strong{font-weight:bold} .tl{text-align:left} .tr{text-align:right} .tc{text-align:center} .vm{vertical-align:middle} .vt{vertical-align:top} .vb{vertical-align:bottom} .fl{float:left} .fr{float:right} .fontstyle{font-style:oblique} .cursor{cursor:pointer} .underline,.underline:hover{text-decoration: underline} .clear{clear:both;} .clearfix:after{content:".";display:block;height:0;clear:both;visibility:hidden} .clearfix{zoom:1} .overflow{overflow: hidden;} /*width & spacing*/ .mr10{margin-right: 10px} .mr20{margin-right: 20px} .mr30{margin-right: 30px} .mb10{margin-bottom: 10px} .mb15{margin-bottom: 15px} .mb20{margin-bottom: 20px} .mb30{margin-bottom: 30px} .mb40{margin-bottom: 30px} .mb50{margin-bottom: 50px} .mb70{margin-bottom: 70px} .pt20{padding-top:20px} .pt30{padding-top:30px} .pb20{padding-bottom:20px} .w996{width: 996px;margin:0 auto;} .indent2em{ text-indent:2em} .borderb{border-bottom:1px #e4e4e4 solid} /*font*/ .f14{font-size:14px} .f16{font-size:16px} .f18{font-size:18px} .f24{font-size:24px;} .sinSun{font-family:"SimSun"} .sinHei{font-family:"SimHei"} .microHei{font-family:"Microsoft YaHei"} .line22{line-height:22px} .line24{line-height:24px} .line30{line-height:30px} /*color*/ .red{color:#f00} .c9{color: #9c9c9c;} .ce3{color:#e3575b} /*body init*/ body{min-width:996px;font-family: "Microsoft YaHei"; color:#282828; font-size:12px} a{color:#282828; text-decoration:none} a:hover{color:red} /*header*/ #header{background:url(../images/idx_01.jpg) no-repeat center top;height:500px ; } #header .top{width: 100%;background: #fff;opacity: 0.8;margin:0 auto; height: 65px;} #header .top .logo {padding-top: 8px;} .header-top{padding:13px 0 55px} .header-wx,.header-wb{background:url(../images/icon.png) no-repeat 0 3px;padding-left:30px;line-height: 24px;display: inline-block;} .header-wb{background-position:0 -47px} .header-wx,.header-wb{padding-bottom:8px} .header-wx span,.header-wb span{position:absolute;top:32px;left:-15px;display:none; box-shadow:3px 5px 10px #070002;z-index:999} .header-wx span img,.header-wb span img{display:block} .header-home{background:#fff url(../images/icon.png) no-repeat center -96px;width:66px;height:65px} /* .nav{background:#fff;width:929px;border-left:1px #b7bfb5 solid;position:relative} */ .nav{background:#fff; position:relative} .nav li{float: left} .nav > li{margin-left:25px;height:65px;line-height:65px;font-size:16px} .nav > li > a{color: #5f5f5f;} .nav > li ul{position:absolute;background:#424242;font-size:14px;width:220px;line-height:40px;text-align:center;padding:5px 0;display:none;} .nav > li ul a{color:#fff;} .nav li ul li{width: 153px;} .nav > li:hover ul{display:block} .nav > .more:hover{background:url(../images/icon.png) no-repeat center -140px} .nav > li ul li{padding-left:30px} .nav > li ul a:hover{color:#b88f91} .nav .nav > li:hover{background-color:#cccccc; font-size: 18px;} .toolbar{border-bottom:1px #e8e8e8 solid;background:#fafafa;height:54px;line-height:54px} #scrollDiv{width:420px;height:54px;line-height:54px;overflow:hidden} #scrollDiv li{height:54px} /*crumb*/ .crumb{line-height:45px} /*footer*/ #footer{padding:50px 0 0;text-align:center; background:url(../images/footer-bg.jpg) repeat-x;height:98px} #footer .footer-menu{margin-bottom: 45px} /**form**/ .ipt-01,.area-01{border:0;background:#fff;height:22px;line-height:22px;padding:6px 5px 7px;width:400px;font-size:14px; vertical-align:middle} .ipt-02{width:110px} .area-01{height:85px;padding:5px} .page{text-align: center;padding: 55px 0;line-height: 23px;text-align:center} .page a,.page span{margin:0 3px;padding:0 8px;color:#757575;display:inline-block;height:23px;border:1px #eee solid} .page a:hover,.page .cur{background-color:#b88f91;color:#fff;} .page .prev{background:url(../images/prev.png) no-repeat 5px center;padding-left:15px} .page .next{background:url(../images/next.png) no-repeat 47px center;padding-right:15px} /*按钮*/ .btn-01{display:inline-block;text-align:center;background: url(../images/btn.png);border:0;cursor: pointer;width:85px;line-height:35px;color: #acacac} .btn-01:hover{color: #fff;background-position: 0 -35px} .btn-02{background:#6c6c6c;color:#fff;width:120px;height:35px;line-height:35px;border:0;cursor:pointer;text-align:center;font-size:14px}
{ "content_hash": "4b7da9f084d692bf2074cec27382ea73", "timestamp": "", "source": "github", "line_count": 133, "max_line_length": 208, "avg_line_length": 40.390977443609025, "alnum_prop": 0.7464631422189129, "repo_name": "cqdewei/cqdewei-php-cms", "id": "80048d0474cb4add774824bc0c430c25f29222c3", "size": "5376", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/home/home/css/common.css", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "240" }, { "name": "CSS", "bytes": "487444" }, { "name": "HTML", "bytes": "93798" }, { "name": "JavaScript", "bytes": "3296918" }, { "name": "PHP", "bytes": "3272229" }, { "name": "Smarty", "bytes": "89274" } ], "symlink_target": "" }
<HTML> <HEAD> <title>Autonomous Systems for SPACE ROBOTICS Lab</title> </HEAD> <BODY BGCOLOR=#FFFFFF TEXT=#000000 LINK=#000FF0 VLINK=#990FFF ALINK=#FF0000> <h1 ALIGN=CENTER>The Autonomous Systems for SPACE ROBOTICS Lab</h1> <h2 ALIGN=CENTER>(Safe, Provably Accurate, Cross-disciplinary Engineering Research On BOunded, Trustworthy Intelligence, and Conditions for Stability)</h2> <P> Oops! There was a problem recompiling the html for the website. One moment, please! I'm sure that our lab members are working right on it... <br><br> </P> <hr> <hr> <P> <i>First updated 2016/09/29. Last updated 2017/03/21.</i> </P> </BODY> </HTML>
{ "content_hash": "b8ed34be92b2f0c43b3bdc7a55e33857", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 155, "avg_line_length": 35.111111111111114, "alnum_prop": 0.740506329113924, "repo_name": "AS4SR/website", "id": "7dd6fb1ffd5f0e5d036d3a8d2c43c381fe7fe063", "size": "632", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public_html/index.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "5990" }, { "name": "HTML", "bytes": "31544" }, { "name": "Python", "bytes": "22316" }, { "name": "Shell", "bytes": "836" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_65) on Tue Feb 04 13:29:24 EST 2014 --> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <TITLE> Function (Storm Core 0.9.1-incubating-SNAPSHOT API) </TITLE> <META NAME="date" CONTENT="2014-02-04"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Function (Storm Core 0.9.1-incubating-SNAPSHOT API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/Function.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../storm/trident/operation/Filter.html" title="interface in storm.trident.operation"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../storm/trident/operation/GroupedMultiReducer.html" title="interface in storm.trident.operation"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../index.html?storm/trident/operation/Function.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="Function.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <!-- ======== START OF CLASS DATA ======== --> <H2> <FONT SIZE="-1"> storm.trident.operation</FONT> <BR> Interface Function</H2> <DL> <DT><B>All Superinterfaces:</B> <DD><A HREF="../../../storm/trident/operation/EachOperation.html" title="interface in storm.trident.operation">EachOperation</A>, <A HREF="../../../storm/trident/operation/Operation.html" title="interface in storm.trident.operation">Operation</A>, <A HREF="http://docs.oracle.com/javase/6/docs/api/java/io/Serializable.html?is-external=true" title="class or interface in java.io">Serializable</A></DD> </DL> <DL> <DT><B>All Known Implementing Classes:</B> <DD><A HREF="../../../storm/trident/operation/BaseFunction.html" title="class in storm.trident.operation">BaseFunction</A>, <A HREF="../../../storm/trident/operation/impl/CombinerAggregatorInitImpl.html" title="class in storm.trident.operation.impl">CombinerAggregatorInitImpl</A>, <A HREF="../../../storm/trident/operation/impl/FilterExecutor.html" title="class in storm.trident.operation.impl">FilterExecutor</A>, <A HREF="../../../storm/trident/testing/Split.html" title="class in storm.trident.testing">Split</A>, <A HREF="../../../storm/trident/testing/StringLength.html" title="class in storm.trident.testing">StringLength</A>, <A HREF="../../../storm/trident/testing/TuplifyArgs.html" title="class in storm.trident.testing">TuplifyArgs</A></DD> </DL> <HR> <DL> <DT><PRE>public interface <B>Function</B><DT>extends <A HREF="../../../storm/trident/operation/EachOperation.html" title="interface in storm.trident.operation">EachOperation</A></DL> </PRE> <P> <HR> <P> <!-- ========== METHOD SUMMARY =========== --> <A NAME="method_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Method Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../storm/trident/operation/Function.html#execute(storm.trident.tuple.TridentTuple, storm.trident.operation.TridentCollector)">execute</A></B>(<A HREF="../../../storm/trident/tuple/TridentTuple.html" title="interface in storm.trident.tuple">TridentTuple</A>&nbsp;tuple, <A HREF="../../../storm/trident/operation/TridentCollector.html" title="interface in storm.trident.operation">TridentCollector</A>&nbsp;collector)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_storm.trident.operation.Operation"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left"><B>Methods inherited from interface storm.trident.operation.<A HREF="../../../storm/trident/operation/Operation.html" title="interface in storm.trident.operation">Operation</A></B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><A HREF="../../../storm/trident/operation/Operation.html#cleanup()">cleanup</A>, <A HREF="../../../storm/trident/operation/Operation.html#prepare(java.util.Map, storm.trident.operation.TridentOperationContext)">prepare</A></CODE></TD> </TR> </TABLE> &nbsp; <P> <!-- ============ METHOD DETAIL ========== --> <A NAME="method_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Method Detail</B></FONT></TH> </TR> </TABLE> <A NAME="execute(storm.trident.tuple.TridentTuple, storm.trident.operation.TridentCollector)"><!-- --></A><H3> execute</H3> <PRE> void <B>execute</B>(<A HREF="../../../storm/trident/tuple/TridentTuple.html" title="interface in storm.trident.tuple">TridentTuple</A>&nbsp;tuple, <A HREF="../../../storm/trident/operation/TridentCollector.html" title="interface in storm.trident.operation">TridentCollector</A>&nbsp;collector)</PRE> <DL> <DD><DL> </DL> </DD> <DD><DL> </DL> </DD> </DL> <!-- ========= END OF CLASS DATA ========= --> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/Function.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../storm/trident/operation/Filter.html" title="interface in storm.trident.operation"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../storm/trident/operation/GroupedMultiReducer.html" title="interface in storm.trident.operation"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../index.html?storm/trident/operation/Function.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="Function.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Copyright &#169; 2014 <a href="http://www.apache.org/">The Apache Software Foundation</a>. All Rights Reserved. </BODY> </HTML>
{ "content_hash": "ae96769eb9f662d4d41e9ba8d031765c", "timestamp": "", "source": "github", "line_count": 227, "max_line_length": 794, "avg_line_length": 48.36123348017621, "alnum_prop": 0.6503006012024048, "repo_name": "techdocscn/storm", "id": "e7dea7758e2ec6339953b4d18b39a0f10d81367d", "size": "10978", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "source/apidocs/storm/trident/operation/Function.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "10888" }, { "name": "Ruby", "bytes": "1341" } ], "symlink_target": "" }
<resources> <color name="black_overlay">#66000000</color> <color name="shadow">#f0f0f0</color> </resources>
{ "content_hash": "aa184307c6d36ba1ec620f4e76d3a5c3", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 49, "avg_line_length": 19.5, "alnum_prop": 0.6666666666666666, "repo_name": "benjaminthorent/AndroLight", "id": "5c4a79f9ffdf4bfbd118d7d5c73f7f9a1920b83a", "size": "117", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "res/values/colors.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "37413" } ], "symlink_target": "" }
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE762_Mismatched_Memory_Management_Routines__delete_array_long_realloc_51b.cpp Label Definition File: CWE762_Mismatched_Memory_Management_Routines__delete_array.label.xml Template File: sources-sinks-51b.tmpl.cpp */ /* * @description * CWE: 762 Mismatched Memory Management Routines * BadSource: realloc Allocate data using realloc() * GoodSource: Allocate data using new [] * Sinks: * GoodSink: Deallocate data using free() * BadSink : Deallocate data using delete [] * Flow Variant: 51 Data flow: data passed as an argument from one function to another in different source files * * */ #include "std_testcase.h" namespace CWE762_Mismatched_Memory_Management_Routines__delete_array_long_realloc_51 { #ifndef OMITBAD void badSink(long * data) { /* POTENTIAL FLAW: Deallocate memory using delete [] - the source memory allocation function may * require a call to free() to deallocate the memory */ delete [] data; } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void goodG2BSink(long * data) { /* POTENTIAL FLAW: Deallocate memory using delete [] - the source memory allocation function may * require a call to free() to deallocate the memory */ delete [] data; } /* goodB2G uses the BadSource with the GoodSink */ void goodB2GSink(long * data) { /* FIX: Free memory using free() */ free(data); } #endif /* OMITGOOD */ } /* close namespace */
{ "content_hash": "2ff6198d2b6d8e1e2faa82d9a15486d0", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 112, "avg_line_length": 29.150943396226417, "alnum_prop": 0.6951456310679611, "repo_name": "JianpingZeng/xcc", "id": "5c2c9c8f04e0c15a0e62f021129da8265f968d84", "size": "1545", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "xcc/test/juliet/testcases/CWE762_Mismatched_Memory_Management_Routines/s02/CWE762_Mismatched_Memory_Management_Routines__delete_array_long_realloc_51b.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
package aQute.bnd.build; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.ref.WeakReference; import java.net.URI; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.Formatter; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.SortedSet; import java.util.StringTokenizer; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.jar.JarEntry; import java.util.jar.JarInputStream; import java.util.jar.Manifest; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.naming.TimeLimitExceededException; import aQute.bnd.annotation.plugin.BndPlugin; import aQute.bnd.exporter.subsystem.SubsystemExporter; import aQute.bnd.header.Attrs; import aQute.bnd.header.OSGiHeader; import aQute.bnd.header.Parameters; import aQute.bnd.maven.support.Maven; import aQute.bnd.osgi.About; import aQute.bnd.osgi.Constants; import aQute.bnd.osgi.Macro; import aQute.bnd.osgi.Processor; import aQute.bnd.osgi.Verifier; import aQute.bnd.resource.repository.ResourceRepositoryImpl; import aQute.bnd.service.BndListener; import aQute.bnd.service.RepositoryPlugin; import aQute.bnd.service.action.Action; import aQute.bnd.service.extension.ExtensionActivator; import aQute.bnd.service.lifecycle.LifeCyclePlugin; import aQute.bnd.service.repository.RepositoryDigest; import aQute.bnd.service.repository.SearchableRepository.ResourceDescriptor; import aQute.bnd.url.MultiURLConnectionHandler; import aQute.bnd.version.Version; import aQute.bnd.version.VersionRange; import aQute.lib.deployer.FileRepo; import aQute.lib.hex.Hex; import aQute.lib.io.IO; import aQute.lib.io.IOConstants; import aQute.lib.settings.Settings; import aQute.lib.strings.Strings; import aQute.lib.utf8properties.UTF8Properties; import aQute.lib.zip.ZipUtil; import aQute.libg.uri.URIUtil; import aQute.service.reporter.Reporter; public class Workspace extends Processor { public static final String EXT = "ext"; static final int BUFFER_SIZE = IOConstants.PAGE_SIZE * 16; public static final String BUILDFILE = "build.bnd"; public static final String CNFDIR = "cnf"; public static final String BNDDIR = "bnd"; public static final String CACHEDIR = "cache/" + About.CURRENT; public static final String STANDALONE_REPO_CLASS = "aQute.bnd.deployer.repository.FixedIndexedRepo"; private final Pattern EMBEDDED_REPO_TESTING_PATTERN = Pattern .compile(".*biz\\.aQute\\.bnd\\.embedded-repo-(.*)\\.jar"); static Map<File,WeakReference<Workspace>> cache = newHashMap(); static Processor defaults = null; final Map<String,Project> models = newHashMap(); final Map<String,Action> commands = newMap(); final File buildDir; final Maven maven = new Maven(Processor.getExecutor()); private boolean offline = true; Settings settings = new Settings(); WorkspaceRepository workspaceRepo = new WorkspaceRepository(this); static String overallDriver = "unset"; static Parameters overallGestalt = new Parameters(); /** * Signal a BndListener plugin. We ran an infinite bug loop :-( */ final ThreadLocal<Reporter> signalBusy = new ThreadLocal<Reporter>(); ResourceRepositoryImpl resourceRepositoryImpl; private Parameters gestalt; private String driver; private final WorkspaceLayout layout; final Set<Project> trail = Collections .newSetFromMap(new ConcurrentHashMap<Project,Boolean>()); /** * This static method finds the workspace and creates a project (or returns * an existing project) * * @param projectDir * @return */ public static Project getProject(File projectDir) throws Exception { projectDir = projectDir.getAbsoluteFile(); assert projectDir.isDirectory(); Workspace ws = getWorkspace(projectDir.getParentFile()); return ws.getProject(projectDir.getName()); } static synchronized public Processor getDefaults() { if (defaults != null) return defaults; UTF8Properties props = new UTF8Properties(); InputStream propStream = Workspace.class.getResourceAsStream("defaults.bnd"); if (propStream != null) { try { props.load(propStream); } catch (IOException e) { throw new IllegalArgumentException("Unable to load bnd defaults.", e); } finally { IO.close(propStream); } } else System.err.println("Cannot load defaults"); defaults = new Processor(props, false); return defaults; } public static Workspace getWorkspace(File parent) throws Exception { return getWorkspace(parent, CNFDIR); } public static Workspace getWorkspaceWithoutException(File parent) throws Exception { try { return getWorkspace(parent); } catch (IllegalArgumentException e) { return null; } } /** * /* Return the nearest workspace */ public static Workspace findWorkspace(File base) throws Exception { File rover = base; while (rover != null) { File file = IO.getFile(rover, "cnf/build.bnd"); if (file.isFile()) return getWorkspace(rover); rover = rover.getParentFile(); } return null; } public static Workspace getWorkspace(File parent, String bndDir) throws Exception { File workspaceDir = parent.getAbsoluteFile(); // the cnf directory can actually be a // file that redirects while (workspaceDir.isDirectory()) { File test = new File(workspaceDir, CNFDIR); if (!test.exists()) test = new File(workspaceDir, bndDir); if (test.isDirectory()) break; if (test.isFile()) { String redirect = IO.collect(test).trim(); test = getFile(test.getParentFile(), redirect).getAbsoluteFile(); workspaceDir = test; } if (!test.exists()) throw new IllegalArgumentException("No Workspace found from: " + parent); } synchronized (cache) { WeakReference<Workspace> wsr = cache.get(workspaceDir); Workspace ws; if (wsr == null || (ws = wsr.get()) == null) { ws = new Workspace(workspaceDir, bndDir); cache.put(workspaceDir, new WeakReference<Workspace>(ws)); } return ws; } } public Workspace(File dir) throws Exception { this(dir, CNFDIR); } public Workspace(File dir, String bndDir) throws Exception { super(getDefaults()); this.layout = WorkspaceLayout.BND; dir = dir.getAbsoluteFile(); if (!dir.exists() && !dir.mkdirs()) { throw new IOException("Could not create directory " + dir); } assert dir.isDirectory(); File buildDir = new File(dir, bndDir).getAbsoluteFile(); if (!buildDir.isDirectory()) buildDir = new File(dir, CNFDIR).getAbsoluteFile(); this.buildDir = buildDir; File buildFile = new File(buildDir, BUILDFILE).getAbsoluteFile(); if (!buildFile.isFile()) warning("No Build File in " + dir); setProperties(buildFile, dir); propertiesChanged(); // // There is a nasty bug/feature in Java that gives errors on our // SSL use of github. The flag jsse.enableSNIExtension should be set // to false. So here we provide a way to set system properties // as early as possible // Attrs sysProps = OSGiHeader.parseProperties(mergeProperties(SYSTEMPROPERTIES)); for (Entry<String,String> e : sysProps.entrySet()) { System.setProperty(e.getKey(), e.getValue()); } } Workspace(WorkspaceLayout layout) { super(getDefaults()); this.layout = layout; this.buildDir = IO.getFile("~/.bnd/default-ws"); this.buildDir.mkdirs(); } public Project getProject(String bsn) throws Exception { synchronized (models) { Project project = models.get(bsn); if (project != null) return project; File projectDir = getFile(bsn); project = new Project(this, projectDir); if (!project.isValid()) return null; models.put(bsn, project); return project; } } void removeProject(Project p) throws Exception { if (p.isCnf()) return; synchronized (models) { models.remove(p.getName()); } for (LifeCyclePlugin lp : getPlugins(LifeCyclePlugin.class)) { lp.delete(p); } } public boolean isPresent(String name) { return models.containsKey(name); } public Collection<Project> getCurrentProjects() { return models.values(); } @Override public boolean refresh() { if (super.refresh()) { for (Project project : getCurrentProjects()) { project.propertiesChanged(); } return true; } return false; } @Override public void propertiesChanged() { File extDir = new File(this.buildDir, EXT); File[] extensions = extDir.listFiles(); if (extensions != null) { for (File extension : extensions) { String extensionName = extension.getName(); if (extensionName.endsWith(".bnd")) { extensionName = extensionName.substring(0, extensionName.length() - ".bnd".length()); try { doIncludeFile(extension, false, getProperties(), "ext." + extensionName); } catch (Exception e) { error("PropertiesChanged: " + e.getMessage()); } } } } super.propertiesChanged(); } public String _workspace(@SuppressWarnings("unused") String args[]) { return getBase().getAbsolutePath(); } public void addCommand(String menu, Action action) { commands.put(menu, action); } public void removeCommand(String menu) { commands.remove(menu); } public void fillActions(Map<String,Action> all) { all.putAll(commands); } public Collection<Project> getAllProjects() throws Exception { List<Project> projects = new ArrayList<Project>(); for (File file : getBase().listFiles()) { if (new File(file, Project.BNDFILE).isFile()) { Project p = getProject(file.getAbsoluteFile().getName()); if (p != null) { projects.add(p); } } } return projects; } /** * Inform any listeners that we changed a file (created/deleted/changed). * * @param f The changed file */ public void changedFile(File f) { List<BndListener> listeners = getPlugins(BndListener.class); for (BndListener l : listeners) try { offline = false; l.changed(f); } catch (Exception e) { e.printStackTrace(); } } public void bracket(boolean begin) { List<BndListener> listeners = getPlugins(BndListener.class); for (BndListener l : listeners) try { if (begin) l.begin(); else l.end(); } catch (Exception e) { // who cares? } } public void signal(Reporter reporter) { if (signalBusy.get() != null) return; signalBusy.set(reporter); try { List<BndListener> listeners = getPlugins(BndListener.class); for (BndListener l : listeners) try { l.signal(this); } catch (Exception e) { // who cares? } } catch (Exception e) { // Ignore } finally { signalBusy.set(null); } } @Override public void signal() { signal(this); } void copy(InputStream in, OutputStream out) throws Exception { byte data[] = new byte[BUFFER_SIZE]; int size = in.read(data); while (size > 0) { out.write(data, 0, size); size = in.read(data); } } class CachedFileRepo extends FileRepo { final Lock lock = new ReentrantLock(); boolean inited; CachedFileRepo() { super("cache", getFile(buildDir, CACHEDIR), false); } @Override public String toString() { return "bnd-cache"; } @Override protected boolean init() throws Exception { if (lock.tryLock(50, TimeUnit.SECONDS) == false) throw new TimeLimitExceededException("Cached File Repo is locked and can't acquire it"); try { if (super.init()) { inited = true; if (!root.exists() && !root.mkdirs()) { throw new IOException("Could not create cache directory " + root); } if (!root.isDirectory()) throw new IllegalArgumentException("Cache directory " + root + " not a directory"); InputStream in = getClass().getResourceAsStream(EMBEDDED_REPO); if (in != null) unzip(in, root); else { // We may be in unit test, look for // biz.aQute.bnd.embedded-repo-<version>.jar on the // classpath StringTokenizer classPathTokenizer = new StringTokenizer( System.getProperty("java.class.path", ""), File.pathSeparator); while (classPathTokenizer.hasMoreTokens()) { String classPathEntry = classPathTokenizer.nextToken().trim(); if (EMBEDDED_REPO_TESTING_PATTERN.matcher(classPathEntry).matches()) { in = new FileInputStream(classPathEntry); unzip(in, root); return true; } } error("Couldn't find biz.aQute.bnd.embedded-repo on the classpath"); return false; } return true; } else return false; } finally { lock.unlock(); } } void unzip(InputStream in, File dir) throws Exception { try { JarInputStream jin = new JarInputStream(in); JarEntry jentry = jin.getNextJarEntry(); while (jentry != null) { if (!jentry.isDirectory()) { File dest = Processor.getFile(dir, jentry.getName()); long modifiedTime = ZipUtil.getModifiedTime(jentry); if (!dest.isFile() || dest.lastModified() < modifiedTime || modifiedTime <= 0) { File dp = dest.getParentFile(); if (!dp.exists() && !dp.mkdirs()) { throw new IOException("Could not create directory " + dp); } FileOutputStream out = new FileOutputStream(dest); try { copy(jin, out); } finally { out.close(); } } } jentry = jin.getNextJarEntry(); } } finally { in.close(); } } } public void syncCache() throws Exception { CachedFileRepo cf = new CachedFileRepo(); cf.init(); cf.close(); } public List<RepositoryPlugin> getRepositories() { return getPlugins(RepositoryPlugin.class); } public Collection<Project> getBuildOrder() throws Exception { List<Project> result = new ArrayList<Project>(); for (Project project : getAllProjects()) { Collection<Project> dependsOn = project.getDependson(); getBuildOrder(dependsOn, result); if (!result.contains(project)) { result.add(project); } } return result; } private void getBuildOrder(Collection<Project> dependsOn, List<Project> result) throws Exception { for (Project project : dependsOn) { Collection<Project> subProjects = project.getDependson(); for (Project subProject : subProjects) { if (!result.contains(subProject)) { result.add(subProject); } } if (!result.contains(project)) { result.add(project); } } } public static Workspace getWorkspace(String path) throws Exception { File file = IO.getFile(new File(""), path); return getWorkspace(file); } public Maven getMaven() { return maven; } @Override protected void setTypeSpecificPlugins(Set<Object> list) { try { super.setTypeSpecificPlugins(list); list.add(this); list.add(maven); list.add(settings); if (!isTrue(getProperty(NOBUILDINCACHE))) { list.add(new CachedFileRepo()); } resourceRepositoryImpl = new ResourceRepositoryImpl(); resourceRepositoryImpl.setCache(IO.getFile(getProperty(CACHEDIR, "~/.bnd/caches/shas"))); resourceRepositoryImpl.setExecutor(getExecutor()); resourceRepositoryImpl.setIndexFile(getFile(buildDir, "repo.json")); resourceRepositoryImpl.setURLConnector(new MultiURLConnectionHandler(this)); customize(resourceRepositoryImpl, null); list.add(resourceRepositoryImpl); // // Exporters // list.add(new SubsystemExporter()); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } } /** * Add any extensions listed * * @param list * @param rri */ @Override protected void addExtensions(Set<Object> list) { // // <bsn>; version=<range> // Parameters extensions = getMergedParameters(EXTENSION); Map<DownloadBlocker,Attrs> blockers = new HashMap<DownloadBlocker,Attrs>(); for (Entry<String,Attrs> i : extensions.entrySet()) { String bsn = removeDuplicateMarker(i.getKey()); String stringRange = i.getValue().get(VERSION_ATTRIBUTE); trace("Adding extension %s-%s", bsn, stringRange); if (stringRange == null) stringRange = Version.LOWEST.toString(); else if (!VersionRange.isVersionRange(stringRange)) { error("Invalid version range %s on extension %s", stringRange, bsn); continue; } try { SortedSet<ResourceDescriptor> matches = resourceRepositoryImpl.find(null, bsn, new VersionRange(stringRange)); if (matches.isEmpty()) { error("Extension %s;version=%s not found in base repo", bsn, stringRange); continue; } DownloadBlocker blocker = new DownloadBlocker(this); blockers.put(blocker, i.getValue()); resourceRepositoryImpl.getResource(matches.last().id, blocker); } catch (Exception e) { error("Failed to load extension %s-%s, %s", bsn, stringRange, e); } } trace("Found extensions %s", blockers); for (Entry<DownloadBlocker,Attrs> blocker : blockers.entrySet()) { try { String reason = blocker.getKey().getReason(); if (reason != null) { error("Extension load failed: %s", reason); continue; } @SuppressWarnings("resource") URLClassLoader cl = new URLClassLoader(new URL[] { blocker.getKey().getFile().toURI().toURL() }, getClass().getClassLoader()); Enumeration<URL> manifests = cl.getResources("META-INF/MANIFEST.MF"); while (manifests.hasMoreElements()) { Manifest m = new Manifest(manifests.nextElement().openStream()); Parameters activators = new Parameters(m.getMainAttributes().getValue("Extension-Activator")); for (Entry<String,Attrs> e : activators.entrySet()) { try { Class< ? > c = cl.loadClass(e.getKey()); ExtensionActivator extensionActivator = (ExtensionActivator) c.newInstance(); customize(extensionActivator, blocker.getValue()); List< ? > plugins = extensionActivator.activate(this, blocker.getValue()); list.add(extensionActivator); if (plugins != null) for (Object plugin : plugins) { list.add(plugin); } } catch (ClassNotFoundException cnfe) { error("Loading extension %s, extension activator missing: %s (ignored)", blocker, e.getKey()); } } } } catch (Exception e) { error("failed to install extension %s due to %s", blocker, e); } } } /** * Return if we're in offline mode. Offline mode is defined as an * environment where nobody tells us the resources are out of date (refresh * or changed). This is currently defined as having bndlisteners. * * @return */ public boolean isOffline() { return offline; } public Workspace setOffline(boolean on) { this.offline = on; return this; } /** * Provide access to the global settings of this machine. * * @throws Exception */ public String _global(String[] args) throws Exception { Macro.verifyCommand(args, "${global;<name>[;<default>]}, get a global setting from ~/.bnd/settings.json", null, 2, 3); String key = args[1]; if (key.equals("key.public")) return Hex.toHexString(settings.getPublicKey()); if (key.equals("key.private")) return Hex.toHexString(settings.getPrivateKey()); String s = settings.get(key); if (s != null) return s; if (args.length == 3) return args[2]; return null; } public String _user(String[] args) throws Exception { return _global(args); } /** * Return the repository signature digests. These digests are a unique id * for the contents of the repository */ public Object _repodigests(String[] args) throws Exception { Macro.verifyCommand(args, "${repodigests;[;<repo names>]...}, get the repository digests", null, 1, 10000); List<RepositoryPlugin> repos = getRepositories(); if (args.length > 1) { repos: for (Iterator<RepositoryPlugin> it = repos.iterator(); it.hasNext();) { String name = it.next().getName(); for (int i = 1; i < args.length; i++) { if (name.equals(args[i])) { continue repos; } } it.remove(); } } List<String> digests = new ArrayList<String>(); for (RepositoryPlugin repo : repos) { try { if (repo instanceof RepositoryDigest) { byte[] digest = ((RepositoryDigest) repo).getDigest(); digests.add(Hex.toHexString(digest)); } else { if (args.length != 1) error("Specified repo %s for ${repodigests} was named but it is not found", repo.getName()); } } catch (Exception e) { if (args.length != 1) error("Specified repo %s for digests is not found", repo.getName()); // else Ignore } } return join(digests, ","); } public static Run getRun(File file) throws Exception { if (!file.isFile()) { return null; } File projectDir = file.getParentFile(); File workspaceDir = projectDir.getParentFile(); if (!workspaceDir.isDirectory()) { return null; } Workspace ws = getWorkspaceWithoutException(workspaceDir); if (ws == null) { return null; } return new Run(ws, projectDir, file); } /** * Report details of this workspace */ public void report(Map<String,Object> table) throws Exception { super.report(table); table.put("Workspace", toString()); table.put("Plugins", getPlugins(Object.class)); table.put("Repos", getRepositories()); table.put("Projects in build order", getBuildOrder()); } public File getCache(String name) { return getFile(buildDir, CACHEDIR + "/" + name); } /** * Return the workspace repo */ public WorkspaceRepository getWorkspaceRepository() { return workspaceRepo; } public void checkStructure() { if (!buildDir.isDirectory()) error("No directory for cnf %s", buildDir); else { File build = IO.getFile(buildDir, BUILDFILE); if (build.isFile()) { error("No %s file in %s", BUILDFILE, buildDir); } } } public File getBuildDir() { return buildDir; } public boolean isValid() { return IO.getFile(buildDir, BUILDFILE).isFile(); } public RepositoryPlugin getRepository(String repo) { for (RepositoryPlugin r : getRepositories()) { if (repo.equals(r.getName())) { return r; } } return null; } public void close() { cache.remove(getPropertiesFile().getParentFile().getParentFile()); try { super.close(); } catch (IOException e) { /* For backwards compatibility, we ignore the exception */ } } /** * Get the bnddriver, can be null if not set. The overallDriver is the * environment that runs this bnd. */ public String getDriver() { if (driver == null) { driver = getProperty(Constants.BNDDRIVER, null); if (driver != null) driver = driver.trim(); } if (driver != null) return driver; return overallDriver; } /** * Set the driver of this environment */ public static void setDriver(String driver) { overallDriver = driver; } /** * Macro to return the driver. Without any arguments, we return the name of * the driver. If there are arguments, we check each of the arguments * against the name of the driver. If it matches, we return the driver name. * If none of the args match the driver name we return an empty string * (which is false). */ public String _driver(String args[]) { if (args.length == 1) { return getDriver(); } String driver = getDriver(); if (driver == null) driver = getProperty(Constants.BNDDRIVER); if (driver != null) { for (int i = 1; i < args.length; i++) { if (args[i].equalsIgnoreCase(driver)) return driver; } } return ""; } /** * Add a gestalt to all workspaces. The gestalt is a set of parts describing * the environment. Each part has a name and optionally attributes. This * method adds a gestalt to the VM. Per workspace it is possible to augment * this. */ public static void addGestalt(String part, Attrs attrs) { Attrs already = overallGestalt.get(part); if (attrs == null) attrs = new Attrs(); if (already != null) { already.putAll(attrs); } else already = attrs; overallGestalt.put(part, already); } /** * Get the attrs for a gestalt part */ public Attrs getGestalt(String part) { return getGestalt().get(part); } /** * Get the attrs for a gestalt part */ public Parameters getGestalt() { if (gestalt == null) { gestalt = getMergedParameters(Constants.GESTALT); gestalt.mergeWith(overallGestalt, false); } return gestalt; } /** * Get the layout style of the workspace. */ public WorkspaceLayout getLayout() { return layout; } /** * The macro to access the gestalt * <p> * {@code $ gestalt;part[;key[;value]]} */ public String _gestalt(String args[]) { if (args.length >= 2) { Attrs attrs = getGestalt(args[1]); if (attrs == null) return ""; if (args.length == 2) return args[1]; String s = attrs.get(args[2]); if (args.length == 3) { if (s == null) s = ""; return s; } if (args.length == 4) { if (args[3].equals(s)) return s; else return ""; } } throw new IllegalArgumentException("${gestalt;<part>[;key[;<value>]]} has too many arguments"); } @Override public String toString() { return "Workspace [" + getBase().getName() + "]"; } /** * Create a project in this workspace */ public Project createProject(String name) throws Exception { if (!Verifier.SYMBOLICNAME.matcher(name).matches()) { error("A project name is a Bundle Symbolic Name, this must therefore consist of only letters, digits and dots"); return null; } File pdir = getFile(name); pdir.mkdirs(); IO.store("#\n# " + name.toUpperCase().replace('.', ' ') + "\n#\n", getFile(pdir, Project.BNDFILE)); Project p = new Project(this, pdir); p.getTarget().mkdirs(); p.getOutput().mkdirs(); p.getTestOutput().mkdirs(); for (File dir : p.getSourcePath()) { dir.mkdirs(); } p.getTestSrc().mkdirs(); for (LifeCyclePlugin l : getPlugins(LifeCyclePlugin.class)) l.created(p); if (!p.isValid()) { error("project %s is not valid", p); } return p; } /** * Create a new Workspace * * @param opts * @param wsdir * @throws Exception */ public static Workspace createWorkspace(File wsdir) throws Exception { if (wsdir.exists()) return null; wsdir.mkdirs(); File cnf = IO.getFile(wsdir, CNFDIR); cnf.mkdir(); IO.store("", new File(cnf, BUILDFILE)); IO.store("-nobundles: true\n", new File(cnf, Project.BNDFILE)); File ext = new File(cnf, EXT); ext.mkdir(); Workspace ws = getWorkspace(wsdir); return ws; } /** * Add a plugin * * @param plugin * @throws Exception */ public boolean addPlugin(Class< ? > plugin, String alias, Map<String,String> parameters, boolean force) throws Exception { BndPlugin ann = plugin.getAnnotation(BndPlugin.class); if (alias == null) { if (ann != null) alias = ann.name(); else { alias = Strings.getLastSegment(plugin.getName()).toLowerCase(); if (alias.endsWith("plugin")) { alias = alias.substring(0, alias.length() - "plugin".length()); } } } if (!Verifier.isBsn(alias)) { error("Not a valid plugin name %s", alias); } File ext = getFile(Workspace.CNFDIR + "/" + Workspace.EXT); ext.mkdirs(); File f = new File(ext, alias + ".bnd"); if (!force) { if (f.exists()) { error("Plugin %s already exists", alias); return false; } } else { IO.delete(f); } Object l = plugin.newInstance(); Formatter setup = new Formatter(); try { setup.format("#\n" // + "# Plugin %s setup\n" // + "#\n", alias); setup.format("-plugin.%s = %s", alias, plugin.getName()); for (Map.Entry<String,String> e : parameters.entrySet()) { setup.format("; \\\n \t%s = '%s'", e.getKey(), escaped(e.getValue())); } setup.format("\n\n"); String out = setup.toString(); if (l instanceof LifeCyclePlugin) { out = ((LifeCyclePlugin) l).augmentSetup(out, alias, parameters); ((LifeCyclePlugin) l).init(this); } trace("setup %s", out); IO.store(out, f); } finally { setup.close(); } refresh(); for (LifeCyclePlugin lp : getPlugins(LifeCyclePlugin.class)) { lp.addedPlugin(this, plugin.getName(), alias, parameters); } return true; } static Pattern ESCAPE_P = Pattern.compile("(\"|')(.*)\1"); private Object escaped(String value) { Matcher matcher = ESCAPE_P.matcher(value); if (matcher.matches()) value = matcher.group(2); return value.replaceAll("'", "\\'"); } public boolean removePlugin(String alias) { File ext = getFile(Workspace.CNFDIR + "/" + Workspace.EXT); File f = new File(ext, alias + ".bnd"); if (!f.exists()) { error("No such plugin %s", alias); return false; } IO.delete(f); refresh(); return true; } /** * Create a workspace that does not inherit from a cnf directory etc. * * @param run * @return */ public static Workspace createStandaloneWorkspace(Processor run, URI base) throws Exception { Workspace ws = new Workspace(WorkspaceLayout.STANDALONE); Parameters standalone = new Parameters(run.getProperty("-standalone", "")); int counter = 1; for (Map.Entry<String,Attrs> e : standalone.entrySet()) { String locationStr = e.getKey(); URI resolvedLocation = URIUtil.resolve(base, locationStr); try (Formatter f = new Formatter();) { String name = e.getValue().get("name"); if (name == null) name = "_" + counter; f.format("%s; name=%s; locations='%s'", STANDALONE_REPO_CLASS, name, resolvedLocation); for (Map.Entry<String,String> attribEntry : e.getValue().entrySet()) { if (!"name".equals(attribEntry.getKey())) f.format(";%s='%s'", attribEntry.getKey(), attribEntry.getValue()); } f.format("\n"); ws.setProperty("-plugin._" + counter, f.toString()); } counter++; } return ws; } }
{ "content_hash": "0593b7a56f68136bce3e6e311efcabba", "timestamp": "", "source": "github", "line_count": 1145, "max_line_length": 115, "avg_line_length": 26.38515283842795, "alnum_prop": 0.665618483333885, "repo_name": "GEBIT/bnd", "id": "2c020ab725c2e12232b473c6b899e6e479ff9081", "size": "30211", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "biz.aQute.bndlib/src/aQute/bnd/build/Workspace.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "58877" }, { "name": "Java", "bytes": "4632570" }, { "name": "Shell", "bytes": "6059" }, { "name": "XSLT", "bytes": "24394" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "3984df65ae995fe3574dbf32e0047f97", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.307692307692308, "alnum_prop": 0.6940298507462687, "repo_name": "mdoering/backbone", "id": "9962b083089e07db762fe669815101b55245aabe", "size": "186", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Malpighiales/Euphorbiaceae/Crotonogyne/Crotonogyne giorgii/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package org.apache.hadoop.hdfs.security; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.impl.Log4JLogger; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hdfs.DFSConfigKeys; import org.apache.hadoop.hdfs.DFSTestUtil; import org.apache.hadoop.hdfs.DistributedFileSystem; import org.apache.hadoop.hdfs.HdfsConfiguration; import org.apache.hadoop.hdfs.MiniDFSCluster; import org.apache.hadoop.hdfs.security.token.delegation.DelegationTokenIdentifier; import org.apache.hadoop.hdfs.security.token.delegation.DelegationTokenSecretManager; import org.apache.hadoop.hdfs.server.common.HdfsServerConstants.StartupOption; import org.apache.hadoop.hdfs.server.namenode.NameNode; import org.apache.hadoop.hdfs.server.namenode.NameNodeAdapter; import org.apache.hadoop.hdfs.server.namenode.web.resources.NamenodeWebHdfsMethods; import org.apache.hadoop.hdfs.web.WebHdfsConstants; import org.apache.hadoop.hdfs.web.WebHdfsFileSystem; import org.apache.hadoop.io.Text; import org.apache.hadoop.security.AccessControlException; import org.apache.hadoop.security.Credentials; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.token.SecretManager.InvalidToken; import org.apache.hadoop.security.token.Token; import org.apache.log4j.Level; import org.junit.*; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.IOException; import java.net.URI; import java.security.PrivilegedExceptionAction; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class TestDelegationToken { private MiniDFSCluster cluster; private DelegationTokenSecretManager dtSecretManager; private Configuration config; private static final Log LOG = LogFactory.getLog(TestDelegationToken.class); @Before public void setUp() throws Exception { config = new HdfsConfiguration(); config.setLong(DFSConfigKeys.DFS_NAMENODE_DELEGATION_TOKEN_MAX_LIFETIME_KEY, 10000); config .setLong(DFSConfigKeys.DFS_NAMENODE_DELEGATION_TOKEN_RENEW_INTERVAL_KEY, 5000); config .setBoolean(DFSConfigKeys.DFS_NAMENODE_DELEGATION_TOKEN_ALWAYS_USE_KEY, true); config.set("hadoop.security.auth_to_local", "RULE:[2:$1@$0](JobTracker@.*FOO.COM)s/@.*//" + "DEFAULT"); FileSystem.setDefaultUri(config, "hdfs://localhost:" + "0"); cluster = new MiniDFSCluster.Builder(config).numDataNodes(0).build(); cluster.waitActive(); dtSecretManager = NameNodeAdapter.getDtSecretManager(cluster.getNamesystem()); } @After public void tearDown() throws Exception { if (cluster != null) { cluster.shutdown(); } } private Token<DelegationTokenIdentifier> generateDelegationToken(String owner, String renewer) { DelegationTokenIdentifier dtId = new DelegationTokenIdentifier(new Text(owner), new Text(renewer), null); return new Token<>(dtId, dtSecretManager); } @Test public void testDelegationTokenSecretManager() throws Exception { Token<DelegationTokenIdentifier> token = generateDelegationToken("SomeUser", "JobTracker"); // Fake renewer should not be able to renew try { dtSecretManager.renewToken(token, "FakeRenewer"); Assert.fail("should have failed"); } catch (AccessControlException ace) { // PASS } dtSecretManager.renewToken(token, "JobTracker"); DelegationTokenIdentifier identifier = new DelegationTokenIdentifier(); byte[] tokenId = token.getIdentifier(); identifier .readFields(new DataInputStream(new ByteArrayInputStream(tokenId))); Assert.assertTrue(null != dtSecretManager.retrievePassword(identifier)); LOG.info("Sleep to expire the token"); Thread.sleep(6000); //Token should be expired try { dtSecretManager.retrievePassword(identifier); //Should not come here Assert.fail("Token should have expired"); } catch (InvalidToken e) { //Success } dtSecretManager.renewToken(token, "JobTracker"); LOG.info("Sleep beyond the max lifetime"); Thread.sleep(5000); try { dtSecretManager.renewToken(token, "JobTracker"); Assert.fail("should have been expired"); } catch (InvalidToken it) { // PASS } } @Test public void testCancelDelegationToken() throws Exception { Token<DelegationTokenIdentifier> token = generateDelegationToken("SomeUser", "JobTracker"); //Fake renewer should not be able to renew try { dtSecretManager.cancelToken(token, "FakeCanceller"); Assert.fail("should have failed"); } catch (AccessControlException ace) { // PASS } dtSecretManager.cancelToken(token, "JobTracker"); try { dtSecretManager.renewToken(token, "JobTracker"); Assert.fail("should have failed"); } catch (InvalidToken it) { // PASS } } @Ignore @Test public void testAddDelegationTokensDFSApi() throws Exception { UserGroupInformation ugi = UserGroupInformation.createRemoteUser("JobTracker"); DistributedFileSystem dfs = cluster.getFileSystem(); Credentials creds = new Credentials(); final Token<?> tokens[] = dfs.addDelegationTokens("JobTracker", creds); Assert.assertEquals(1, tokens.length); Assert.assertEquals(1, creds.numberOfTokens()); checkTokenIdentifier(ugi, tokens[0]); final Token<?> tokens2[] = dfs.addDelegationTokens("JobTracker", creds); Assert.assertEquals(0, tokens2.length); // already have token Assert.assertEquals(1, creds.numberOfTokens()); } @SuppressWarnings("deprecation") @Test public void testDelegationTokenWebHdfsApi() throws Exception { ((Log4JLogger)NamenodeWebHdfsMethods.LOG).getLogger().setLevel(Level.ALL); final String uri = WebHdfsConstants.WEBHDFS_SCHEME + "://" + config.get(DFSConfigKeys.DFS_NAMENODE_HTTP_ADDRESS_KEY); //get file system as JobTracker final UserGroupInformation ugi = UserGroupInformation .createUserForTesting("JobTracker", new String[]{"user"}); final WebHdfsFileSystem webhdfs = ugi.doAs(new PrivilegedExceptionAction<WebHdfsFileSystem>() { @Override public WebHdfsFileSystem run() throws Exception { return (WebHdfsFileSystem) FileSystem.get(new URI(uri), config); } }); { //test addDelegationTokens(..) Credentials creds = new Credentials(); final Token<?> tokens[] = webhdfs.addDelegationTokens("JobTracker", creds); Assert.assertEquals(1, tokens.length); Assert.assertEquals(1, creds.numberOfTokens()); Assert.assertSame(tokens[0], creds.getAllTokens().iterator().next()); checkTokenIdentifier(ugi, tokens[0]); final Token<?> tokens2[] = webhdfs.addDelegationTokens("JobTracker", creds); Assert.assertEquals(0, tokens2.length); } } @Ignore @Test public void testDelegationTokenWithDoAs() throws Exception { final DistributedFileSystem dfs = cluster.getFileSystem(); final Credentials creds = new Credentials(); final Token<?> tokens[] = dfs.addDelegationTokens("JobTracker", creds); Assert.assertEquals(1, tokens.length); @SuppressWarnings("unchecked") final Token<DelegationTokenIdentifier> token = (Token<DelegationTokenIdentifier>) tokens[0]; final UserGroupInformation longUgi = UserGroupInformation.createRemoteUser("JobTracker/foo.com@FOO.COM"); final UserGroupInformation shortUgi = UserGroupInformation.createRemoteUser("JobTracker"); longUgi.doAs(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws IOException { try { token.renew(config); } catch (Exception e) { Assert.fail("Could not renew delegation token for user " + longUgi); } return null; } }); shortUgi.doAs(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { token.renew(config); return null; } }); longUgi.doAs(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws IOException { try { token.cancel(config); } catch (Exception e) { Assert.fail("Could not cancel delegation token for user " + longUgi); } return null; } }); } /** * Test that the delegation token secret manager only runs when the * NN is out of safe mode. This is because the secret manager * has to log to the edit log, which should not be written in * safe mode. Regression test for HDFS-2579. */ @Test public void testDTManagerInSafeMode() throws Exception { cluster.startDataNodes(config, 1, true, StartupOption.REGULAR, null); FileSystem fs = cluster.getFileSystem(); for (int i = 0; i < 5; i++) { DFSTestUtil.createFile(fs, new Path("/test-" + i), 100, (short) 1, 1L); } cluster.getConfiguration(0) .setInt(DFSConfigKeys.DFS_NAMENODE_DELEGATION_KEY_UPDATE_INTERVAL_KEY, 500); cluster.getConfiguration(0) .setInt(DFSConfigKeys.DFS_NAMENODE_SAFEMODE_EXTENSION_KEY, 30000); cluster.setWaitSafeMode(false); cluster.restartNameNode(); NameNode nn = cluster.getNameNode(); assertTrue(nn.isInSafeMode()); DelegationTokenSecretManager sm = NameNodeAdapter.getDtSecretManager(nn.getNamesystem()); assertFalse("Secret manager should not run in safe mode", sm.isRunning()); NameNodeAdapter.leaveSafeMode(nn); assertTrue("Secret manager should start when safe mode is exited", sm.isRunning()); LOG.info("========= entering safemode again"); NameNodeAdapter.enterSafeMode(nn, false); assertFalse("Secret manager should stop again when safe mode " + "is manually entered", sm.isRunning()); // Set the cluster to leave safemode quickly on its own. cluster.getConfiguration(0) .setInt(DFSConfigKeys.DFS_NAMENODE_SAFEMODE_EXTENSION_KEY, 0); cluster.setWaitSafeMode(true); cluster.restartNameNode(); nn = cluster.getNameNode(); sm = NameNodeAdapter.getDtSecretManager(nn.getNamesystem()); assertFalse(nn.isInSafeMode()); assertTrue(sm.isRunning()); } @SuppressWarnings("unchecked") private void checkTokenIdentifier(UserGroupInformation ugi, final Token<?> token) throws Exception { Assert.assertNotNull(token); // should be able to use token.decodeIdentifier() but webhdfs isn't // registered with the service loader for token decoding DelegationTokenIdentifier identifier = new DelegationTokenIdentifier(); byte[] tokenId = token.getIdentifier(); DataInputStream in = new DataInputStream(new ByteArrayInputStream(tokenId)); try { identifier.readFields(in); } finally { in.close(); } Assert.assertNotNull(identifier); LOG.info( "A valid token should have non-null password, and should be renewed successfully"); Assert.assertTrue(null != dtSecretManager.retrievePassword(identifier)); dtSecretManager .renewToken((Token<DelegationTokenIdentifier>) token, "JobTracker"); ugi.doAs(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { token.renew(config); token.cancel(config); return null; } }); } }
{ "content_hash": "590656d1c914be18244eeef4de0a5905", "timestamp": "", "source": "github", "line_count": 311, "max_line_length": 91, "avg_line_length": 37.463022508038584, "alnum_prop": 0.7019139987983865, "repo_name": "smkniazi/hops", "id": "610e72c1392610b76f4670bc4aa40e72db0886f1", "size": "12457", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/security/TestDelegationToken.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AspectJ", "bytes": "31146" }, { "name": "Batchfile", "bytes": "61662" }, { "name": "C", "bytes": "1535591" }, { "name": "C++", "bytes": "95816" }, { "name": "CMake", "bytes": "47489" }, { "name": "CSS", "bytes": "47311" }, { "name": "Dockerfile", "bytes": "3372" }, { "name": "HTML", "bytes": "133827" }, { "name": "Java", "bytes": "55574211" }, { "name": "JavaScript", "bytes": "26910" }, { "name": "Perl", "bytes": "9496" }, { "name": "Python", "bytes": "11309" }, { "name": "Shell", "bytes": "188557" }, { "name": "TLA", "bytes": "14993" }, { "name": "TeX", "bytes": "19322" }, { "name": "XSLT", "bytes": "15741" } ], "symlink_target": "" }
title: Introduction subtitle: What does Didit do? category: intro --- # Introduction [![Didit screenshot](public/didit-screenshot.png)](public/didit-screenshot.png) Didit is a continuous build system for the classroom. + Didit is integrated with student [Git] repositories. When students push new commits to their repository, Didit attempts to build and test their work. + Didit can provide students with quick and easily-accessible feedback on whether their work compiles and passes a suite of public tests. + Didit can run a suite of hidden tests, compute grades based on the results of those tests, and serve grade reports to students. + Didit allows staff to record student revisions at multiple deadline times and release grades using different deadlines for different students, to handle slack days or extensions. ## Moving parts **Staff Git repository**: Didit assumes that a *staff repository* stores building and grading material for each assignment. The staff repository must be organized with a required directory structure. **Student Git repositories**: Each student has a *student repository* for each assignment. Student repositories must be organized in a required directory structure. **Shared filesystem**: Didit requires a *shared filesystem* for accessing student and staff repositories and for storing build results. **Assignments**: an *assignment* has a two-part name so assignments of the same kind can be grouped together: `psets/ps0`, `projects/abcplayer`, etc. **Build**: a *build* is an attempt to compile and run tests against a student submission for a particular assignment using a particular staff revision. See **[builds]**, and **[build configuration]**, and **[build security]**. **Staff revision, builder revision**: when it builds an assignment, Didit computes the latest revision of the staff repo that modified material for that assignment; this revision is the *staff revision* for the build. **Public and hidden tests**: in addition to compilation results, *public test* results are visible to students, including stack traces and console output. *Hidden test* results are only visible to staff. **Sweep**: *Sweeping* an assignment causes Didit to (1) record the current revision for every student repo and (2) ensure that all of those revisions have been built with the current builder revision. See **[sweeps]**. **Milestone**: A *milestone* collects grades, assigned individually by revision or in bulk from a sweep, and allows grade reports to be released to students. Milestones are named, e.g. "beta" and "final." **Grade report**: A *grade report* shows the results of all tests specified in the grading configuartion for an assignment. Grade reports are visible to students when released under a milestone. See **[grade assignment]**. **Amazon Simple Workflow Service**: Didit uses the [AWS Simple Workflow Service](http://aws.amazon.com/swf/) to queue and coordinate builds. **Web font-end**: The *web front-end* serves web pages, handles build requests, and manages the build workflow by sending tasks to SWF. **Workers**: *Workers* receive SWF tasks and perform builds: compiling, testing, and grading. [Git]: http://git-scm.com/ [builds]: builds-and-sweeps.html#builds [build configuration]: build-config.html [build security]: build-security.html [sweeps]: builds-and-sweeps.html#sweeps [grade assignment]: grade-assignment.html
{ "content_hash": "560bcb826461675cb3659511dd4db90a", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 217, "avg_line_length": 54.935483870967744, "alnum_prop": 0.7762771579565473, "repo_name": "maxg/didit", "id": "41aa1f2fe78eb998aefc074eb0318654c9182058", "size": "3410", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/introduction.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3027" }, { "name": "HTML", "bytes": "41604" }, { "name": "JavaScript", "bytes": "240599" }, { "name": "Shell", "bytes": "11565" } ], "symlink_target": "" }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package services; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Usuario */ public class ServicesTest { public ServicesTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of busLogIn method, of class Services. */ @Test public void testBusLogIn() { System.out.println("busLogIn"); int id = 1; String plate = "FFC38"; Services instance = new Services(); String expResult = ""; String result = instance.busLogIn(id, plate); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } @Test public void testInvalidBusLogIn() { System.out.println("busLogIn"); int id = 1; String plate = ""; Services instance = new Services(); String expResult = ""; String result = instance.busLogIn(id, plate); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of busLogInRegister method, of class Services. */ @Test public void testBusLogInRegister() { System.out.println("busLogInRegister"); String plate = "FFC38 "; String password = "123"; Services instance = new Services(); String expResult = ""; String result = instance.busLogInRegister(plate, password); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } @Test public void testInvalid1BusLogInRegister() { System.out.println("busLogInRegister"); String plate = "FFC38"; String password = ""; Services instance = new Services(); String expResult = ""; String result = instance.busLogInRegister(plate, password); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } @Test public void testInvalid2BusLogInRegister() { System.out.println("busLogInRegister"); String plate = ""; String password = "123"; Services instance = new Services(); String expResult = ""; String result = instance.busLogInRegister(plate, password); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of busLocationRegister method, of class Services. */ @Test public void testBusLocationRegister() { System.out.println("busLocationRegister"); int id = 1; Services instance = new Services(); String expResult = ""; String result = instance.busLocationRegister(id); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } @Test public void testInvalid1BusLocationRegister() { System.out.println("busLocationRegister"); int id = 0; Services instance = new Services(); String expResult = ""; String result = instance.busLocationRegister(id); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of busLocationUpdate method, of class Services. */ @Test public void testBusLocationUpdate() { System.out.println("busLocationUpdate"); int id = 0; double latitude = 0.0; double longitude = 0.0; Services instance = new Services(); String expResult = ""; String result = instance.busLocationUpdate(id, latitude, longitude); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of busLocationDelete method, of class Services. */ @Test public void testBusLocationDelete() { System.out.println("busLocationDelete"); int id = 0; Services instance = new Services(); String expResult = ""; String result = instance.busLocationDelete(id); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } /** * Test of busUpdateGet method, of class Services. */ @Test public void testBusUpdateGet() { System.out.println("busUpdateGet"); Services instance = new Services(); String expResult = ""; String result = instance.busUpdateGet(); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail("The test case is a prototype."); } }
{ "content_hash": "afee578b2764fc9b6032ca03e74b23e5", "timestamp": "", "source": "github", "line_count": 181, "max_line_length": 83, "avg_line_length": 31.646408839779006, "alnum_prop": 0.6178421787709497, "repo_name": "DARKATOS/BUSAPP", "id": "5c38b569f1ccd13d3b3397d02bec12b2175aedcb", "size": "5728", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "BUSAPP/test/services/ServicesTest.java", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "8912" }, { "name": "Java", "bytes": "44710" }, { "name": "JavaScript", "bytes": "7739" }, { "name": "SQLPL", "bytes": "3267" } ], "symlink_target": "" }
/* * www.ichmags.net - Backgammon */ package net.ichmags.backgammon; import net.ichmags.backgammon.setup.IPlayer; import net.ichmags.backgammon.setup.impl.Player; /** * A helper class to easily share common definitions and functionalities. * * @author Anastasios Patrikis */ public class CommonEngine { /** * Get the {@link Player} identified by his {@link IPlayer.ID}. * * @param currentID The {@link IPlayer.ID} to use for lookup. * @param player1 The candidate number <i>1</i>. * @param player2 The candidate number <i>2</i>. * @return The {@link Player}. */ public static IPlayer getPlayer(IPlayer.ID currentID, IPlayer player1, IPlayer player2) { return (player1.getID().equals(currentID)) ? player1 : player2; } /** * Get the opponent of a {@link Player}. * * @param current The current {@link Player}. * @param player1 The candidate number <i>1</i>. * @param player2 The candidate number <i>2</i>. * @return The opponent {@link Player}. */ public static IPlayer getOponent(IPlayer current, IPlayer player1, IPlayer player2) { return (player1.equals(current)) ? player2 : player1; } /** * Get the opponent of a {@link Player}. * * @param currentID The current {@link IPlayer.ID}. * @param player1 The candidate number <i>1</i>. * @param player2 The candidate number <i>2</i>. * @return The opponent {@link Player}. */ public static IPlayer getOponent(IPlayer.ID currentID, IPlayer player1, IPlayer player2) { return (player1.getID().equals(currentID)) ? player2 : player1; } }
{ "content_hash": "8a1e5c2cbc4e97781b35ca2885ea6247", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 91, "avg_line_length": 29.055555555555557, "alnum_prop": 0.6832377310388783, "repo_name": "apatrikis/imn-backgammon-engine-impl", "id": "c0c8bc0e58c123d914d81cd117de58ea7ddb105d", "size": "1569", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/main/java/net/ichmags/backgammon/CommonEngine.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "142116" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/tutorial_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical"> <org.buildmlearn.toolkit.views.TextViewPlus android:id="@+id/tutorial_title" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:padding="16dp" android:text="@string/screen_1_title" android:textSize="@dimen/headline"/> <ImageView android:id="@+id/device_image" android:layout_width="wrap_content" android:layout_height="0dp" android:layout_weight="1" android:adjustViewBounds="true" android:contentDescription="@string/tutorial_image" android:scaleType="centerInside"/> <org.buildmlearn.toolkit.views.TextViewPlus android:id="@+id/tutorial_desc" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="16dp" android:gravity="center" android:padding="16dp" android:text="@string/screen_1_desc" android:textSize="@dimen/body"/> </LinearLayout>
{ "content_hash": "db1eb7d6670e2123f1317881dc2d279a", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 62, "avg_line_length": 35.078947368421055, "alnum_prop": 0.660165041260315, "repo_name": "opticod/BuildmLearn-Toolkit-Android", "id": "f5c093a9ce69ed55c0cc4640645bc7bfb7e91d93", "size": "1333", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "source-code/app/src/main/res/layout/tutorial_layout.xml", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Java", "bytes": "815190" } ], "symlink_target": "" }
@implementation CocoaVideoScriptModel + (NSDictionary *)JSONKeyPathsByPropertyKey { return @{ }; } + (NSValueTransformer *)startTimeJSONTransformer { return [MTLValueTransformer reversibleTransformerWithForwardBlock:^id(id str) { return [NSNumber numberWithLong:([CocoaVideoScriptModel getMilliSecondsFromString:str] / 1000)]; } reverseBlock:^id(id milliseconds) { return [CocoaVideoScriptModel getDateStringFromMilliSeconds:((NSNumber *)milliseconds).longValue]; }]; } + (NSValueTransformer *)endTimeJSONTransformer { return [MTLValueTransformer reversibleTransformerWithForwardBlock:^id(id str) { return [NSNumber numberWithLong:([CocoaVideoScriptModel getMilliSecondsFromString:str] / 1000)]; } reverseBlock:^id(id milliseconds) { return [CocoaVideoScriptModel getDateStringFromMilliSeconds:((NSNumber *)milliseconds).longValue]; }]; } + (long)getMilliSecondsFromString:(NSString *)dateString { NSArray *dateComponents = [dateString componentsSeparatedByString:@":"]; int minuteValue = ((NSString *)dateComponents[0]).intValue; int secondValue = ((NSString *)dateComponents[1]).intValue; int millisecondValue = ((NSString *)dateComponents[2]).intValue; return (millisecondValue + secondValue * 1000 + minuteValue * 60000); } + (NSString *)getDateStringFromMilliSeconds:(long)milliSeconds { int minuteValue = ceil(milliSeconds / 60000); NSString *minuteStr = minuteValue >= 10 ? [NSString stringWithFormat:@"%d", minuteValue] : [NSString stringWithFormat:@"0%d", minuteValue]; int secondValue = ceil((milliSeconds - minuteValue * 60000) / 1000); NSString *secondStr = secondValue >= 10 ? [NSString stringWithFormat:@"%d", secondValue] : [NSString stringWithFormat:@"0%d", secondValue]; int millisecondValue = milliSeconds - minuteValue * 60000 - secondValue * 1000; NSString *millisecondStr = millisecondValue >= 100 ? [NSString stringWithFormat:@"%d", millisecondValue] : (millisecondValue >= 10 ? [NSString stringWithFormat:@"0%d", millisecondValue] : [NSString stringWithFormat:@"%00d", millisecondValue]); return [NSString stringWithFormat:@"%@:%@:%@", minuteStr, secondStr, millisecondStr]; } @end
{ "content_hash": "f2c7898bac81182653475773a9970b7f", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 247, "avg_line_length": 46.8125, "alnum_prop": 0.7298620382732532, "repo_name": "chenyongwei/CocoaVideoPlayer", "id": "482832909ee447472dff5e04c236aacb41298f09", "size": "2531", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "CocoaVideoPlayer/DataModel/CocoaVideoScriptModel.m", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "74328" }, { "name": "C++", "bytes": "52495" }, { "name": "Objective-C", "bytes": "488873" }, { "name": "Objective-C++", "bytes": "83568" }, { "name": "Perl", "bytes": "89" }, { "name": "Shell", "bytes": "3825" } ], "symlink_target": "" }
.. _ref-sorted-containers: ---------------------------------------- Overview of Sorted Containers ---------------------------------------- Three sorted containers are provided: SortedDict, SortedMultiDict and SortedSet. *SortedDict* is similar to the built-in Julia type ``Dict`` with the additional feature that the keys are stored in sorted order and can be efficiently iterated in this order. SortedDict is a subtype of Associative. It is slower than ``Dict`` because looking up a key requires an O(log *n*) tree search rather than an expected O(1) hash-table lookup time as with Dict. SortedDict is a parametrized type with three parameters, the key type ``K``, the value type ``V``, and the ordering type ``O``. SortedSet has only keys; it is an alternative to the built-in ``Set`` container. Internally, SortedSet is implemented as a SortedDict in which the value type is ``Void``. Finally, SortedMultiDict is similar to SortedDict except that each key can be associated with multiple values. The key=>value pairs in a SortedMultiDict are stored according to the sorted order for keys, and key=>value pairs with the same key are stored in order of insertion. The containers internally use a 2-3 tree, which is a kind of balanced tree and is described in many elementary data structure textbooks. The containers require two functions to compare keys: a *less-than* and *equals* function. With the default ordering argument, the comparison functions are ``isless(key1,key2)`` (true when ``key1 < key2``) and ``isequal(key1,key2)`` (true when ``key1 == key2``) where ``key1`` and ``key2`` are keys. More details are provided below. Tokens for Sorted Containers ~~~~~~~~~~~~~~~~~~~~~~~~~~~ The sorted container objects use a special type for indexing called a *token* defined as a two-entry tuple and aliased as ``SDToken``, ``SMDToken``, and ``SetToken`` for SortedDict, SortedMultiDict and SortedSet respectively. A token is the address of a single data item in the container and can be dereferenced in time O(1). The first entry of a Token tuple is the container as a whole, and the second refers to the particular item. The second part is called a *semitoken*. The types for a semitoken are ``SDSemiToken``, ``SMDSemiToken``, and ``SetSemiToken`` for the three types of containers SortedDict, SortedMultiDict and SortedSet. These types are all aliases of ``IntSemiToken``. A restriction for the sorted containers is that ``IntSemiToken`` or its aliases cannot used as the key-type. This is because ambiguity would result between the two subscripting calls ``sc[k]`` and ``sc[st]`` described below. In the rare scenario that a sorted container whose key-type is ``IntSemiToken`` is required, a workaround is to wrap the key inside another immutable structure. In the current version of Julia, it is costly to operate on tuples whose entries are not bits-types because such tuples are allocated on the heap. For example, the first entry of a token is a pointer to a container (a non-bits type), so a new token is allocated on the heap rather than the stack. In order to avoid performance loss, the package uses tokens less frequently than semitokens. For a function taking a token as an argument like ``deref`` described below, if it is invoked by explicitly naming the token like this:: tok = (sc,st) # sc is a sorted container, st is a semitoken k,v = deref(tok) then there may be a loss of performance compared to:: k,v = deref((sc,st)) because the former needs an extra heap allocation step for ``tok``. The notion of token is similar to the concept of iterators used by C++ standard containers. Tokens can be explicitly advanced or regressed through the data in the sorted order; they are implicitly advanced or regressed via iteration loops defined below. A token may take two special values: the *before-start* value and the *past-end* value. These values act as lower and upper bounds on the actual data. The before-start token can be advanced, while the past-end token can be regressed. A dereferencing operation on either leads to an error. In the current implementation, semitokens are internally stored as integers. However, for the purpose of future compatibility, the user should not extract this internal representation; these integers do not have a documented interpretation in terms of the container. Constructors for Sorted Containers ~~~~~~~~~~~~~~~~~~~~~~~~~~~ ``SortedDict(d)`` Argument ``d`` is an ordinary Julia dict (or any associative type) used to initialize the container:: c = SortedDict(Dict("New York" => 1788, "Illinois" => 1818)) In this example the key-type is deduced to be String, while the value-type is Int. The default ordering object ``Forward`` is used. See below for more information about ordering. ``SortedDict(d,o)`` Argument ``d`` is an ordinary Julia dict (or any associative type) used to initialize the container and ``o`` is an ordering object used for ordering the keys. ``SortedDict(k1=>v1, k2=>v2, ...)`` Arguments are key-value pairs for insertion into the dictionary. The keys must be of the same type as one another; the values must also be of one type. ``SortedDict(o, k1=>v1, k2=>v2, ...)`` The first argument ``o`` is an ordering object. The remaining arguments are key-value pairs for insertion into the dictionary. The keys must be of the same type as one another; the values must also be of one type. ``SortedDict(iter)`` Takes an arbitrary iterable object of key=>value pairs. The default Forward ordering is used. ``SortedDict(iter,o)`` Takes an arbitrary iterable object of key=>value pairs. The ordering object ``o`` is explicitly given. ``SortedDict{K,V,Ord}(o)`` Construct an empty SortedDict in which type parameters are explicitly listed; ordering object is explicitly specified. (See below for discussion of ordering.) An empty SortedDict may also be constructed using ``SortedDict(Dict{K,V}(),o)`` where the ``o`` argument is optional. ``SortedMultiDict(ks,vs,o)`` Construct a SortedMultiDict using keys given by ``ks``, values given by ``vs`` and ordering object ``o``. The ordering object defaults to ``Forward`` if not specified. The two arguments ``ks`` and ``vs`` are 1-dimensional arrays of the same length in which ``ks`` holds keys and ``vs`` holds the corresponding values. ``SortedMultiDict(k1=>v1, k2=>v2, ...)`` Arguments are key-value pairs for insertion into the multidict. The keys must be of the same type as one another; the values must also be of one type. ``SortedMultiDict(o, k1=>v1, k2=>v2, ...)`` The first argument ``o`` is an ordering object. The remaining arguments are key-value pairs for insertion into the multidict. The keys must be of the same type as one another; the values must also be of one type. ``SortedMultiDict(iter)`` Takes an arbitrary iterable object of key=>value pairs. The default Forward ordering is used. ``SortedMultiDict(iter,o)`` Takes an arbitrary iterable object of key=>value pairs. The ordering object ``o`` is explicitly given. ``SortedMultiDict{K,V,Ord}(o)`` Construct an empty sorted multidict in which type parameters are explicitly listed; ordering object is explicitly specified. (See below for discussion of ordering.) An empty SortedMultiDict may also be constructed via ``SortedMultiDict(K[], V[], o)`` where the ``o`` argument is optional. ``SortedSet(iter,o)`` Construct a SortedSet using keys given by iterable ``iter`` (e.g., an array) and ordering object ``o``. The ordering object defaults to ``Forward`` if not specified. ``SortedSet{K,Ord}(o)`` Construct an empty sorted set in which type parameter is explicitly listed; ordering object is explicitly specified. (See below for discussion of ordering.) An alternate way to create an empty set of type ``K`` is ``SortedSet(K[], o)``; again, the order argument defaults to ``Forward`` if not specified. Complexity of Sorted Containers ~~~~~~~~~~~~~~~~~~~~~~~~~~~ In the list of functions below, the running time of the various operations is provided. In these running times, *n* denotes the current size (number of items) in the container at the time of the function call, and *c* denotes the time needed to compare two keys. Navigating the Containers ~~~~~~~~~~~~~~~~~~~~~~~~~~~ ``sd[k]`` Argument ``sd`` is a SortedDict and ``k`` is a key. In an expression, this retrieves the value associated with the key (or ``KeyError`` if none). On the left-hand side of an assignment, this assigns or reassigns the value associated with the key. (For assigning and reassigning, see also ``insert!`` below.) Time: O(*c* log *n*) ``find(sd,k)`` Argument ``sd`` is a SortedDict and argument ``k`` is a key. This function returns the semitoken that refers to the item whose key is ``k``, or past-end semitoken if ``k`` is absent. Time: O(*c* log *n*) ``deref((sc,st))`` Argument ``(sc,st)`` is a token (i.e., ``sc`` is a container and ``st`` is a semitoken). Note the double-parentheses in the calling syntax: the argument of ``deref`` is a token, which is defined to be a 2-tuple. This returns a key=>value pair. pointed to by the token for SortedDict and SortedMultiDict. Note that the syntax ``k,v=deref((sc,st))`` is valid because Julia automatically iterates over the two entries of the Pair in order to assign ``k`` and ``v``. For SortedSet this returns a key. Time: O(1) ``deref_key((sc,st))`` Argument ``(sc,st)`` is a token for SortedMultiDict or SortedDict. This returns the key (i.e., the first half of a key=>value pair) pointed to by the token. This functionality is available as plain ``deref`` for SortedSet. Time: O(1) ``deref_value((sc,st))`` Argument ``(sc,st)`` is a token for SortedMultiDict or SortedDict. This returns the value (i.e., the second half of a key=>value pair) pointed to by the token. Time: O(1) ``startof(sc)`` Argument ``sc`` is SortedDict, SortedMultiDict or SortedSet. This function returns the semitoken of the first item according to the sorted order in the container. If the container is empty, it returns the past-end semitoken. Time: O(log *n*) ``endof(sc)`` Argument ``sc`` is a SortedDict, SortedMultiDict or SortedSet. This function returns the semitoken of the last item according to the sorted order in the container. If the container is empty, it returns the before-start semitoken. Time: O(log *n*) ``first(sc)`` Argument ``sc`` is a SortedDict, SortedMultiDict or SortedSet This function returns the first item (a ``k=>v`` pair for SortedDict and SortedMultiDict or a key for SortedSet) according to the sorted order in the container. Thus, ``first(sc)`` is equivalent to ``deref((sc,startof(sc)))``. It is an error to call this function on an empty container. Time: O(log *n*) ``last(sc)`` Argument ``sc`` is a SortedDict, SortedMultiDict or SortedSet. This function returns the last item (a ``k=>v`` pair for SortedDict and SortedMultiDict or a key for SortedSet) according to the sorted order in the container. Thus, ``last(sc)`` is equivalent to ``deref((sc,endof(sc)))``. It is an error to call this function on an empty container. Time: O(log *n*) ``pastendsemitoken(sc)`` Argument ``sc`` is a SortedDict, SortedMultiDict or SortedSet. This function returns the past-end semitoken. Time: O(1) ``beforestartsemitoken(sc)`` Argument ``sc`` is a SortedDict, SortedMultiDict or SortedSet. This function returns the before-start semitoken. Time: O(1) ``advance((sc,st))`` Argument ``(sc,st)`` is a token. This function returns the semitoken of the next entry in the container according to the sort order of the keys. After the last item, this routine returns the past-end semitoken. It is an error to invoke this function if ``(sc,st)`` is the past-end token. If ``(sc,st)`` is the before-start token, then this routine returns the semitoken of the first item in the sort order (i.e., the same semitoken returned by the ``startof`` function). Time: O(log *n*) ``regress((sc,st))`` Argument ``(sc,st)`` is a token. This function returns the semitoken of the previous entry in the container according to the sort order of the keys. If ``(sc,st)`` indexes the first item, this routine returns the before-start semitoken. It is an error to invoke this function if ``(sc,st)`` is the before-start token. If ``(sc,st)`` is the past-end token, then this routine returns the smitoken of the last item in the sort order (i.e., the same semitoken returned by the ``endof`` function). Time: O(log *n*) ``searchsortedfirst(sc,k)`` Argument ``sc`` is a SortedDict, SortedMultiDict or SortedSet and ``k`` is a key. This routine returns the semitoken of the first item in the container whose key is greater than or equal to ``k``. If there is no such key, then the past-end semitoken is returned. Time: O(*c* log *n*) ``searchsortedlast(sc,k)`` Argument ``sc`` is a SortedDict, SortedMultiDict or SortedSet and ``k`` is a key. This routine returns the semitoken of the last item in the container whose key is less than or equal to ``k``. If there is no such key, then the before-start semitoken is returned. Time: O(*c* log *n*) ``searchsortedafter(sc,k)`` Argument ``sc`` is a SortedDict, SortedMultiDict or SortedSet and ``k`` is an element of the key type. This routine returns the semitoken of the first item in the container whose key is greater than ``k``. If there is no such key, then the past-end semitoken is returned. Time: O(*c* log *n*) ``searchequalrange(sc,k)`` Argument ``sc`` is a SortedMultiDict and ``k`` is an element of the key type. This routine returns a pair of semitokens; the first of the pair is the semitoken addressing the first item in the container with key ``k`` and the second is the semitoken addressing the last item in the container with key ``k``. If no item matches the given key, then the pair (past-end-semitoken, before-start-semitoken) is returned. Time: O(*c* log *n*) Inserting & Deleting in Sorted Containers ~~~~~~~~~~~~~~~~~~~~~~~~~~~ ``empty!(sc)`` Argument ``sc`` is a SortedDict, SortedMultiDict or SortedSet. This empties the container. Time: O(1). ``insert!(sc,k,v)`` Argument ``sc`` is a SortedDict or SortedMultiDict, ``k`` is a key and ``v`` is the corresponding value. This inserts the ``(k,v)`` pair into the container. If the key is already present in a SortedDict or SortedSet, this overwrites the old value. In the case of SortedMultiDict, no overwriting takes place (since SortedMultiDict allows the same key to associate with multiple values). In the case of SortedDict, the return value is a pair whose first entry is boolean and indicates whether the insertion was new (i.e., the key was not previously present) and the second entry is the semitoken of the new entry. In the case of SortedMultiDict, a semitoken is returned (but no boolean). Time: O(*c* log *n*) ``insert!(sc,k)`` Argument ``sc`` is a SortedSet and ``k`` is a key. This inserts the key into the container. If the key is already present in a this overwrites the old value. (This is not necessarily a no-op; see below for remarks about the customizing the sort order.) The return value is a pair whose first entry is boolean and indicates whether the insertion was new (i.e., the key was not previously present) and the second entry is the semitoken of the new entry. Time: O(*c* log *n*) ``push!(sc,k)`` Argument ``sc`` is a SortedSet and ``k`` is a key. This inserts the key into the container. If the key is already present in a this overwrites the old value. (This is not necessarily a no-op; see below for remarks about the customizing the sort order.) The return value is ``sc``. Time: O(*c* log *n*) ``push!(sc, k=>v)`` Argument ``sc`` is a SortedDict or SortedMultiDict and ``k=>v`` is a key-value pair. This inserts the key-value pair into the container. If the key is already present in a this overwrites the old value. The return value is ``sc``. Time: O(*c* log *n*) ``delete!((sc,st))`` Argument ``(sc,st)`` is a token for a SortedDict, SortedMultiDict or SortedSet. This operation deletes the item addressed by ``(sc,st)``. It is an error to call this on an entry that has already been deleted or on the before-start or past-end tokens. After this operation is complete, ``(sc,st)`` is an invalid token and cannot be used in any further operations. Time: O(log *n*) ``delete!(sc,k)`` Argument ``sc`` is a SortedDict or SortedSet and ``k`` is a key. This operation deletes the item whose key is ``k``. It is a ``KeyError`` if ``k`` is not a key of an item in the container. After this operation is complete, any token addressing the deleted item is invalid. Returns ``sc``. Time: O(*c* log *n*) ``pop!(sc,k)`` Deletes the item with key ``k`` in SortedDict or SortedSet ``sc`` and returns the value that was associated with ``k`` in the case of SortedDict or ``k`` itself in the case of SortedSet. A ``KeyError`` results if ``k`` is not in ``sc``. Time: O(*c* log *n*) ``pop!(ss)`` Deletes the item with first key in SortedSet ``ss`` and returns the key. A ``BoundsError`` results if ``ss`` is empty. Time: O(*c* log *n*) ``sc[st]`` If ``st`` is a semitoken and ``sc`` is a SortedDict or SortedMultiDict, then ``sc[st]`` refers to the value field of the (key,value) pair that the full token ``(sc,st)`` refers to. This expression may occur on either side of an assignment statement. Time: O(1) Token Manipulation ~~~~~~~~~~~~~~~~~~~~~~~~~~~ ``compare(sc,st1,st2)`` Here, ``st1`` and ``st2`` are semitokens for the same container ``sc``; this function determines the relative positions of the data items indexed by ``(sc,st1)`` and ``(sc,st2)`` in the sorted order. The return value is -1 if ``(sc,st1)`` precedes ``(sc,st2)``, 0 if they are equal, and 1 if ``(sc,st1)`` succeeds ``(sc,st2)``. This function compares the tokens by determining their relative position within the tree without dereferencing them. For SortedDict it is mostly equivalent to comparing ``deref_key((sc,st1))`` to ``deref_key((sc,st2))`` using the ordering of the SortedDict except in the case that either ``(sc,st1)`` or ``(sc,st2)`` is the before-start or past-end token, in which case the ``deref`` operation will fail. Which one is more efficient depends on the time-complexity of comparing two keys. Similarly, for SortedSet it is mostly equivalent to comparing ``deref((sc,st1))`` to ``deref((sc,st2))``. For SortedMultiDict, this function is not equivalent to a key comparison since two items in a SortedMultiDict with the same key are not necessarily the same item. Time: O(log *n*) ``status((sc,st))`` This function returns 0 if the token ``(sc,st)`` is invalid (e.g., refers to a deleted item), 1 if the token is valid and points to data, 2 if the token is the before-start token and 3 if it is the past-end token. Time: O(1) Iteration Over Sorted Containers ~~~~~~~~~~~~~~~~~~~~~~~~~~~ As is standard in Julia, iteration over the containers is implemented via calls to three functions, ``start``, ``next`` and ``done``. It is usual practice, however, to call these functions implicitly with a for-loop rather than explicitly, so they are presented here in for-loop notation. Internally, all of these iterations are implemented with semitokens that are advanced via the ``advance`` operation. Each iteration of these loops requires O(log *n*) operations to advance the semitoken. If one loops over an entire container, then the amortized cost of advancing the semitoken drops to O(1). The following snippet loops over the entire container ``sc``, where ``sc`` is a SortedDict or SortedMultiDict:: for (k,v) in sc < body > end In this loop, ``(k,v)`` takes on successive (key,value) pairs according to the sort order of the key. If one uses:: for p in sc < body > end where ``sc`` is a SortedDict or SortedMultiDict, then ``p`` is a ``k=>v`` pair. For SortedSet one uses:: for k in ss < body > end There are two ways to iterate over a subrange of a container. The first is the inclusive iteration for SortedDict and SortedMultiDict:: for (k,v) in inclusive(sc,st1,st2) < body > end Here, ``st1`` and ``st2`` are semitokens that refer to the container ``sc``. It is acceptable for ``(sc,st1)`` to be the past-end token or ``(sc,st2)`` to be the before-start token (in these cases, the body is not executed). If ``compare(sc,st1,st2)==1`` then the body is not executed. A second calling format for ``inclusive`` is ``inclusive(sc,(st1,st2))``. One purpose for second format is so that the return value of ``searchequalrange`` may be used directly as the second argument to ``inclusive``. One can also define a loop that excludes the final item:: for (k,v) in exclusive(sc,st1,st2) < body > end In this case, all the data addressed by tokens from ``(sc,st1)`` up to but excluding ``(sc,st2)`` are executed. The body is not executed at all if ``compare(sc,st1,st2)>=0``. In this setting, either or both can be the past-end token, and ``(sc,st2)`` can be the before-start token. For the sake of consistency, ``exclusive`` also supports the calling format ``exclusive(sc,(st1,st2))``. In the previous few snippets, if the loop object is ``p`` instead of ``(k,v)``, then ``p`` is a ``k=>v`` pair. Both the ``inclusive`` and ``exclusive`` functions return objects that can be saved and used later for iteration. The validity of the tokens is not checked until the loop initiates. For SortedSet the usage is:: for k in inclusive(ss,st1,st2) < body > end for k in exclusive(ss,st1,st2) < body > end If ``sc`` is a SortedDict or SortedMultiDict, one can iterate over just keys or just values:: for k in keys(sc) < body > end for v in values(sc) < body > end Finally, one can retrieve semitokens during any of these iterations. In the case of SortedDict and SortedMultiDict, one uses:: for (st,k,v) in semitokens(sc) < body > end for (st,k) in semitokens(keys(sc)) < body > end for (st,v) in semitokens(values(sc)) < body > end In each of the above three iterations, ``st`` is a semitoken referring to the current ``(k,v)`` pair. In the case of SortedSet, the following iteration may be used:: for (st,k) in semitokens(ss) < body > end If one wishes to retrieve only semitokens, the following may be used:: for st in onlysemitokens(sc) < body > end In this case, ``sc`` is a SortedDict, SortedMultiDict, or SortedSet. To be compatible with standard containers, the package also offers ``eachindex`` iteration:: for ind in eachindex(sc) < body > end This iteration function ``eachindex`` is equivalent to ``keys`` in the case of SortedDict. It is equivalent to ``onlysemitokens`` in the case of SortedMultiDict and SortedMultiSet. In place of ``sc`` in the above ``keys``, ``values`` and ``semitokens``, snippets, one could also use ``inclusive(sc,st1,st2)`` or ``exclusive(sc,st1,st2)``. Similarly, for SortedSet, one can iterate over ``semitokens(inclusive(ss,st1,st2))`` or ``semitokens(exclusive(ss,st1,st2))`` Note that it is acceptable for the loop body in the above ``semitokens`` code snippets to invoke ``delete!((sc,st))`` or ``delete!((ss,st))``. This is because the for-loop internal state variable is already advanced to the next token at the beginning of the body, so ``st`` is not necessarily referred to in the loop body (unless the user refers to it). Other Functions ~~~~~~~~~~~~~~~~~~~~~~~~~~~ ``isempty(sc)`` Returns ``true`` if the container is empty (no items). Time: O(1) ``length(sc)`` Returns the length, i.e., number of items, in the container. Time: O(1) ``in(p,sc)`` Returns true if ``p`` is in ``sc``. In the case that ``sc`` is a SortedDict or SortedMultiDict, ``p`` is a key=>value pair. In the case that ``sc`` is a SortedSet, ``p`` should be a key. Time: O(*c* log *n*) for SortedDict and SortedSet. In the case of SortedMultiDict, the time is O(*cl* log *n*), where *l* stands for the number of entries that have the key of the given pair. (So therefore this call is inefficient if the same key addresses a large number of values, and an alternative should be considered.) ``in(x,iter)`` Returns true if ``x`` is in ``iter``, where ``iter`` refers to any of the iterable objects described above in the discussion of container loops and ``x`` is of the appropriate type. For all of the iterables except the five listed below, the algorithm used is a linear-time search. For example, the call:: (k=>v) in exclusive(sd,st1,st2) where ``sd`` is a SortedDict, ``st1`` and ``st2`` are semitokens, ``k`` is a key, and ``v`` is a value, will loop over all entries in the dictionary between the two tokens and a compare for equality using ``isequal`` between the indexed item and ``k=>v``. The five exceptions are:: (k=>v) in sd (k=>v) in smd k in ss k in keys(sd) k in keys(smd) Here, ``sd`` is a SortedDict, ``smd`` is a SortedMultiDict, and ``ss`` is a SortedSet. These five invocations of ``in`` use the index structure of the sorted container and test equality based on the order object of the keys rather than ``isequal``. Therefore, these five are all faster than linear-time looping. The first three were already discussed in the previous entry. The last two are equivalent to ``haskey(sd,k)`` and ``haskey(smd,k)`` respectively. To force the use of ``isequal`` test on the keys rather than the order object (thus slowing the execution from logarithmic to linear time), replace the above five constructs with these:: (k=>v) in collect(sd) (k=>v) in collect(smd) k in collect(ss) k in collect(keys(sd)) k in collect(keys(smd)) ``eltype(sc)`` Returns the (key,value) type (a 2-entry pair, i.e., ``Pair{K,V}``) for SortedDict and SortedMultiDict. Returns the key type for SortedSet. This function may also be applied to the type itself. Time: O(1) ``keytype(sc)`` Returns the key type for SortedDict, SortedMultiDict and SortedSet. This function may also be applied to the type itself. Time: O(1) ``valtype(sc)`` Returns the value type for SortedDict and SortedMultiDict. This function may also be applied to the type itself. Time: O(1) ``similar(sc)`` Returns a new SortedDict, SortedMultiDict, or SortedSet of the same type and with the same ordering as ``sc`` but with no entries (i.e., empty). Time: O(1) ``orderobject(sc)`` Returns the order object used to construct the container. Time: O(1) ``haskey(sc,k)`` Returns true if key ``k`` is present for SortedDict, SortedMultiDict or SortedSet ``sc``. For SortedSet, ``haskey(sc,k)`` is a synonym for ``in(k,sc)``. For SortedDict and SortedMultiDict, ``haskey(sc,k)`` is equivalent to ``in(k,keys(sc))``. Time: O(*c* log *n*) ``get(sd,k,v)`` Returns the value associated with key ``k`` where ``sd`` is a SortedDict, or else returns ``v`` if ``k`` is not in ``sd``. Time: O(*c* log *n*) ``get!(sd,k,v)`` Returns the value associated with key ``k`` where ``sd`` is a SortedDict, or else returns ``v`` if ``k`` is not in ``sd``, and in the latter case, inserts ``(k,v)`` into ``sd``. Time: O(*c* log *n*) ``getkey(sd,k,defaultk)`` Returns key ``k`` where ``sd`` is a SortedDict, if ``k`` is in ``sd`` else it returns ``defaultk``. If the container uses in its ordering an ``eq`` method different from isequal (e.g., case-insensitive ASCII strings illustrated below), then the return value is the actual key stored in the SortedDict that is equivalent to ``k`` according to the ``eq`` method, which might not be equal to ``k``. Similarly, if the user performs an implicit conversion as part of the call (e.g., the container has keys that are floats, but the ``k`` argument to ``getkey`` is an Int), then the returned key is the actual stored key rather than ``k``. Time: O(*c* log *n*) ``isequal(sc1,sc2)`` Checks if two containers are equal in the sense that they contain the same items; the keys are compared using the ``eq`` method, while the values are compared with the ``isequal`` function. In the case of SortedMultiDict, equality requires that the values associated with a particular key have same order (that is, the same insertion order). Note that ``isequal`` in this sense does not imply any correspondence between semitokens for items in ``sc1`` with those for ``sc2``. If the equality-testing method associated with the keys and values implies hash-equivalence in the case of SortedDict, then ``isequal`` of the entire containers implies hash-equivalence of the containers. Time: O(*cn* + *n* log *n*) ``packcopy(sc)`` This returns a copy of ``sc`` in which the data is packed. When deletions take place, the previously allocated memory is not returned. This function can be used to reclaim memory after many deletions. Time: O(*cn* log *n*) ``deepcopy(sc)`` This returns a copy of ``sc`` in which the data is deep-copied, i.e., the keys and values are replicated if they are mutable types. A semitoken for the original ``sc`` is a valid semitoken for the copy because this operation preserves the relative positions of the data in memory. Time O(*maxn*), where *maxn* denotes the maximum size that ``sc`` has attained in the past. ``packdeepcopy(sc)`` This returns a packed copy of ``sc`` in which the keys and values are deep-copied. This function can be used to reclaim memory after many deletions. Time: O(*cn* log *n*) ``merge(sc1, sc2...)`` This returns a SortedDict or SortedMultiDict that results from merging SortedDicts or SortedMultiDicts ``sc1``, ``sc2``, etc., which all must have the same key-value-ordering types. In the case of keys duplicated among the arguments, the rightmost argument that owns the key gets its value stored for SortedDict. In the case of SortedMultiDict all the key-value pairs are stored, and for keys shared between ``sc1`` and ``sc2`` the ordering is left-to-right. This function is not available for SortedSet, but the ``union`` function (see below) provides equivalent functionality. Time: O(*cN* log *N*), where *N* is the total size of all the arguments. ``merge!(sc, sc1...)`` This updates ``sc`` by merging SortedDicts or SortedMultiDicts ``sc1``, etc. into ``sc``. These must all must have the same key-value types. In the case of keys duplicated among the arguments, the rightmost argument that owns the key gets its value stored for SortedDict. In the case of SortedMultiDict all the key-value pairs are stored, and for overlapping keys the ordering is left-to-right. This function is not available for SortedSet, but the ``union!`` function (see below) provides equivalent functionality. Time: O(*cN* log *N*), where *N* is the total size of all the arguments. Set operations ~~~~~~~~~~~~~~~~~~~~~~~~~~~ The SortedSet container supports the following set operations. Note that in the case of intersect, symdiff and setdiff, the two SortedSets should have the same key and ordering object. If they have different key or ordering types, no error message is produced; instead, the built-in default versions of these functions (that can be applied to ``Any`` iterables and that return arrays) are invoked. ``union!(ss, iterable)`` This function inserts each item from the second argument (which must iterable) into the SortedSet ``ss``. The items must be convertible to the key-type of ``ss``. Time: O(*ci* log *n*) where *i* is the number of items in the iterable argument. ``union(ss, iterable...)`` This function creates a new SortedSet (the return argument) and inserts each item from ``ss`` and each item from each iterable argument into the returned SortedSet. Time: O(*cn* log *n*) where *n* is the total number of items in all the arguments. ``intersect(ss, others...)`` Each argument is a SortedSet with the same key and order type. The return variable is a new SortedSet that is the intersection of all the sets that are input. Time: O(*cn* log *n*), where *n* is the total number of items in all the arguments. ``symdiff(ss1, ss2)`` The two argument are sorted sets with the same key and order type. This operation computes the symmetric difference, i.e., a sorted set containing entries that are in one of ``ss1``, ``ss2`` but not both. Time: O(*cn* log *n*), where *n* is the total size of the two containers. ``setdiff(ss1, ss2)`` The two arguments are sorted sets with the same key and order type. This operation computes the difference, i.e., a sorted set containing entries that in are in ``ss1`` but not ``ss2``. Time: O(*cn* log *n*), where *n* is the total size of the two containers. ``setdiff!(ss, iterable)`` This function deletes items in ``ss`` that appear in the second argument. The second argument must be iterable and its entries must be convertible to the key type of m1. Time: O(*cm* log *n*), where *n* is the size of ``ss`` and *m* is the number of items in ``iterable``. ``issubset(iterable, ss)`` This function checks whether each item of the first argument is an element of the SortedSet ``ss``. The entries must be convertible to the key-type of ``ss``. Time: O(*cm* log *n*), where *n* is the sizes of ``ss`` and *m* is the number of items in ``iterable``. Ordering of keys ~~~~~~~~~~~~~~~~~~~~~~~~~~~ As mentioned earlier, the default ordering of keys uses ``isless`` and ``isequal`` functions. If the default ordering is used, it is a requirement of the container that ``isequal(a,b)`` is true if and only if ``!isless(a,b)`` and ``!isless(b,a)`` are both true. This relationship between ``isequal`` and ``isless`` holds for common built-in types, but it may not hold for all types, especially user-defined types. If it does not hold for a certain type, then a custom ordering argument must be defined as discussed in the next few paragraphs. The name for the default ordering (i.e., using ``isless`` and ``isequal``) is ``Forward``. Note: this is the name of the ordering object; its type is ``ForwardOrdering.`` Another possible ordering object is ``Reverse``, which reverses the usual sorted order. This name must be imported ``import Base.Reverse`` if it is used. As an example of a custom ordering, suppose the keys are of type ``String``, and the user wishes to order the keys ignoring case: *APPLE*, *berry* and *Cherry* would appear in that order, and *APPLE* and *aPPlE* would be indistinguishable in this ordering. The simplest approach is to define an ordering object of the form ``Lt(my_isless)``, where ``Lt`` is a built-in type (see ``ordering.jl``) and ``my_isless`` is the user's comparison function. In the above example, the ordering object would be:: Lt((x,y) -> isless(lowercase(x),lowercase(y))) The ordering object is indicated in the above list of constructors in the ``o`` position (see above for constructor syntax). This approach suffers from a performance hit (10%-50% depending on the container) because the compiler cannot inline or compute the correct dispatch for the function in parentheses, so the dispatch takes place at run-time. A more complicated but higher-performance method to implement a custom ordering is as follows. First, the user creates a singleton type that is a subtype of ``Ordering`` as follows:: immutable CaseInsensitive <: Ordering end Next, the user defines a method named ``lt`` for less-than in this ordering:: lt(::CaseInsensitive, a, b) = isless(lowercase(a), lowercase(b)) The first argument to ``lt`` is an object of the ``CaseInsensitive`` type (there is only one such object since it is a singleton type). The container also needs an equal-to function; the default is:: eq(o::Ordering, a, b) = !lt(o, a, b) && !lt(o, b, a) For a further slight performance boost, the user can also customize this function with a more efficient implementation. In the above example, an appropriate customization would be:: eq(::CaseInsensitive, a, b) = isequal(lowercase(a), lowercase(b)) Finally, the user specifies the unique element of ``CaseInsensitive``, namely the object ``CaseInsensitive()``, as the ordering object to the ``SortedDict``, ``SortedMultiDict`` or ``SortedSet`` constructor. For the above code to work, the module must make the following declarations, typically near the beginning:: import Base.Ordering import Base.lt import DataStructures.eq Cautionary note on mutable keys ~~~~~~~~~~~~~~~~~~~~~~~~~~~ As with ordinary Dicts, keys for the sorted containers can be either mutable or immutable. In the case of mutable keys, it is important that the keys not be mutated once they are in the container else the indexing structure will be corrupted. (The same restriction applies to Dict.) For example, suppose a SortedDict ``sd`` is defined in which the keys are of type ``Array{Int,1}.`` (For this to be possible, the user must provide an ``isless`` function or order object for ``Array{Int,1}`` since none is built into Julia.) Suppose the values of ``sd`` are of type ``Int``. Then the following sequence of statements leaves ``sd`` in a corrupted state:: k = [1,2,3] sd[k] = 19 k[1] = 7 Performance of Sorted Containers ~~~~~~~~~~~~~~~~~~~~~~~~~~~ The sorted containers are currently not optimized for cache performance. This will be addressed in the future. There is a minor performance issue as follows: the container may hold onto a small number of keys and values even after the data records containing those keys and values have been deleted. This may cause a memory drain in the case of large keys and values. It may also lead to a delay in the invocation of finalizers. All keys and values are released completely by the ``empty!`` function.
{ "content_hash": "5d681b915be4f5c48da24e6cc24ebcad", "timestamp": "", "source": "github", "line_count": 1033, "max_line_length": 90, "avg_line_length": 37.20135527589545, "alnum_prop": 0.704494001925629, "repo_name": "JuliaPackageMirrors/DataStructures.jl", "id": "9645f15a6fd5d3160e20b9a3a334686b21a225b7", "size": "38429", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/source/sorted_containers.rst", "mode": "33188", "license": "mit", "language": [ { "name": "Julia", "bytes": "274735" } ], "symlink_target": "" }
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Comprobante extends Model { protected $table = 'comprobantes'; }
{ "content_hash": "b047d155d13d86202e78d9b88cbb6215", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 39, "avg_line_length": 13.9, "alnum_prop": 0.7410071942446043, "repo_name": "ferglezt/ServiciosEducativos", "id": "a3a0b71f04a2786b71db4eadbe0274a04900ef01", "size": "139", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/Comprobante.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "123151" }, { "name": "PHP", "bytes": "157501" }, { "name": "Vue", "bytes": "563" } ], "symlink_target": "" }
module GLib module Deprecatable unless respond_to?(:define_singleton_method) def define_singleton_method(name, &block) singleton_class = class << self; self; end singleton_class.__send__(:define_method, name, &block) end end @@deprecated_const = {} def define_deprecated_const(deprecated_const, new_const = {}) @@deprecated_const[self] ||= {} @@deprecated_const[self][deprecated_const.to_sym] = new_const end def define_deprecated_enums(enums, prefix = nil) enums = module_eval(enums.to_s) rescue return enums.constants.each do |const| deprecated_const = prefix ? "#{prefix}_#{const}" : const new_const = [enums, const].join('::') define_deprecated_const(deprecated_const, new_const) end end alias :define_deprecated_flags :define_deprecated_enums def define_deprecated_singleton_method(deprecated_method, new_method = {}, &block) __define_deprecated_method__(:singleton, deprecated_method, new_method, &block) end def define_deprecated_method(deprecated_method, new_method = {}, &block) __define_deprecated_method__(:instance, deprecated_method, new_method, &block) end def define_deprecated_method_by_hash_args(deprecated_method, old_args, new_args, req_argc = 0, &block) klass = self alias_name = "__deprecatable_#{deprecated_method}__" alias_method alias_name, deprecated_method private alias_name define_method(deprecated_method) do |*margs, &mblock| if (margs.size == req_argc) || (margs.size == (req_argc + 1) && margs.last.is_a?(Hash)) else margs = block.call(self, *margs, &mblock) msg = "#{caller[0]}: '#{klass}##{deprecated_method}(#{old_args})' style has been deprecated." warn "#{msg} Use '#{klass}##{deprecated_method}(#{new_args})' style." end __send__(alias_name, *margs, &mblock) end end @@deprecated_signal = {} def define_deprecated_signal(deprecated_signal, new_signal = {}) @@deprecated_signal[self] ||= {} @@deprecated_signal[self][deprecated_signal.to_s.gsub('_', '-').to_sym] = new_signal end def self.extended(class_or_module) GLib::Instantiatable.class_eval do %w(signal_connect signal_connect_after).each do |connect_method| alias_name = "__deprecatable_#{connect_method}__" next if private_method_defined?(alias_name) alias_method alias_name, connect_method private alias_name define_method(connect_method) do |signal, *margs, &mblock| signal = signal.to_s.gsub('_', '-').to_sym signals = @@deprecated_signal[self] if new_signal = (signals || {})[signal] msg = "#{caller[0]}: '#{signal}' signal has been deprecated." case new_signal when String, Symbol warn "#{msg} Use '#{new_signal}' signal." signal = new_signal when Hash if new_signal[:raise] raise DeprecatedError.new("#{msg} #{new_signal[:raise]}") elsif new_signal[:warn] warn "#{msg} #{new_signal[:warn]}" else warn "#{msg} Don't use this signal anymore." end return end end __send__(alias_name, signal, *margs, &mblock) end end end end private def const_missing(deprecated_const) if new_const = (@@deprecated_const[self] || {})[deprecated_const.to_sym] msg = "#{caller[0]}: '#{[name, deprecated_const].join('::')}' has been deprecated." case new_const when String, Symbol new_const_val = constant_get(new_const) case new_const_val when GLib::Enum, GLib::Flags alt = " or ':#{new_const_val.nick.gsub('-', '_')}'" end warn "#{msg} Use '#{new_const}'#{alt}." return const_set(deprecated_const, new_const_val) when Hash if new_const[:raise] raise DeprecatedError.new("#{msg} #{new_const[:raise]}") elsif new_const[:warn] warn "#{msg} #{new_const[:warn]}" else warn "#{msg} Don't use this constant anymore." end return end end raise NameError.new("uninitialized constant #{[self, deprecated_const].join('::')}") end def constant_get(const) const.split('::').inject(Object){|r, c| r.const_get(c)} end def __define_deprecated_method__(type, deprecated_method, new_method = {}, &block) def_method = type == :singleton ? :define_singleton_method : :define_method sep = type == :singleton ? '.' : '#' klass = self __send__(def_method, deprecated_method) do |*margs, &mblock| msg = "#{caller[0]}: '#{klass}#{sep}#{deprecated_method}' has been deprecated." case new_method when String, Symbol warn "#{msg} Use '#{klass}#{sep}#{new_method}'." __send__(new_method, *margs, &mblock) when Hash if new_method[:raise] raise DeprecatedError.new("#{msg} #{new_method[:raise]}") elsif new_method[:warn] warn "#{msg} #{new_method[:warn]}" block.call(self, *margs, &mblock) if block end end end end end class DeprecatedError < RuntimeError end end
{ "content_hash": "d56f44a5120525c251f5d69be7b3cf2d", "timestamp": "", "source": "github", "line_count": 149, "max_line_length": 106, "avg_line_length": 36.95302013422819, "alnum_prop": 0.5664729386124228, "repo_name": "mat-mo/arch-pkgs", "id": "7da4e61028f23761644eaa3f1f55206e3528a21d", "size": "5506", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ruby-glib2/pkg/ruby-glib2/usr/lib/ruby/gems/2.1.0/gems/glib2-2.1.0/lib/glib2/deprecatable.rb", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
/** * @ngdoc overview * @name pascalprecht.translate * * @description * The main module which holds everything together. */ angular.module('pascalprecht.translate', ['ng']) .run(runTranslate); function runTranslate($translate) { 'use strict'; var key = $translate.storageKey(), storage = $translate.storage(); var fallbackFromIncorrectStorageValue = function () { var preferred = $translate.preferredLanguage(); if (angular.isString(preferred)) { $translate.use(preferred); // $translate.use() will also remember the language. // So, we don't need to call storage.put() here. } else { storage.put(key, $translate.use()); } }; fallbackFromIncorrectStorageValue.displayName = 'fallbackFromIncorrectStorageValue'; if (storage) { if (!storage.get(key)) { fallbackFromIncorrectStorageValue(); } else { $translate.use(storage.get(key))['catch'](fallbackFromIncorrectStorageValue); } } else if (angular.isString($translate.preferredLanguage())) { $translate.use($translate.preferredLanguage()); } } runTranslate.displayName = 'runTranslate';
{ "content_hash": "9033411555f59a9de8aebd72555ce3ef", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 86, "avg_line_length": 27.095238095238095, "alnum_prop": 0.6827768014059754, "repo_name": "k-nut/angular-translate", "id": "622520e1e9af7b0f47b8c62c8efc92cf58bb03ec", "size": "1138", "binary": false, "copies": "25", "ref": "refs/heads/master", "path": "src/translate.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "36687" }, { "name": "JavaScript", "bytes": "349726" }, { "name": "Shell", "bytes": "1272" } ], "symlink_target": "" }
#include "std.h" #include "config.h" #include "lpc_incl.h" #include "file_incl.h" #include "swap.h" #include "simul_efun.h" #include "comm.h" #include "md.h" /* * Swap out programs from objects. * * Todo: * Separate objects/programs, so that they can swapped out * independently. This way even inherited programs could * be swapped, at the expense of not swapping entire program. */ static int num_swapped; static int total_bytes_swapped; static int line_num_bytes_swapped; static char file_name_buf[100]; static char *file_name = file_name_buf; static FILE *swap_file; /* The swap file is opened once */ static struct sw_block { int start; int length; struct sw_block *next; } *swap_free; static int last_data; static int assert_swap_file PROT((void)); static int alloc_swap PROT((int)); static void free_swap PROT((int start, int length)); static int swap_in PROT((char **, int)); static int swap_out PROT((char *, int, int *)); /** ** General swapping routines. **/ /* * Make sure swap file is opened. */ static int assert_swap_file() { if (swap_file == NULL) { #ifndef MSDOS char host[50]; gethostname(host, sizeof host); sprintf(file_name_buf, "%s.%s.%d", SWAP_FILE, host, port_number); file_name = file_name_buf; if (file_name[0] == '/') file_name++; #ifdef OS2 swap_file = fopen(file_name, "w+b"); #else swap_file = fopen(file_name, "w+"); #endif #else swap_file = fopen(strcpy(file_name, "LPMUD.SWAP"), "w+b"); #endif swap_free = 0; last_data = 0; /* Leave this file pointer open ! */ if (swap_file == 0) return 0; } return 1; } /* * Find a position to swap to, using free blocks if possible. * 'length' is the size we need. * * Todo - think about better free block allocation methods */ static int alloc_swap P1(int, length) { struct sw_block *ptr, *prev; int ret; /* * Doing first fit. (next fit might work nicely if next pointer is reset * when a block is freed, anticipating a new allocation of the same size) */ for (ptr = swap_free, prev = 0; ptr; prev = ptr, ptr = ptr->next) { if (ptr->length < length) continue; /* * found a block, update free list */ ret = ptr->start; ptr->start += length; ptr->length -= length; if (ptr->length == 0) { /* * exact fit, remove free block from list */ if (!prev) swap_free = ptr->next; else prev->next = ptr->next; FREE(ptr); } return ret; } /* * no appropriate blocks found, go to end of file */ return last_data; } /* * Free up a chunk of swap space, coalescing free blocks if necessary. * * Todo - think about tradeoff of storing the free block * info in the swap file itself. */ static void free_swap P2(int, start, int, length) { struct sw_block *m, *ptr, *prev; length += sizeof(int); /* extend with size of hidden information */ /* * Construct and insert new free block */ m = (struct sw_block *) DXALLOC(sizeof(struct sw_block), TAG_SWAP, "free_swap"); m->start = start; m->length = length; for (ptr = swap_free, prev = 0; ptr; prev = ptr, ptr = ptr->next) { if (start < ptr->start) break; } if (!prev) { swap_free = m; } else { prev->next = m; } m->next = ptr; /* * Combine adjacent blocks */ if (ptr && m->start + m->length == ptr->start) { m->length += ptr->length; m->next = ptr->next; FREE(ptr); } if (prev && prev->start + prev->length == m->start) { prev->length += m->length; prev->next = m->next; FREE(m); m = prev; } /* * There is an implicit infinite block at the end making life hard Can't * do this earlier, since m and prev could have combined, so prev must be * found again (or use doubly linked list, etc). */ if (m->start + m->length == last_data) { DEBUG_CHECK(m->next, "extraneous free swap blocks!\n"); /* find prev pointer again *sigh* */ for (ptr = swap_free, prev = 0; ptr != m; prev = ptr, ptr = ptr->next); last_data = m->start; FREE(m); if (!prev) swap_free = 0; else prev->next = 0; } } /* * Actually swap something out. * block - the memory to swap out * size - how big it is * locp - the swap location is written to the int this points to */ static int swap_out P3(char *, block, int, size, int *, locp) { extern int errno; if (!block || time_to_swap == 0) return 0; if (!assert_swap_file()) return 0; if (*locp == -1) { /* needs data written out */ *locp = alloc_swap(size + sizeof size); if (fseek(swap_file, *locp, 0) == -1) fatal("Couldn't seek the swap file, errno %d, offset %d.\n", errno, *locp); if (fwrite((char *) &size, sizeof size, 1, swap_file) != 1 || fwrite(block, size, 1, swap_file) != 1) { debug_message("I/O error in swap.\n"); perror("FOO: "); *locp = -1; return 0; } if (*locp >= last_data) last_data = *locp + sizeof size + size; } total_bytes_swapped += size;/* also count sizeof int?? */ return 1; } /* * Read something back in from swap. Return the size. * blockp - a pointer to what will hold the block read in * loc - position in the swap file to read from */ static int swap_in P2(char **, blockp, int, loc) { extern int errno; int size; if (loc == -1) return 0; if (fseek(swap_file, loc, 0) == -1) fatal("Couldn't seek the swap file, errno %d, offset %d.\n", errno, loc); /* find out size */ if (fread((char *) &size, sizeof size, 1, swap_file) == -1) fatal("Couldn't read the swap file.\n"); *blockp = DXALLOC(size, TAG_SWAP, "swap_in"); if (fread(*blockp, size, 1, swap_file) == -1) fatal("Couldn't read the swap file.\n"); total_bytes_swapped -= size; return size; } /** ** Routines to swap/load specific things. **/ /* * marion - adjust pointers for swap out and later relocate on swap in * program * functions * strings * variable_names * inherit * argument_types * type_start */ int locate_out P1(struct program *, prog) { char *p = 0; /* keep cc happy */ if (!prog) return 0; #ifdef DEBUG if (d_flag > 1) { debug_message("locate_out: %lX %lX %lX %lX %lX %lX %lX\n", prog->p.i.program, prog->p.i.functions, prog->p.i.strings, prog->p.i.variable_names, prog->p.i.inherit, prog->p.i.argument_types, prog->p.i.type_start); } #endif prog->p.i.program = &p[prog->p.i.program - (char *) prog]; prog->p.i.functions = (struct function *) & p[(char *) prog->p.i.functions - (char *) prog]; prog->p.i.strings = (char **) &p[(char *) prog->p.i.strings - (char *) prog]; prog->p.i.variable_names = (struct variable *) & p[(char *) prog->p.i.variable_names - (char *) prog]; prog->p.i.inherit = (struct inherit *) & p[(char *) prog->p.i.inherit - (char *) prog]; if (prog->p.i.type_start) { prog->p.i.argument_types = (unsigned short *) &p[(char *) prog->p.i.argument_types - (char *) prog]; prog->p.i.type_start = (unsigned short *) &p[(char *) prog->p.i.type_start - (char *) prog]; } return 1; } /* * marion - relocate pointers after swap in * program * functions * strings * variable_names * inherit * argument_types * type_start */ int locate_in P1(struct program *, prog) { char *p = (char *) prog; if (!prog) return 0; prog->p.i.program = &p[prog->p.i.program - (char *) 0]; prog->p.i.functions = (struct function *) & p[(char *) prog->p.i.functions - (char *) 0]; prog->p.i.strings = (char **) &p[(char *) prog->p.i.strings - (char *) 0]; prog->p.i.variable_names = (struct variable *) & p[(char *) prog->p.i.variable_names - (char *) 0]; prog->p.i.inherit = (struct inherit *) & p[(char *) prog->p.i.inherit - (char *) 0]; if (prog->p.i.type_start) { prog->p.i.argument_types = (unsigned short *) &p[(char *) prog->p.i.argument_types - (char *) 0]; prog->p.i.type_start = (unsigned short *) &p[(char *) prog->p.i.type_start - (char *) 0]; } #ifdef DEBUG if (d_flag > 1) { debug_message("locate_in: %lX %lX %lX %lX %lX %lX\n", prog->p.i.program, prog->p.i.functions, prog->p.i.strings, prog->p.i.variable_names, prog->p.i.inherit, prog->p.i.argument_types, prog->p.i.type_start); } #endif return 1; } /* * Swap out an object. Only the program is swapped, not the 'struct object'. * * marion - the swap seems to corrupt the function table */ int swap P1(struct object *, ob) { /* the simuls[] table uses pointers to the functions so the simul_efun * program cannot be relocated. locate_in() could be changed to * correct this or simuls[] could use offsets, but it doesn't seem * worth it just to get the simul_efun object to swap. Maybe later. */ if (ob == simul_efun_ob) return 0; if (ob->flags & O_DESTRUCTED) return 0; #ifdef DEBUG if (d_flag > 1) { /* marion */ debug_message("Swap object %s (ref %d)\n", ob->name, ob->ref); } #endif if (ob->prog->p.i.line_info) swap_line_numbers(ob->prog); /* not always done before we get here */ if ((ob->flags & O_HEART_BEAT) || (ob->flags & O_CLONE)) { #ifdef DEBUG if (d_flag > 1) { debug_message(" object not swapped - heart beat or cloned.\n"); } #endif return 0; } if (ob->prog->p.i.ref > 1 || ob->interactive) { #ifdef DEBUG if (d_flag > 1) { debug_message(" object not swapped - inherited or interactive.\n"); } #endif return 0; } if (ob->prog->p.i.func_ref > 0) { #ifdef DEBUG if (d_flag > 1) { debug_message(" object not swapped - referenced by functions.\n"); } #endif return 0; } locate_out(ob->prog); /* relocate the internal pointers */ if (swap_out((char *) ob->prog, ob->prog->p.i.total_size, (int *) &ob->swap_num)) { num_swapped++; free_prog(ob->prog, 0); /* Do not free the strings */ ob->prog = 0; ob->flags |= O_SWAPPED; return 1; } else { locate_in(ob->prog); return 0; } } void load_ob_from_swap P1(struct object *, ob) { if (ob->swap_num == -1) fatal("Loading not swapped object.\n"); #ifdef DEBUG if (d_flag > 1) { /* marion */ debug_message("Unswap object %s (ref %d)\n", ob->name, ob->ref); } #endif swap_in((char **) &ob->prog, ob->swap_num); SET_TAG(ob->prog, TAG_PROGRAM); /* * to be relocated: program functions strings variable_names inherit * argument_types type_start */ locate_in(ob->prog); /* relocate the internal pointers */ /* The reference count will already be 1 ! */ ob->flags &= ~O_SWAPPED; num_swapped--; total_prog_block_size += ob->prog->p.i.total_size; total_num_prog_blocks += 1; } /* * Swap out line number information. */ int swap_line_numbers P1(struct program *, prog) { int size; if (!prog || !prog->p.i.line_info) return 0; #ifdef DEBUG if (d_flag > 1) { debug_message("Swap line numbers for %s\n", prog->name); } #endif size = prog->p.i.file_info[0]; if (swap_out((char *) prog->p.i.file_info, size, &prog->p.i.line_swap_index)) { line_num_bytes_swapped += size; FREE(prog->p.i.file_info); prog->p.i.file_info = 0; prog->p.i.line_info = 0; return 1; } return 0; } /* * Reload line number information from swap. */ void load_line_numbers P1(struct program *, prog) { int size; if (prog->p.i.line_info) return; #ifdef DEBUG if (d_flag > 1) { debug_message("Unswap line numbers for %s\n", prog->name); } #endif size = swap_in((char **) &prog->p.i.file_info, prog->p.i.line_swap_index); SET_TAG(prog->p.i.file_info, TAG_LINENUMBERS); prog->p.i.line_info = (unsigned char *)&prog->p.i.file_info[prog->p.i.file_info[1]]; line_num_bytes_swapped -= size; } /** ** Misc. routines. **/ /* * Remove the swap space associated with this object. */ void remove_swap_file P1(struct object *, ob) { if (!ob) return; /* may be swapped out, so swap in to get size, update stats, etc */ if (ob->flags & O_SWAPPED) load_ob_from_swap(ob); if (ob->prog) free_swap(ob->swap_num, ob->prog->p.i.total_size); ob->swap_num = -1; } /* * Same as above, but to remove line_number swap space. */ void remove_line_swap P1(struct program *, prog) { if (!prog->p.i.line_info) load_line_numbers(prog); if (prog->p.i.line_swap_index != -1 && prog->p.i.line_info) free_swap(prog->p.i.line_swap_index, prog->p.i.file_info[0]); prog->p.i.line_swap_index = -1; } void print_swap_stats() { extern int errno; int size, cnt, end; struct sw_block *m; add_message("Swap information:\n"); add_message("-------------------------\n"); add_vmessage("Progs swapped: %10lu\n", num_swapped); add_vmessage("Linenum bytes: %10lu\n", line_num_bytes_swapped); add_vmessage("Total bytes swapped: %10lu\n", total_bytes_swapped); if (!swap_file) { add_message("No swap file\n"); return; } size = cnt = 0; for (m = swap_free; m; size += m->length, cnt++, m = m->next); if (fseek(swap_file, 0L, 2) == -1) fatal("Couldn't seek end of the swap file, errno %d\n", errno); end = ftell(swap_file) - last_data; if (end) { size += end; cnt++; } add_vmessage("Freed bytes: %10lu (%d chunks)\n", size, cnt); } /* * This one is called at shutdown. Remove the swap file. */ void unlink_swap_file() { if (swap_file == 0) return; #ifndef MSDOS unlink(file_name); fclose(swap_file); #else fclose(swap_file); unlink(file_name); #endif }
{ "content_hash": "679b5da919d360cc31fc5c9497dfb320", "timestamp": "", "source": "github", "line_count": 538, "max_line_length": 88, "avg_line_length": 25.2546468401487, "alnum_prop": 0.5941708986531243, "repo_name": "holtsoftware/potential-octo-wallhack", "id": "0e99a56ba61c0b87d6f5036f7cbda1b82952c472", "size": "13587", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "School C++/other/lpc/swap.c", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "25942" }, { "name": "C++", "bytes": "56630" } ], "symlink_target": "" }
package com.twitter.util.registry import scala.util.control.NoStackTrace import org.scalatest.funsuite.AnyFunSuite class FormatterTest extends AnyFunSuite { test("asMap generates reasonable Maps") { val registry = new SimpleRegistry registry.put(Seq("foo", "bar"), "baz") registry.put(Seq("foo", "qux"), "quux") val actual = Formatter.asMap(registry) val expected = Map("registry" -> Map("foo" -> Map("bar" -> "baz", "qux" -> "quux"))) assert(actual == expected) } test("add should handle empties") { assert( Formatter.add(Map.empty, Seq.empty, "big") == Map(Formatter.Eponymous -> "big") ) } test("add should handle putting an entry in an existing map if nothing's there") { assert( Formatter.add(Map.empty, Seq("it's"), "big") == Map("it's" -> "big") ) } test("add should handle putting recursive entries in an existing map if nothing's there") { val actual = Formatter.add(Map.empty, Seq("it's", "very"), "big") val expected = Map("it's" -> Map("very" -> "big")) assert(actual == expected) } test("add should handle colliding prefixes") { val actual = Formatter.add(Map("it's" -> Map("not" -> "small")), Seq("it's", "very"), "big") val expected = Map("it's" -> Map("very" -> "big", "not" -> "small")) assert(actual == expected) } test("add should handle colliding prefixes that are shorter") { val actual = Formatter.add(Map("it's" -> "small"), Seq("it's", "very"), "big") val expected = Map("it's" -> Map("very" -> "big", Formatter.Eponymous -> "small")) assert(actual == expected) } test("add should bail on collisions") { val actual = intercept[Exception with NoStackTrace] { Formatter.add(Map("it's" -> "small"), Seq("it's"), "big") } val expected = Formatter.Collision assert(actual == expected) } test("add should bail on finding a weird type") { val actual = intercept[Exception with NoStackTrace] { Formatter.add(Map("it's" -> new Object), Seq("it's"), "big") } val expected = Formatter.InvalidType assert(actual == expected) } test("makeMap should make a map") { val seq = Seq("my", "spoon", "is", "too") val value = "big" val actual = Formatter.makeMap(seq, value) val expected = Map("my" -> Map("spoon" -> Map("is" -> Map("too" -> "big")))) assert(actual == expected) } test("makeMap should fail on empties") { val seq = Seq.empty val value = "big" val actual = intercept[Exception with NoStackTrace] { Formatter.makeMap(seq, value) } assert(actual == Formatter.Empty) } }
{ "content_hash": "84f35ac46247b82ef0760e1c4bbdc981", "timestamp": "", "source": "github", "line_count": 80, "max_line_length": 96, "avg_line_length": 32.725, "alnum_prop": 0.6168831168831169, "repo_name": "twitter/util", "id": "05e044d18b82595fffd05bdc4d7449eaea4a1a32", "size": "2618", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "util-registry/src/test/scala/com/twitter/util/registry/FormatterTest.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "3006" }, { "name": "Java", "bytes": "176316" }, { "name": "Makefile", "bytes": "396" }, { "name": "Mako", "bytes": "3465" }, { "name": "Scala", "bytes": "3032537" }, { "name": "Shell", "bytes": "2167" }, { "name": "Starlark", "bytes": "87606" } ], "symlink_target": "" }
/* * Custom Type Definitions * When including 3rd party modules you also need to include the type definition for the module * if they don't provide one within the module. You can try to install it with typings typings install node --save * If you can't find the type definition in the registry we can make an ambient definition in * this file for now. For example declare module "my-module" { export function doesSomething(value: string): string; } * * If you're prototying and you will fix the types later you can also declare it as type any * declare var assert: any; * * If you're importing a module that uses Node.js modules which are CommonJS you need to import as * import * as _ from 'lodash' * You can include your type definitions in this file until you create one for the typings registry * see https://github.com/typings/registry * */ // Extending mapbox typings declare namespace mapboxgl { export interface Map { addControl(control: Control, position?:string): this; } } declare module 'd3-sankey' { export interface Sankey{ link():any; nodes(any):any; nodeWidth(any):any; nodePadding(any):any; layout(any):any; size(any):any; relayout():any; } export function sankey():Sankey; } // Extra variables that live on Global that will be replaced by webpack DefinePlugin declare var ENV: string; declare var HMR: boolean; interface GlobalEnvironment { ENV; HMR; } interface WebpackModule { hot: { data?: any, idle: any, accept(dependencies?: string | string[], callback?: (updatedDependencies?: any) => void): void; decline(dependencies?: string | string[]): void; dispose(callback?: (data?: any) => void): void; addDisposeHandler(callback?: (data?: any) => void): void; removeDisposeHandler(callback?: (data?: any) => void): void; check(autoApply?: any, callback?: (err?: Error, outdatedModules?: any[]) => void): void; apply(options?: any, callback?: (err?: Error, outdatedModules?: any[]) => void): void; status(callback?: (status?: string) => void): void | string; removeStatusHandler(callback?: (status?: string) => void): void; }; } interface WebpackRequire { context(file: string, flag?: boolean, exp?: RegExp): any; } // Extend typings interface NodeRequire extends WebpackRequire {} interface NodeModule extends WebpackModule {} interface Global extends GlobalEnvironment {}
{ "content_hash": "f8d8e56a17a22e9419a83d506c74b215", "timestamp": "", "source": "github", "line_count": 75, "max_line_length": 99, "avg_line_length": 32.22666666666667, "alnum_prop": 0.7012825817128672, "repo_name": "23deg/23", "id": "0ca98dc7bb7fcceb8b8ea73ed5546ab55afdc0af", "size": "2417", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/typings.d.ts", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "54343" }, { "name": "HTML", "bytes": "49485" }, { "name": "Protocol Buffer", "bytes": "544" }, { "name": "TypeScript", "bytes": "156648" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_171) on Mon Aug 06 14:29:36 PDT 2018 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Package com.jk.util.validation.builtin (com.jalalkiswani:jk-util 1.0.1-SNAPSHOT API)</title> <meta name="date" content="2018-08-06"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Package com.jk.util.validation.builtin (com.jalalkiswani:jk-util 1.0.1-SNAPSHOT API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li class="navBarCell1Rev">Use</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/jk/util/validation/builtin/package-use.html" target="_top">Frames</a></li> <li><a href="package-use.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 title="Uses of Package com.jk.util.validation.builtin" class="title">Uses of Package<br>com.jk.util.validation.builtin</h1> </div> <div class="contentContainer"> <ul class="blockList"> <li class="blockList"> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../com/jk/util/validation/builtin/package-summary.html">com.jk.util.validation.builtin</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#com.jk.util.validation.builtin">com.jk.util.validation.builtin</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"><a name="com.jk.util.validation.builtin"> <!-- --> </a> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation"> <caption><span>Classes in <a href="../../../../../com/jk/util/validation/builtin/package-summary.html">com.jk.util.validation.builtin</a> used by <a href="../../../../../com/jk/util/validation/builtin/package-summary.html">com.jk.util.validation.builtin</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colOne"><a href="../../../../../com/jk/util/validation/builtin/class-use/FSValidators.html#com.jk.util.validation.builtin">FSValidators</a> <div class="block">An enumeration of validator factories for commonly needed forms of validation such as non-empty strings, valid file names and URLs and so forth.</div> </td> </tr> </tbody> </table> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li class="navBarCell1Rev">Use</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/jk/util/validation/builtin/package-use.html" target="_top">Frames</a></li> <li><a href="package-use.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2018 <a href="http://www.jalalkiswani.com">Jalal Kiswani</a>. All rights reserved.</small></p> </body> </html>
{ "content_hash": "6697bd685befb64c631ea68bdb7d428c", "timestamp": "", "source": "github", "line_count": 162, "max_line_length": 308, "avg_line_length": 38.01851851851852, "alnum_prop": 0.6171456405260595, "repo_name": "kiswanij/jk-util", "id": "506521ac95f3acfd1047b1a823d801a4c20fbba2", "size": "6159", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/apidocs/com/jk/util/validation/builtin/package-use.html", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "579106" } ], "symlink_target": "" }
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences Partial Public Class FindReferencesTests <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestAlias1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using $$D = System.[|DateTime|]; partial class C { [|D|] date; void Goo() { } } </Document> <Document> partial class C { // Should not be found here. D date; } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestAlias2(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using $$D = [|C|]; partial class {|Definition:C|} { [|D|] date; void Goo() { } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestAlias3(host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using $$D = [|N|]; namespace {|Definition:[|N|]|} { partial class C { [|D|].C date; [|N|].C date; void Goo() { } } } </Document> </Project> </Workspace> Await TestAPI(input, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestNamedType_CSharpAttributeEndingWithAttributeThroughAlias(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using GooAttribute = System.[|ObsoleteAttribute|]; [[|GooAttribute|]] class C{ } [[|Goo|]] class D{ } [[|GooAttribute|]()] class B{ } [[|$$Goo|]()] // Invoke FAR here on Goo class Program { static void Main(string[] args) {} } ]]> </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> <WorkItem(667962, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/667962")> Public Async Function TestMultipleAliasSymbols(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; using XAttribute = NS.[|XAttribute|]; using $$YAttribute = NS.[|XAttribute|]; using YAttributeAttribute = NS.[|XAttribute|]; [[|Y|]] [[|YAttribute|]] [[|@YAttribute|]] class Test { } namespace NS { [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class {|Definition:XAttribute|} : Attribute { } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> <WorkItem(667962, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/667962")> Public Async Function TestMultipleAliasSymbols2(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; using XAttribute = NS.[|XAttribute|]; using $$YAttribute = NS.[|XAttribute|]; [[|Y|]] [[|YAttribute|]] [[|@YAttribute|]] class Test { } namespace NS { [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class {|Definition:XAttribute|} : Attribute { } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestNamedType_VBAttributeEndingWithAttributeThroughAlias(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ Imports GooAttribute = System.[|ObsoleteAttribute|]; <[|GooAttribute|]> Class C End Class <[|Goo|]> Class D End Class <[|GooAttribute|]()> Class B End Class <[|$$Goo|]()> ' Invoke FAR here on Goo Class Program Public Shared Sub Main() End Function End Class ]]> </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestAliasReferenceInGlobalSuppression(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using $$AliasToC = N.[|C|]; [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("RuleCategory", "RuleId", Scope = "member", Target = "~M:N.[|C|].Goo")] namespace N { class {|Definition:C|} { void Goo() { } } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestAliasReferenceInGlobalSuppression_WithAttributeSuffix(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using $$AliasToC = N.[|C|]; [assembly: System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("RuleCategory", "RuleId", Scope = "member", Target = "~M:N.[|C|].Goo")] namespace N { class {|Definition:C|} { void Goo() { } } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestAliasReferenceInGlobalSuppression_WithUsing(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using $$AliasToC = N.[|C|]; using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage("RuleCategory", "RuleId", Scope = "member", Target = "~M:N.[|C|].Goo")] namespace N { class {|Definition:C|} { void Goo() { } } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestAliasReferenceInGlobalSuppression_WithUsing_WithAttributeSuffix(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using $$AliasToC = N.[|C|]; using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessageAttribute("RuleCategory", "RuleId", Scope = "member", Target = "~M:N.[|C|].Goo")] namespace N { class {|Definition:C|} { void Goo() { } } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(55894, "https://github.com/dotnet/roslyn/issues/55894")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestGlobalAlias1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> global using $$D = System.[|DateTime|]; partial class C { [|D|] date; void Goo() { } } </Document> <Document> partial class C { [|D|] date; } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(55894, "https://github.com/dotnet/roslyn/issues/55894")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestGlobalAlias2(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> global using $$D = System.[|DateTime|]; </Document> <Document> partial class C { [|D|] date; } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(55894, "https://github.com/dotnet/roslyn/issues/55894")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestGlobalAlias3(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> global using $$DAttribute = System.[|CLSCompliantAttribute|]; </Document> <Document> [[|DAttribute|]] partial class C { } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(55894, "https://github.com/dotnet/roslyn/issues/55894")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestGlobalAlias4(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> global using $$DAttribute = System.[|CLSCompliantAttribute|]; </Document> <Document> [[|DAttribute|](false)] partial class C { } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(55894, "https://github.com/dotnet/roslyn/issues/55894")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestGlobalAlias5(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> global using $$DAttribute = System.[|CLSCompliantAttribute|]; </Document> <Document> [[|D|]] partial class D { } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(55894, "https://github.com/dotnet/roslyn/issues/55894")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestGlobalAlias6(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> global using $$DAttribute = System.[|CLSCompliantAttribute|]; </Document> <Document> [[|D|](false)] partial class D { } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(55894, "https://github.com/dotnet/roslyn/issues/55894")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestGlobalAlias7(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> global using $$D = System.[|DateTime|]; </Document> <Document> namespace Outer { using D2 = [|D|]; partial class C { [|D2|] date; } } </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function End Class End Namespace
{ "content_hash": "8240e685f484e62370bef4f0bde338b8", "timestamp": "", "source": "github", "line_count": 462, "max_line_length": 141, "avg_line_length": 29.01298701298701, "alnum_prop": 0.5980304386750224, "repo_name": "sharwell/roslyn", "id": "1776e2d32a990d8a873d7e165b85eee085a273e0", "size": "13406", "binary": false, "copies": "4", "ref": "refs/heads/main", "path": "src/EditorFeatures/Test2/FindReferences/FindReferencesTests.AliasSymbols.vb", "mode": "33188", "license": "mit", "language": [ { "name": "1C Enterprise", "bytes": "257760" }, { "name": "Batchfile", "bytes": "8025" }, { "name": "C#", "bytes": "141191940" }, { "name": "C++", "bytes": "5602" }, { "name": "CMake", "bytes": "9153" }, { "name": "Dockerfile", "bytes": "2450" }, { "name": "F#", "bytes": "549" }, { "name": "PowerShell", "bytes": "243533" }, { "name": "Shell", "bytes": "94467" }, { "name": "Visual Basic .NET", "bytes": "71837994" } ], "symlink_target": "" }
#include "tensorflow/tsl/profiler/utils/group_events.h" #include <algorithm> #include <cstdint> #include <functional> #include <iterator> #include <map> #include <memory> #include <optional> #include <queue> #include <string> #include <utility> #include <vector> #include "absl/algorithm/container.h" #include "absl/container/flat_hash_map.h" #include "absl/strings/str_cat.h" #include "tensorflow/tsl/lib/gtl/map_util.h" #include "tensorflow/tsl/platform/types.h" #include "tensorflow/tsl/profiler/lib/context_types.h" #include "tensorflow/tsl/profiler/utils/tf_xplane_visitor.h" #include "tensorflow/tsl/profiler/utils/xplane_builder.h" #include "tensorflow/tsl/profiler/utils/xplane_schema.h" #include "tensorflow/tsl/profiler/utils/xplane_utils.h" #include "tensorflow/tsl/profiler/utils/xplane_visitor.h" namespace tsl { namespace profiler { namespace { // Creates stat metadata for the stats which may be added by grouping. void CreateStatMetadata(XPlane* plane) { XPlaneBuilder builder(plane); builder.GetOrCreateStatMetadata(GetStatTypeStr(StatType::kGroupId)); builder.GetOrCreateStatMetadata(GetStatTypeStr(StatType::kStepName)); builder.GetOrCreateStatMetadata(GetStatTypeStr(StatType::kIsEager)); } // Returns event type if it is a KernelLaunch or KernelExecute event. std::optional<int64_t> GetKernelEventType(bool is_host_plane, const XEventVisitor& event) { if (event.GetStat(StatType::kCorrelationId).has_value()) { return is_host_plane ? HostEventType::kKernelLaunch : HostEventType::kKernelExecute; } return std::nullopt; } int64_t GetEventType(bool is_host_plane, const XEventVisitor& event) { if (std::optional<int64_t> event_type = event.Type()) { return *event_type; } else if (std::optional<int64_t> kernel_event_type = GetKernelEventType(is_host_plane, event)) { // KernelLaunch and KernelExecute event types are not supported by // XPlaneVisitor and should be checked separately. // TODO(b/148346217): Make XPlaneVisitor support KernelLaunch and // KernelExecute event types. return *kernel_event_type; } else { return HostEventType::kUnknownHostEventType; } } bool IsLegacyProducerEvent(const XEventVisitor& event) { static const auto* const kProducerEvents = new absl::flat_hash_set<int64_t>{ HostEventType::kTraceContext, HostEventType::kFunctionRun, HostEventType::kSessionRun, HostEventType::kRunGraph}; return event.Type().has_value() && kProducerEvents->contains(*event.Type()); } bool IsLegacyConsumerEvent(const XEventVisitor& event) { static const auto* const kConsumerEvents = new absl::flat_hash_set<int64_t>{ HostEventType::kExecutorStateProcess, HostEventType::kExecutorDoneCallback, HostEventType::kRunGraphDone}; return event.Type().has_value() && kConsumerEvents->contains(*event.Type()); } bool IsLegacyRootEvent(const XEventVisitor& event) { static const auto* const kRootEvents = new absl::flat_hash_set<int64_t>{ HostEventType::kTraceContext, HostEventType::kFunctionRun, HostEventType::kSessionRun, HostEventType::kRunGraph}; return event.Type().has_value() && kRootEvents->contains(*event.Type()); } // Stats used in ConnectIntraThread. struct GroupingEventStats { explicit GroupingEventStats(const XEventVisitor& event); std::optional<int> producer_type; std::optional<uint64_t> producer_id; std::optional<int> consumer_type; std::optional<uint64_t> consumer_id; std::optional<int> root_level; bool is_async = false; }; GroupingEventStats::GroupingEventStats(const XEventVisitor& event) { std::optional<int64_t> step_id; event.ForEachStat([&](const XStatVisitor& stat) { if (!stat.Type().has_value()) return; switch (*stat.Type()) { case StatType::kProducerType: producer_type = stat.IntValue(); break; case StatType::kProducerId: producer_id = stat.IntOrUintValue(); break; case StatType::kConsumerType: consumer_type = stat.IntValue(); break; case StatType::kConsumerId: consumer_id = stat.IntOrUintValue(); break; case StatType::kIsRoot: root_level = stat.IntValue(); break; case StatType::kIsAsync: is_async = stat.BoolValue(); break; case StatType::kStepId: step_id = stat.IntValue(); break; default: break; } }); if (!producer_type.has_value() || !producer_id.has_value()) { if (step_id.has_value() && IsLegacyProducerEvent(event)) { producer_type = static_cast<int>(ContextType::kTfExecutor); producer_id = *step_id; } } if (!consumer_type.has_value() || !consumer_id.has_value()) { if (step_id.has_value() && IsLegacyConsumerEvent(event)) { consumer_type = static_cast<int>(ContextType::kTfExecutor); consumer_id = *step_id; } } if (!root_level.has_value() && IsLegacyRootEvent(event)) { root_level = 1; } } void SetContextGroup(const GroupingEventStats& stats, EventNode* event, ContextGroupMap* context_groups) { if (stats.producer_type.has_value() && stats.producer_id.has_value()) { ((*context_groups)[*stats.producer_type][*stats.producer_id]) .producers.push_back(event); } if (stats.consumer_type.has_value() && stats.consumer_id.has_value()) { ((*context_groups)[*stats.consumer_type][*stats.consumer_id]) .consumers.push_back(event); } } void ConnectContextGroups(const ContextGroupMap& context_groups) { for (auto& type_id_group : context_groups) { for (auto& id_group : type_id_group.second) { const ContextGroup& group = id_group.second; for (EventNode* parent : group.producers) { for (EventNode* child : group.consumers) { parent->AddChild(child); } } } } } bool HasFunctionRun(EventNode* event_node) { for (EventNode* child : event_node->GetChildren()) { if (child->GetEventVisitor().Type() == HostEventType::kFunctionRun) { return true; } } return false; } bool IsImplicitRootEvent(const XEventVisitor& event) { static const auto* const kImplicitRootEvents = new absl::flat_hash_set<int64_t>{ HostEventType::kFunctionRun, HostEventType::kSessionRun, HostEventType::kRunGraph, HostEventType::kExecutorStateProcess}; return event.Type().has_value() && kImplicitRootEvents->contains(*event.Type()); } void ProcessRootEvent(int64_t group_id, EventNode* root_event, GroupMetadataMap* group_metadata_map) { root_event->PropagateGroupId(group_id, group_metadata_map); std::string group_name = root_event->GetGroupName(); // TODO(b/160255693): Change the event name instead. if (!IsImplicitRootEvent(root_event->GetEventVisitor())) { // Add the `step_name` stat for the user-defined root events only. When an // XEvent is converted to a trace event, the trace event name is set to the // `step_name` stat's value if present. root_event->AddStepName(group_name); } (*group_metadata_map)[group_id].name = std::move(group_name); } using Comparator = std::function<bool(const EventNode*)>; const EventNode* FindParentWithComparator(const Comparator& comparator, const EventNode* node, bool include_self) { std::queue<const EventNode*> nodes; absl::flat_hash_set<const EventNode*> seen = {node}; if (include_self) { nodes.push(node); } else { for (const EventNode* parent : node->GetParents()) { nodes.push(parent); seen.insert(parent); } } while (!nodes.empty()) { const EventNode* node = nodes.front(); nodes.pop(); if (comparator(node)) return node; for (const EventNode* parent : node->GetParents()) { if (seen.contains(parent)) continue; nodes.push(parent); seen.insert(parent); } } return nullptr; } bool IsIteratorEventType(absl::optional<int64_t> event_type) { return event_type == HostEventType::kIterator || event_type == HostEventType::kDeviceInputPipelineSecondIterator; } } // namespace // Returns true if TF's loop ops exist in the given XSpace's metadata. bool CheckLoopOp(const XSpace& space) { for (const XPlane& plane : space.planes()) { for (const auto& event_metadata : plane.event_metadata()) { absl::optional<int64_t> event_type = FindHostEventType(event_metadata.second.name()); if (!event_type.has_value()) continue; switch (*event_type) { case HostEventType::kWhileOpEvalCond: case HostEventType::kWhileOpStartBody: case HostEventType::kForOp: case HostEventType::kParallelForOp: case HostEventType::kForeverOp: return true; default: break; } } } return false; } absl::optional<XStatVisitor> EventNode::GetContextStat( int64_t stat_type) const { std::queue<const EventNode*> nodes; absl::flat_hash_set<const EventNode*> seen = {this}; nodes.push(this); while (!nodes.empty()) { const EventNode* node = nodes.front(); nodes.pop(); if (absl::optional<XStatVisitor> stat = node->visitor_.GetStat(stat_type)) { return stat; } for (const EventNode* parent : node->GetParents()) { if (seen.contains(parent)) continue; nodes.push(parent); seen.insert(parent); } } return absl::nullopt; } std::string EventNode::GetGroupName() const { std::string name; if (absl::optional<XStatVisitor> stat = GetContextStat(StatType::kGraphType)) { absl::StrAppend(&name, stat->StrOrRefValue(), " "); } else if (!(IsImplicitRootEvent(visitor_))) { absl::StrAppend(&name, GetEventVisitor().Name(), " "); } int64_t step_num = group_id_.value_or(0); if (absl::optional<XStatVisitor> stat = GetContextStat(StatType::kIterNum)) { step_num = stat->IntValue(); } else if (absl::optional<XStatVisitor> stat = GetContextStat(StatType::kStepNum)) { step_num = stat->IntValue(); } absl::StrAppend(&name, step_num); return name; } XStat* EventNode::FindOrAddStatByType(int64_t stat_type) { const XPlaneVisitor& plane = visitor_.Plane(); const XStatMetadata* stat_metadata = plane.GetStatMetadataByType(stat_type); DCHECK(stat_metadata != nullptr); auto* raw_event = const_cast<XEvent*>(&visitor_.RawEvent()); // NOLINT return FindOrAddMutableStat(*stat_metadata, raw_event); } void EventNode::SetGroupId(int64_t group_id) { group_id_ = group_id; FindOrAddStatByType(StatType::kGroupId)->set_int64_value(group_id); } void EventNode::PropagateGroupId(int64_t group_id, GroupMetadataMap* group_metadata_map) { std::queue<EventNode*> nodes; absl::flat_hash_set<EventNode*> seen = {this}; nodes.push(this); while (!nodes.empty()) { EventNode* node = nodes.front(); nodes.pop(); absl::optional<int64_t> node_group_id = node->GetGroupId(); if (node_group_id.has_value()) { if (*node_group_id != group_id) { (*group_metadata_map)[group_id].children.insert(*node_group_id); (*group_metadata_map)[*node_group_id].parents.insert(group_id); } } else { node->SetGroupId(group_id); for (EventNode* child : node->GetChildren()) { if (seen.contains(child)) continue; nodes.push(child); seen.insert(child); } } } } void EventNode::AddStepName(absl::string_view step_name) { FindOrAddStatByType(StatType::kStepName) ->set_str_value(step_name.data(), step_name.size()); } void EventNode::SetIsEager(bool is_eager) { FindOrAddStatByType(StatType::kIsEager)->set_int64_value(is_eager ? 1 : 0); } bool EventNode::IsCompiledFunc() const { auto is_func = visitor_.GetStat(StatType::kIsFunc); return !is_func || is_func->IntValue(); } bool EventNode::IsEager() const { /* Both eager mode (op-by-op) and non-eager mode (eager functions) of eager * executions are unified and forward to TF1 executor now. Therefore we will * check following conditions: */ const EventNode* node = FindParent(HostEventType::kEagerKernelExecute); if (node == nullptr) { // if current op is NOT scheduled under "EagerExecute", likely this is // from TF1, therefore not eager. return false; } // Otherwise, it is eager mode execution of an operation if and only if it is // not a eager mode execution of a compiled function. return !node->IsCompiledFunc(); } const EventNode* EventNode::FindParent(int64_t event_type) const { return FindParentWithComparator( [event_type](const EventNode* node) { return node->GetEventVisitor().Type() == event_type; }, this, /*include_self=*/true); } void EventForest::ConnectIntraThread(XPlane* plane, XPlaneVisitor* visitor, ContextGroupMap* context_groups) { // TODO(b/149095099): avoid string comparison. bool is_host_plane = (visitor->Name() == kHostThreadsPlaneName); for (auto& line : *plane->mutable_lines()) { std::vector<EventNode*> parent_nodes; for (auto& event : *line.mutable_events()) { XEventVisitor event_visitor(visitor, &line, &event); int64_t event_type = GetEventType(is_host_plane, event_visitor); EventNode* cur_node = &event_node_map_[event_type].emplace_back(std::move(event_visitor)); GroupingEventStats stats(cur_node->GetEventVisitor()); if (stats.root_level.has_value()) { cur_node->SetRootLevel(*stats.root_level); } // Update `context_groups` for `ConnectInterThread`. SetContextGroup(stats, cur_node, context_groups); // Async events are ignored when processing the nesting relationship. if (!stats.is_async) { while (!parent_nodes.empty()) { EventNode* parent_node = parent_nodes.back(); if (parent_node->GetEventVisitor().GetTimespan().Includes( cur_node->GetEventVisitor().GetTimespan())) { parent_node->AddChild(cur_node); break; } else { parent_nodes.pop_back(); } } parent_nodes.push_back(cur_node); } } } } void EventForest::ConnectInterThread( const std::vector<InterThreadConnectInfo>& connect_info_list) { for (const auto& connect_info : connect_info_list) { absl::flat_hash_map<std::vector<uint64>, EventNode*> connect_map; const std::vector<int64_t>& parent_stat_types = connect_info.parent_stat_types; const std::vector<int64_t>* child_stat_types = &connect_info.child_stat_types; if (child_stat_types->empty()) { child_stat_types = &parent_stat_types; } if (auto parent_event_node_list = gtl::FindOrNull(event_node_map_, connect_info.parent_event_type)) { for (EventNode& parent_event_node : *parent_event_node_list) { std::vector<uint64> stats; for (auto stat_type : parent_stat_types) { absl::optional<XStatVisitor> stat = parent_event_node.GetContextStat(stat_type); if (!stat) break; stats.push_back(stat->IntOrUintValue()); } if (stats.size() == parent_stat_types.size()) { connect_map[stats] = &parent_event_node; } } } if (auto child_event_node_list = gtl::FindOrNull(event_node_map_, connect_info.child_event_type)) { for (EventNode& child_event_node : *child_event_node_list) { std::vector<uint64> stats; for (auto stat_type : *child_stat_types) { absl::optional<XStatVisitor> stat = child_event_node.GetContextStat(stat_type); if (!stat) break; stats.push_back(stat->IntOrUintValue()); } if (stats.size() == child_stat_types->size()) { if (auto parent_event_node = gtl::FindPtrOrNull(connect_map, stats)) { parent_event_node->AddChild(&child_event_node); } } } } } } // Returns whether a root event needs grouping. bool RootNeedsGrouping(const EventNode* root) { // No grouping is needed if it is already grouped. if (root->GetGroupId().has_value()) return false; // If there is a parent node with the same root level, skip grouping at <root> // and later apply grouping at the parent node. // If there is a parent node with a different root level, apply grouping at // <root>, and later apply grouping at the parent node. Root events with // different levels are grouped separately. const EventNode* root_parent = FindParentWithComparator( [root](const EventNode* parent) { return parent->RootLevel() == root->RootLevel(); }, root, /*include_self=*/false); return root_parent == nullptr; } // Sorts root events based on root level and timestamp. void SortRootEventList(EventList* event_list) { absl::c_sort(*event_list, [](const EventNode* e1, const EventNode* e2) { // If two root events have the same root level, the root event with an // earlier timestamp will be processed first. Otherwise, the event with a // larger root level will be processed first. return e1->RootLevel() == e2->RootLevel() ? *e1 < *e2 : e1->RootLevel() > e2->RootLevel(); }); } void EventForest::CreateEventGroups() { int64_t group_id = 0; if (!tf_loop_root_events_.empty()) { for (EventNode* root_event : tf_loop_root_events_) { ProcessRootEvent(group_id++, root_event, &group_metadata_map_); } return; } // Iterate over all events and collect all root events. EventList root_events; for (auto& [event_type, events] : event_node_map_) { for (EventNode& event : events) { if (!event.RootLevel()) continue; absl::optional<XStatVisitor> step_id_stat = event.GetEventVisitor().GetStat(StatType::kStepId); // If this is a root event that associated with tf.data, skip. if (step_id_stat && tf_data_step_ids_.contains(step_id_stat->IntValue())) continue; root_events.push_back(&event); } } SortRootEventList(&root_events); for (EventNode* root_event : root_events) { if (RootNeedsGrouping(root_event)) { ProcessRootEvent(group_id++, root_event, &group_metadata_map_); } } } void EventForest::MarkEagerlyExecutedGpuKernels() { auto kernel_execute_event_node_list = gtl::FindOrNull(event_node_map_, HostEventType::kKernelExecute); if (!kernel_execute_event_node_list) return; for (EventNode& kernel_execute_event_node : *kernel_execute_event_node_list) { kernel_execute_event_node.SetIsEager(kernel_execute_event_node.IsEager()); } } void EventForest::MarkEagerlyExecutedCpuTfOps() { auto tf_op_run_event_node_list = gtl::FindOrNull(event_node_map_, HostEventType::kTfOpRun); if (!tf_op_run_event_node_list) return; for (EventNode& tf_op_run_event_node : *tf_op_run_event_node_list) { tf_op_run_event_node.SetIsEager(tf_op_run_event_node.IsEager()); } } void EventForest::ProcessTfDataSteps() { const int64_t tf_data_event_types[] = { HostEventType::kTfDataCapturedFunctionRun, HostEventType::kTfDataCapturedFunctionRunAsync, HostEventType::kTfDataCapturedFunctionRunInstantiated, HostEventType::kTfDataCapturedFunctionRunWithBorrowedArgs}; for (const int64_t tf_data_event_type : tf_data_event_types) { auto tf_data_events = gtl::FindOrNull(event_node_map_, tf_data_event_type); if (!tf_data_events) continue; for (const EventNode& tf_data_event : *tf_data_events) { absl::optional<XStatVisitor> step_id_stat = tf_data_event.GetEventVisitor().GetStat(StatType::kStepId); if (!step_id_stat) continue; tf_data_step_ids_.insert(step_id_stat->IntValue()); } } } void EventForest::ProcessTensorFlowLoop() { struct TensorFlowLoopIteration { EventNode* first_event = nullptr; std::vector<EventNode*> events; }; using TensorFlowLoop = absl::flat_hash_map<int64_t /*iter_num*/, TensorFlowLoopIteration>; absl::flat_hash_map<int64_t /*step_id*/, TensorFlowLoop> tf_loops; // Sort the TF executor events by TF function/session (step_id) and iter_num. auto executor_event_list = gtl::FindOrNull(event_node_map_, HostEventType::kExecutorStateProcess); if (!executor_event_list) return; for (EventNode& executor_event : *executor_event_list) { absl::optional<XStatVisitor> step_id_stat = executor_event.GetEventVisitor().GetStat(StatType::kStepId); absl::optional<XStatVisitor> iter_num_stat = executor_event.GetEventVisitor().GetStat(StatType::kIterNum); if (!step_id_stat || !iter_num_stat) continue; int64_t step_id = step_id_stat->IntValue(); // Skip tf.data events. if (tf_data_step_ids_.contains(step_id)) continue; TensorFlowLoop& tf_loop = tf_loops[step_id]; TensorFlowLoopIteration& iteration = tf_loop[iter_num_stat->IntValue()]; if (!iteration.first_event || executor_event < *iteration.first_event) { iteration.first_event = &executor_event; } iteration.events.push_back(&executor_event); } std::vector<const TensorFlowLoopIteration*> iters; for (const auto& step_id_and_tf_loop : tf_loops) { const TensorFlowLoop& tf_loop = step_id_and_tf_loop.second; // Filter out TF function/session without loops. if (tf_loop.size() == 1 && tf_loop.contains(0)) continue; for (const auto& iter_num_and_iter : tf_loop) { iters.push_back(&iter_num_and_iter.second); } } // Sort iterations based on timestamp of the first event in the iteration. absl::c_sort(iters, [](const auto& iter1, const auto& iter2) { return *iter1->first_event < *iter2->first_event; }); // Register the first event of each iteration as a root event. Also, add the // other events of the iteration as child to the root event. for (const TensorFlowLoopIteration* iter : iters) { EventNode* root_event = iter->first_event; tf_loop_root_events_.push_back(root_event); for (EventNode* event : iter->events) { if (event == root_event) continue; root_event->AddChild(event); } } } void EventForest::ProcessWorker() { auto eager_kernel_execute_event_list = gtl::FindOrNull(event_node_map_, HostEventType::kEagerKernelExecute); if (!eager_kernel_execute_event_list) return; // The last EagerKernelExecute with a FunctionRun child. EventNode* root_event = nullptr; for (EventNode& eager_kernel_execute_event : *eager_kernel_execute_event_list) { if (HasFunctionRun(&eager_kernel_execute_event)) { // A function op becomes a new root. root_event = &eager_kernel_execute_event; root_event->SetRootLevel(1); } else if (root_event) { // Add non-function eager ops as child. root_event->AddChild(&eager_kernel_execute_event); } } } void EventForest::AddPlane( const std::function<XPlaneVisitor(const XPlane*)> visitor_factory, XPlane* plane) { CreateStatMetadata(plane); planes_.push_back({plane, visitor_factory(plane)}); } void EventForest::AddSpace( const std::function<XPlaneVisitor(const XPlane*)> visitor_factory, XSpace* space) { for (XPlane& plane : *space->mutable_planes()) { AddPlane(visitor_factory, &plane); } } void EventForest::AddPlanes( const std::function<XPlaneVisitor(const XPlane*)> visitor_factory, const std::vector<XPlane*>& planes) { for (XPlane* plane : planes) { AddPlane(visitor_factory, plane); } } void EventForest::ConnectEvents( const std::vector<InterThreadConnectInfo>& connect_info_list) { ContextGroupMap context_groups; for (auto& plane_visitor : planes_) { ConnectIntraThread(plane_visitor.first, &plane_visitor.second, &context_groups); } ConnectInterThread(connect_info_list); ConnectContextGroups(context_groups); } void EventForest::ConnectTfDataEvents() { absl::flat_hash_map< std::pair<int64_t /*iterator_id*/, int64_t /*element_id*/>, std::vector<EventNode*>> produce_iterator_map; uint64 num_producers = 0; for (HostEventType event_type : {HostEventType::kPrefetchProduce, HostEventType::kParallelInterleaveProduce, HostEventType::kParallelMapProduce, HostEventType::kMapAndBatchProduce, HostEventType::kParseExampleProduce, HostEventType::kParallelBatchProduce}) { auto produce_event_list = gtl::FindOrNull(event_node_map_, event_type); if (!produce_event_list) continue; VLOG(1) << produce_event_list->size() << " " << GetHostEventTypeStr(event_type) << " events found."; for (EventNode& produce_event : *produce_event_list) { absl::optional<XStatVisitor> element_id = produce_event.GetEventVisitor().GetStat(StatType::kElementId); if (!element_id.has_value()) continue; for (EventNode* produce_iterator : produce_event.GetChildren()) { if (IsIteratorEventType(produce_iterator->GetEventVisitor().Type())) { absl::optional<XStatVisitor> iterator_id = produce_iterator->GetEventVisitor().GetStat(StatType::kParentId); if (!iterator_id.has_value()) break; produce_iterator_map[{iterator_id->IntValue(), element_id->IntValue()}] .push_back(produce_iterator); ++num_producers; break; } } } } VLOG(1) << num_producers << " producer iterators found."; uint64 num_matched = 0; for (HostEventType event_type : {HostEventType::kPrefetchConsume, HostEventType::kParallelInterleaveConsume, HostEventType::kParallelMapConsume, HostEventType::kMapAndBatchConsume, HostEventType::kParseExampleConsume, HostEventType::kParallelBatchConsume}) { auto consume_event_list = gtl::FindOrNull(event_node_map_, event_type); if (!consume_event_list) continue; VLOG(1) << consume_event_list->size() << " " << GetHostEventTypeStr(event_type) << " events found."; for (EventNode& consume_event : *consume_event_list) { absl::optional<XStatVisitor> element_id = consume_event.GetEventVisitor().GetStat(StatType::kElementId); if (!element_id.has_value()) continue; if (consume_event.GetParents().empty()) continue; // consume_event is nested by consumer_iterator and does not have other // parents. EventNode* consume_iterator = consume_event.GetParents().at(0); if (!consume_iterator || !IsIteratorEventType(consume_iterator->GetEventVisitor().Type())) { continue; } absl::optional<XStatVisitor> iterator_id = consume_iterator->GetEventVisitor().GetStat(StatType::kStepId); if (!iterator_id.has_value()) continue; if (auto produce_iterators = gtl::FindOrNull( produce_iterator_map, std::make_pair(iterator_id->IntValue(), element_id->IntValue()))) { for (EventNode* produce_iterator : *produce_iterators) { consume_iterator->AddChild(produce_iterator); ++num_matched; } } } } VLOG(1) << num_matched << " consumer iterators matched."; } void EventForest::GroupEvents() { ProcessTfDataSteps(); ProcessTensorFlowLoop(); ProcessWorker(); CreateEventGroups(); MarkEagerlyExecutedGpuKernels(); MarkEagerlyExecutedCpuTfOps(); } std::vector<InterThreadConnectInfo> CreateInterThreadConnectInfoList() { std::vector<InterThreadConnectInfo> connect_info_list = { {HostEventType::kExecutorStateProcess, HostEventType::kIteratorGetNextOp, {StatType::kStepId, StatType::kIterNum}}, {HostEventType::kExecutorStateProcess, HostEventType::kIteratorGetNextAsOptionalOp, {StatType::kStepId, StatType::kIterNum}}, {HostEventType::kKernelLaunch, HostEventType::kKernelExecute, {StatType::kCorrelationId}}}; return connect_info_list; } void GroupTfEvents(XSpace* space, EventForest* event_forest) { if (CheckLoopOp(*space)) { // TODO(b/154510598): Support TF's loop ops. return; } std::vector<InterThreadConnectInfo> connect_info_list = CreateInterThreadConnectInfoList(); event_forest->AddSpace(CreateTfXPlaneVisitor, space); event_forest->ConnectEvents(connect_info_list); event_forest->GroupEvents(); } void GroupTfEvents(XSpace* space) { EventForest event_forest; GroupTfEvents(space, &event_forest); } } // namespace profiler } // namespace tsl
{ "content_hash": "8d99c56c298b18ceccb94d51f6821a13", "timestamp": "", "source": "github", "line_count": 780, "max_line_length": 80, "avg_line_length": 36.684615384615384, "alnum_prop": 0.6654434892010904, "repo_name": "tensorflow/tensorflow-pywrap_tf_optimizer", "id": "5a718d0614c8d9ee1ff89d101cb40ed03504e6b4", "size": "29282", "binary": false, "copies": "9", "ref": "refs/heads/master", "path": "tensorflow/tsl/profiler/utils/group_events.cc", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "36962" }, { "name": "C", "bytes": "1360509" }, { "name": "C#", "bytes": "13584" }, { "name": "C++", "bytes": "124617937" }, { "name": "CMake", "bytes": "183407" }, { "name": "Cython", "bytes": "5003" }, { "name": "Dockerfile", "bytes": "416070" }, { "name": "Go", "bytes": "2104698" }, { "name": "HTML", "bytes": "4686483" }, { "name": "Java", "bytes": "1074471" }, { "name": "Jupyter Notebook", "bytes": "789401" }, { "name": "LLVM", "bytes": "6536" }, { "name": "MLIR", "bytes": "11175525" }, { "name": "Makefile", "bytes": "2760" }, { "name": "Objective-C", "bytes": "169288" }, { "name": "Objective-C++", "bytes": "294187" }, { "name": "Pawn", "bytes": "5552" }, { "name": "Perl", "bytes": "7536" }, { "name": "Python", "bytes": "42599764" }, { "name": "Roff", "bytes": "5034" }, { "name": "Ruby", "bytes": "9199" }, { "name": "Shell", "bytes": "619753" }, { "name": "Smarty", "bytes": "89545" }, { "name": "SourcePawn", "bytes": "14607" }, { "name": "Starlark", "bytes": "7521293" }, { "name": "Swift", "bytes": "78435" }, { "name": "Vim Snippet", "bytes": "58" } ], "symlink_target": "" }
using namespace boost::filesystem; using namespace boost::filesystem::path_traits; std::vector<StationBase> DirectoryProperties::initialize_stations() { // create vector of 'numberOfFolders' StationBases std::vector<StationBase> station( this->numberOfFolders ); // initialize stations parameters, as name, path, type and its types derivatives this->initialize_station_parameters( &station ); return station; } void DirectoryProperties::initialize_station_parameters( std::vector<StationBase> *station ) { // get stations names this->fill_station_names( station ); // get station type and stores paths for TS and complementary needed files, // accordingly to FILE_TYPE (equipment type) this->fill_station_types_and_paths( station ); } void DirectoryProperties::fill_station_names( std::vector<StationBase> *station ) { path p( this->pathName ); try { if( exists( p ) ) { if( is_directory( p ) ) { typedef std::vector<path> vec; // store paths, vec v; // so we can sort them later copy(directory_iterator(p), directory_iterator(), back_inserter(v)); sort(v.begin(), v.end()); // sort, since directory iteration is not ordered on some file systems size_t counter = 0; for (vec::const_iterator it (v.begin()); it != v.end(); ++it) { (*station)[counter].stationName = it->filename().string(); (*station)[counter++].path = this->pathName; } } else { std::cout << p << " exists, but is neither a regular file nor a directory" << std::endl; } } else { std::cout << p << " does not exist" << std::endl; } } catch( const filesystem_error& ex ) { std::cout << ex.what() << '\n'; } } void DirectoryProperties::fill_station_types_and_paths( std::vector<StationBase> *station ) { size_t nTbl = 0; for( int i = 0; i < this->numberOfFolders; i++ ) { nTbl = this->get_number_of_tbl_files( &(*station)[i] ); // MTU type if( nTbl > 0 ) { (*station)[i].fileType = FILE_TYPE_MTU; MtuDirInfo::fill_in_dir_mtu_info( &(*station)[i], nTbl ); } } } size_t DirectoryProperties::get_number_of_subfolders() { using namespace boost::lambda; path p( this->pathName ); size_t subfoldersCounter = std::count_if( directory_iterator(p), directory_iterator(), boost::lambda::bind( static_cast<bool(*)(const path&)>(is_directory), boost::lambda::bind( &directory_entry::path, _1 ) ) ); return subfoldersCounter; } size_t DirectoryProperties::get_number_of_tbl_files( StationBase *station ) { path p( this->pathName + "\\" + station->stationName ); size_t fileCounter = 0; try { if( exists( p ) ) { if( is_directory( p ) ) { typedef std::vector<path> vec; // store paths, vec v; // so we can sort them later copy(directory_iterator(p), directory_iterator(), back_inserter(v)); sort(v.begin(), v.end()); // sort, since directory iteration is not ordered on some file systems for (vec::const_iterator it (v.begin()); it != v.end(); ++it) { //std::cout << it->filename().string() << std::endl; if( it->filename().string().find( ".TBL" ) != std::string::npos ) fileCounter++; } } else { std::cout << p << " exists, but is neither a regular file nor a directory" << std::endl; return fileCounter; } } else { std::cout << p << " does not exist" << std::endl; return fileCounter; } } catch( const filesystem_error& ex ) { std::cout << ex.what() << '\n'; return fileCounter; } return fileCounter; } size_t DirectoryProperties::get_number_of_tsn_files( StationBase *station ) { size_t fileCounter = 0; size_t tsCounter = 0; StationFile auxTs; path p( this->pathName + "\\" + station->stationName ); try { if( exists( p ) ) { if( is_directory( p ) ) { typedef std::vector<path> vec; // store paths, vec v; // so we can sort them later copy(directory_iterator(p), directory_iterator(), back_inserter(v)); sort(v.begin(), v.end()); // sort, since directory iteration is not ordered on some file systems // get amount of TSn files for (vec::const_iterator it (v.begin()); it != v.end(); ++it) if( it->filename().string().find( ".TS" ) != std::string::npos ) fileCounter++; } else { std::cout << p << " exists, but is neither a regular file nor a directory" << std::endl; } } else { std::cout << p << " does not exist" << std::endl; } } catch( const filesystem_error& ex ) { std::cout << ex.what() << '\n'; } return fileCounter; } void MtuDirInfo::fill_in_dir_mtu_info( StationBase *station, size_t nTbl ) { size_t fileCounter = 0; vector<string> auxTblNames(nTbl); StationFile auxTs; string auxPath = station->path + "\\" + station->stationName; path p( auxPath ); try { if( exists( p ) ) { if( is_directory( p ) ) { typedef std::vector<path> vec; // store paths, vec v; // so we can sort them later copy(directory_iterator(p), directory_iterator(), back_inserter(v)); sort(v.begin(), v.end()); // sort, since directory iteration is not ordered on some file systems // get tbl names for (vec::const_iterator it (v.begin()); it != v.end(); ++it) { if( it->filename().string().find( ".TBL" ) != std::string::npos ) auxTblNames[ fileCounter++ ] = it->filename().string(); } // get TSn and its respective TBL and CTS files size_t tsCounter = 0; for( int i = 0; i < nTbl; i++ ) { for (vec::const_iterator it (v.begin()); it != v.end(); ++it) { if( it->filename().string().find( auxTblNames[i].substr( 0, auxTblNames[i].find( ".TBL" ) ) + ".TS" ) != std::string::npos ) { auxTs.mtu.tsnFile = it->string(); auxTs.mtu.tblFile = auxPath + "\\" + auxTblNames[i]; auxTs.mtu.mtuTsBand = phoenixTsBand_t( atoi( &(auxTs.mtu.tsnFile.back()) ) ); auxTs.mtu.ctsFile = auxPath + "\\" + it->filename().string().substr( 0, auxTblNames[i].find( ".TBL" ) ) + ".CTS"; station->ts.push_back(auxTs); tsCounter++; } } } } else { std::cout << p << " exists, but is neither a regular file nor a directory" << std::endl; } } else { std::cout << p << " does not exist" << std::endl; } } catch( const filesystem_error& ex ) { std::cout << ex.what() << '\n'; } } //size_t DirectoryProperties::count_TSn_files_for_each_tbl_file_and_get_its_name( StationBase *station, size_t idx, std::vector<std::string> **vectorOfTSnFiles ) //{ // //size_t fileCounter = 0; // //std::string inputSubPath = this->pathName + "\\" + station->stationName; // // //path p( inputSubPath ); // //try // //{ // // if( exists( p ) ) // // { // // if( is_directory( p ) ) // // { // // typedef std::vector<path> vec; // store paths, // // vec v; // so we can sort them later // // // copy(directory_iterator(p), directory_iterator(), back_inserter(v)); // // // sort(v.begin(), v.end()); // sort, since directory iteration is not ordered on some file systems // // // for (vec::const_iterator it (v.begin()); it != v.end(); ++it) // // { // // if( it->filename().string().find( station->mtu->inputTbl[idx] + ".TS" ) != std::string::npos ) { // // //vectorOfTSnFiles[idx][fileCounter++] = ""; // // } // // } // // } // // else // // { // // std::cout << p << " exists, but no TSn file could be associated with " << station->mtu->inputTbl[idx] << ".TBL file" << std::endl; // // return 0; // // } // // } // // else // // { // // std::cout << p << " does not exist" << std::endl; // // return 0; // // } // //} // //catch( const filesystem_error& ex ) // //{ // // std::cout << ex.what() << '\n' << std::endl; // // return 0; // //} // // //return fileCounter; // // return 0; //} // //void DirectoryProperties::define_tbl_files( StationBase *station ) //{ // //std::string inputSubPath = this->pathName + "\\" + station->stationName; // //path p( inputSubPath ); // // //size_t fileCounter = 0; // //try // //{ // // if( exists( p ) ) // // { // // if( is_directory( p ) ) // // { // // typedef std::vector<path> vec; // store paths, // // vec v; // so we can sort them later // // // copy(directory_iterator(p), directory_iterator(), back_inserter(v)); // // // sort(v.begin(), v.end()); // sort, since directory iteration is not ordered on some file systems // // // for (vec::const_iterator it (v.begin()); it != v.end(); ++it) // // { // // if( it->filename().string().find( ".TBL" ) != std::string::npos ) // // station->mtu->inputTbl[ fileCounter++ ] = it->filename().string().substr( 0, it->filename().string().find( ".TBL" ) ); // // } // // } // // else // // { // // std::cout << p << " exists, but is neither a regular file nor a directory" << std::endl; // // return; // // } // // } // // else // // { // // std::cout << p << " does not exist" << std::endl; // // return; // // } // //} // //catch( const filesystem_error& ex ) // //{ // // std::cout << ex.what() << '\n' << std::endl; // // return; // //} //} // //void DirectoryProperties::get_tbl_names( std::string *TBLs, std::string file, size_t size ) //{ // std::ifstream infile; // infile.open( file.c_str(), std::ios::in ); // // for( int i = 0; i < size; ++i ) // std::getline( infile, TBLs[ i ] ); // // infile.close(); //}
{ "content_hash": "8ab517af33546b5a2435eb8844e2103c", "timestamp": "", "source": "github", "line_count": 348, "max_line_length": 161, "avg_line_length": 27.74712643678161, "alnum_prop": 0.5605840927920464, "repo_name": "leomiquelutti/mtaas", "id": "041ce2b8a6ee194beff15f250b88843b070f8525", "size": "9809", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "mtaas/mtaas/DirectoryProperties.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "112930" }, { "name": "C++", "bytes": "232576" } ], "symlink_target": "" }
import mock from rally.plugins.openstack.context.network import allow_ssh from tests.unit import fakes from tests.unit import test CTX = "rally.plugins.openstack.context.network.allow_ssh" class AllowSSHContextTestCase(test.TestCase): def setUp(self): super(AllowSSHContextTestCase, self).setUp() self.users = 2 self.secgroup_name = "test-secgroup" self.ctx_with_secgroup = test.get_test_context() self.ctx_with_secgroup.update({ "users": [ { "tenant_id": "uuid1", "endpoint": "endpoint", "secgroup": {"id": "secgroup_id", "name": "secgroup"} } ] * self.users, "admin": {"tenant_id": "uuid2", "endpoint": "admin_endpoint"}, "tenants": {"uuid1": {"id": "uuid1", "name": "uuid1"}}, }) self.ctx_without_secgroup = test.get_test_context() self.ctx_without_secgroup.update({ "users": [{"tenant_id": "uuid1", "endpoint": "endpoint"}, {"tenant_id": "uuid1", "endpoint": "endpoint"}], "admin": {"tenant_id": "uuid2", "endpoint": "admin_endpoint"}, "tenants": {"uuid1": {"id": "uuid1", "name": "uuid1"}}, }) @mock.patch("%s.osclients.Clients" % CTX) def test__prepare_open_secgroup(self, mock_clients): fake_nova = fakes.FakeNovaClient() self.assertEqual(len(fake_nova.security_groups.list()), 1) mock_cl = mock.MagicMock() mock_cl.nova.return_value = fake_nova mock_clients.return_value = mock_cl ret = allow_ssh._prepare_open_secgroup("endpoint", self.secgroup_name) self.assertEqual(self.secgroup_name, ret["name"]) self.assertEqual(2, len(fake_nova.security_groups.list())) self.assertIn( self.secgroup_name, [sg.name for sg in fake_nova.security_groups.list()]) # run prep again, check that another security group is not created allow_ssh._prepare_open_secgroup("endpoint", self.secgroup_name) self.assertEqual(2, len(fake_nova.security_groups.list())) @mock.patch("%s.osclients.Clients" % CTX) def test__prepare_open_secgroup_rules(self, mock_clients): fake_nova = fakes.FakeNovaClient() # NOTE(hughsaunders) Default security group is precreated self.assertEqual(1, len(fake_nova.security_groups.list())) mock_cl = mock.MagicMock() mock_cl.nova.return_value = fake_nova mock_clients.return_value = mock_cl allow_ssh._prepare_open_secgroup("endpoint", self.secgroup_name) self.assertEqual(2, len(fake_nova.security_groups.list())) rally_open = fake_nova.security_groups.find(self.secgroup_name) self.assertEqual(3, len(rally_open.rules)) # run prep again, check that extra rules are not created allow_ssh._prepare_open_secgroup("endpoint", self.secgroup_name) rally_open = fake_nova.security_groups.find(self.secgroup_name) self.assertEqual(3, len(rally_open.rules)) @mock.patch("%s.osclients.Clients" % CTX) @mock.patch("%s._prepare_open_secgroup" % CTX) @mock.patch("rally.plugins.openstack.wrappers.network.wrap") def test_secgroup_setup_cleanup_with_secgroup_supported( self, mock_network_wrap, mock__prepare_open_secgroup, mock_clients): mock_network_wrapper = mock.MagicMock() mock_network_wrapper.supports_extension.return_value = ( True, "") mock_network_wrap.return_value = mock_network_wrapper mock__prepare_open_secgroup.return_value = { "name": "secgroup", "id": "secgroup_id"} mock_clients.return_value = mock.MagicMock() secgrp_ctx = allow_ssh.AllowSSH(self.ctx_with_secgroup) secgrp_ctx.setup() self.assertEqual(self.ctx_with_secgroup, secgrp_ctx.context) secgrp_ctx.cleanup() self.assertEqual( [ mock.call("admin_endpoint"), mock.call("endpoint"), mock.call().nova(), mock.call().nova().security_groups.get("secgroup_id"), mock.call().nova().security_groups.get().delete() ], mock_clients.mock_calls) mock_network_wrap.assert_called_once_with( mock_clients.return_value, self.ctx_with_secgroup["task"], config={}) @mock.patch("%s.osclients.Clients" % CTX) @mock.patch("rally.plugins.openstack.wrappers.network.wrap") def test_secgroup_setup_with_secgroup_unsupported( self, mock_network_wrap, mock_clients): mock_network_wrapper = mock.MagicMock() mock_network_wrapper.supports_extension.return_value = ( False, "Not supported") mock_network_wrap.return_value = mock_network_wrapper mock_clients.return_value = mock.MagicMock() secgrp_ctx = allow_ssh.AllowSSH(dict(self.ctx_without_secgroup)) secgrp_ctx.setup() self.assertEqual(self.ctx_without_secgroup, secgrp_ctx.context) mock_clients.assert_called_once_with("admin_endpoint") mock_network_wrap.assert_called_once_with( mock_clients.return_value, self.ctx_without_secgroup["task"], config={})
{ "content_hash": "af94c5eab9d90157c968c19cd63b00af", "timestamp": "", "source": "github", "line_count": 133, "max_line_length": 78, "avg_line_length": 40.50375939849624, "alnum_prop": 0.6047893075923519, "repo_name": "redhat-openstack/rally", "id": "8615bc08a1a9a2abf6e50b48d16c0ee6e84722d6", "size": "6017", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "tests/unit/plugins/openstack/context/network/test_allow_ssh.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Mako", "bytes": "48863" }, { "name": "Python", "bytes": "2746418" }, { "name": "Shell", "bytes": "43908" } ], "symlink_target": "" }
`Home <index.html>`_ OpenStack-Ansible Installation Guide Installation workflow --------------------- This diagram shows the general workflow associated with OSA installation. **Figure 1.7. Installation workflow** .. image:: figures/workflow-overview.png -------------- .. include:: navigation.txt
{ "content_hash": "f16b272606555a76a073eb094b1f51a2", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 59, "avg_line_length": 20.266666666666666, "alnum_prop": 0.6842105263157895, "repo_name": "jpmontez/os-ansible-deployment", "id": "fa885b5c648888de546b153b5d13960a16ef3829", "size": "306", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "doc/source/install-guide/overview-workflow.rst", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "666" }, { "name": "Python", "bytes": "278366" }, { "name": "Shell", "bytes": "99129" } ], "symlink_target": "" }
package com.intellij.refactoring.introduceField; import com.intellij.codeInsight.AnnotationUtil; import com.intellij.codeInsight.completion.JavaCompletionUtil; import com.intellij.ide.util.ClassFilter; import com.intellij.ide.util.PropertiesComponent; import com.intellij.ide.util.TreeClassChooser; import com.intellij.ide.util.TreeClassChooserFactory; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.event.DocumentEvent; import com.intellij.openapi.editor.event.DocumentListener; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.LanguageLevelProjectExtension; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.Comparing; import com.intellij.pom.java.LanguageLevel; import com.intellij.psi.*; import com.intellij.psi.codeStyle.JavaCodeStyleManager; import com.intellij.psi.codeStyle.SuggestedNameInfo; import com.intellij.psi.codeStyle.VariableKind; import com.intellij.psi.impl.source.resolve.JavaResolveUtil; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.refactoring.HelpID; import com.intellij.refactoring.JavaRefactoringSettings; import com.intellij.refactoring.RefactoringBundle; import com.intellij.refactoring.introduceParameter.AbstractJavaInplaceIntroducer; import com.intellij.refactoring.ui.*; import com.intellij.refactoring.util.CommonRefactoringUtil; import com.intellij.refactoring.util.EnumConstantsUtil; import com.intellij.refactoring.util.RefactoringMessageUtil; import com.intellij.ui.RecentsManager; import com.intellij.ui.ReferenceEditorComboWithBrowseButton; import com.intellij.ui.StateRestoringCheckBox; import com.intellij.usageView.UsageViewUtil; import com.intellij.util.ArrayUtil; import com.intellij.util.IncorrectOperationException; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Set; import static com.intellij.codeInsight.AnnotationUtil.CHECK_EXTERNAL; class IntroduceConstantDialog extends DialogWrapper { private static final Logger LOG = Logger.getInstance("#com.intellij.refactoring.introduceField.IntroduceConstantDialog"); @NonNls private static final String RECENTS_KEY = "IntroduceConstantDialog.RECENTS_KEY"; @NonNls protected static final String NONNLS_SELECTED_PROPERTY = "INTRODUCE_CONSTANT_NONNLS"; private final Project myProject; private final PsiClass myParentClass; private final PsiExpression myInitializerExpression; private final PsiLocalVariable myLocalVariable; private final boolean myInvokedOnDeclaration; private final PsiExpression[] myOccurrences; private final String myEnteredName; private final int myOccurrencesCount; private PsiClass myTargetClass; private final TypeSelectorManager myTypeSelectorManager; private NameSuggestionsField myNameField; private JCheckBox myCbReplaceAll; private TypeSelector myTypeSelector; private StateRestoringCheckBox myCbDeleteVariable; private final JavaCodeStyleManager myCodeStyleManager; private ReferenceEditorComboWithBrowseButton myTfTargetClassName; private BaseExpressionToFieldHandler.TargetDestination myDestinationClass; private JPanel myTypePanel; private JPanel myTargetClassNamePanel; private JPanel myPanel; private JLabel myTypeLabel; private JPanel myNameSuggestionPanel; private JLabel myNameSuggestionLabel; private JLabel myTargetClassNameLabel; private JCheckBox myCbNonNls; private JPanel myVisibilityPanel; private final JavaVisibilityPanel myVPanel; private final JCheckBox myIntroduceEnumConstantCb = new JCheckBox(RefactoringBundle.message("introduce.constant.enum.cb"), true); IntroduceConstantDialog(Project project, PsiClass parentClass, PsiExpression initializerExpression, PsiLocalVariable localVariable, boolean isInvokedOnDeclaration, PsiExpression[] occurrences, PsiClass targetClass, TypeSelectorManager typeSelectorManager, String enteredName) { super(project, true); myProject = project; myParentClass = parentClass; myInitializerExpression = initializerExpression; myLocalVariable = localVariable; myInvokedOnDeclaration = isInvokedOnDeclaration; myOccurrences = occurrences; myEnteredName = enteredName; myOccurrencesCount = occurrences.length; myTargetClass = targetClass; myTypeSelectorManager = typeSelectorManager; myDestinationClass = null; setTitle(IntroduceConstantHandler.REFACTORING_NAME); myCodeStyleManager = JavaCodeStyleManager.getInstance(myProject); myVPanel = new JavaVisibilityPanel(false, true); myVisibilityPanel.add(myVPanel, BorderLayout.CENTER); init(); String initialVisibility = JavaRefactoringSettings.getInstance().INTRODUCE_CONSTANT_VISIBILITY; if (initialVisibility == null) { initialVisibility = PsiModifier.PUBLIC; } myVPanel.setVisibility(initialVisibility); myIntroduceEnumConstantCb.setEnabled(isSuitableForEnumConstant()); updateVisibilityPanel(); updateButtons(); } public String getEnteredName() { return myNameField.getEnteredName(); } private String getTargetClassName() { return myTfTargetClassName.getText().trim(); } public BaseExpressionToFieldHandler.TargetDestination getDestinationClass () { return myDestinationClass; } public boolean introduceEnumConstant() { return myIntroduceEnumConstantCb.isEnabled() && myIntroduceEnumConstantCb.isSelected(); } public String getFieldVisibility() { return myVPanel.getVisibility(); } public boolean isReplaceAllOccurrences() { return myOccurrencesCount > 1 && myCbReplaceAll.isSelected(); } public PsiType getSelectedType() { return myTypeSelector.getSelectedType(); } @Override protected String getHelpId() { return HelpID.INTRODUCE_CONSTANT; } @Override protected JComponent createNorthPanel() { myTypeSelector = myTypeSelectorManager.getTypeSelector(); myTypePanel.setLayout(new BorderLayout()); myTypePanel.add(myTypeSelector.getComponent(), BorderLayout.CENTER); if (myTypeSelector.getFocusableComponent() != null) { myTypeLabel.setLabelFor(myTypeSelector.getFocusableComponent()); } myNameField = new NameSuggestionsField(myProject); myNameSuggestionPanel.setLayout(new BorderLayout()); myNameField.addDataChangedListener(() -> updateButtons()); myNameSuggestionPanel.add(myNameField.getComponent(), BorderLayout.CENTER); myNameSuggestionLabel.setLabelFor(myNameField.getFocusableComponent()); Set<String> possibleClassNames = new LinkedHashSet<>(); for (final PsiExpression occurrence : myOccurrences) { final PsiClass parentClass = new IntroduceConstantHandler().getParentClass(occurrence); if (parentClass != null && parentClass.getQualifiedName() != null) { possibleClassNames.add(parentClass.getQualifiedName()); } } myTfTargetClassName = new ReferenceEditorComboWithBrowseButton(new ChooseClassAction(), "", myProject, true, RECENTS_KEY); myTargetClassNamePanel.setLayout(new BorderLayout()); myTargetClassNamePanel.add(myTfTargetClassName, BorderLayout.CENTER); myTargetClassNameLabel.setLabelFor(myTfTargetClassName); for (String possibleClassName : possibleClassNames) { myTfTargetClassName.prependItem(possibleClassName); } myTfTargetClassName.getChildComponent().setSelectedItem(myParentClass.getQualifiedName()); myTfTargetClassName.getChildComponent().addDocumentListener(new DocumentListener() { @Override public void documentChanged(@NotNull DocumentEvent e) { targetClassChanged(); enableEnumDependant(introduceEnumConstant()); } }); myIntroduceEnumConstantCb.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { enableEnumDependant(introduceEnumConstant()); } }); final JPanel enumPanel = new JPanel(new BorderLayout()); enumPanel.add(myIntroduceEnumConstantCb, BorderLayout.EAST); myTargetClassNamePanel.add(enumPanel, BorderLayout.SOUTH); final String propertyName; if (myLocalVariable != null) { propertyName = myCodeStyleManager.variableNameToPropertyName(myLocalVariable.getName(), VariableKind.LOCAL_VARIABLE); } else { propertyName = null; } final NameSuggestionsManager nameSuggestionsManager = new NameSuggestionsManager(myTypeSelector, myNameField, createNameSuggestionGenerator(propertyName, myInitializerExpression, myCodeStyleManager, myEnteredName, myParentClass)); nameSuggestionsManager.setLabelsFor(myTypeLabel, myNameSuggestionLabel); ////////// if (myOccurrencesCount > 1) { myCbReplaceAll.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { updateTypeSelector(); myNameField.requestFocusInWindow(); } }); myCbReplaceAll.setText(RefactoringBundle.message("replace.all.occurences", myOccurrencesCount)); } else { myCbReplaceAll.setVisible(false); } if (myLocalVariable != null) { if (myInvokedOnDeclaration) { myCbDeleteVariable.setEnabled(false); myCbDeleteVariable.setSelected(true); } else if (myCbReplaceAll != null) { updateCbDeleteVariable(); myCbReplaceAll.addItemListener( new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { updateCbDeleteVariable(); } }); } } else { myCbDeleteVariable.setVisible(false); } if ((myTypeSelectorManager.isSuggestedType(CommonClassNames.JAVA_LANG_STRING) || (myLocalVariable != null && AnnotationUtil.isAnnotated(myLocalVariable, AnnotationUtil.NON_NLS, CHECK_EXTERNAL))) && LanguageLevelProjectExtension.getInstance(myProject).getLanguageLevel().isAtLeast(LanguageLevel.JDK_1_5) && JavaPsiFacade.getInstance(myProject).findClass(AnnotationUtil.NON_NLS, myParentClass.getResolveScope()) != null) { final PropertiesComponent component = PropertiesComponent.getInstance(myProject); myCbNonNls.setSelected(component.getBoolean(NONNLS_SELECTED_PROPERTY)); myCbNonNls.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { component.setValue(NONNLS_SELECTED_PROPERTY, myCbNonNls.isSelected()); } }); } else { myCbNonNls.setVisible(false); } updateTypeSelector(); enableEnumDependant(introduceEnumConstant()); return myPanel; } public void setReplaceAllOccurrences(boolean replaceAllOccurrences) { if (myCbReplaceAll != null) { myCbReplaceAll.setSelected(replaceAllOccurrences); } } protected static NameSuggestionsGenerator createNameSuggestionGenerator(final String propertyName, final PsiExpression psiExpression, final JavaCodeStyleManager codeStyleManager, final String enteredName, final PsiClass parentClass) { return new NameSuggestionsGenerator() { @Override public SuggestedNameInfo getSuggestedNameInfo(PsiType type) { SuggestedNameInfo nameInfo = codeStyleManager.suggestVariableName(VariableKind.STATIC_FINAL_FIELD, propertyName, psiExpression, type); if (psiExpression != null) { String[] names = nameInfo.names; for (int i = 0, namesLength = names.length; i < namesLength; i++) { String name = names[i]; if (parentClass.findFieldByName(name, false) != null) { names[i] = codeStyleManager.suggestUniqueVariableName(name, psiExpression, true); } } } final String[] strings = AbstractJavaInplaceIntroducer.appendUnresolvedExprName(JavaCompletionUtil .completeVariableNameForRefactoring(codeStyleManager, type, VariableKind.LOCAL_VARIABLE, nameInfo), psiExpression); return new SuggestedNameInfo.Delegate(enteredName != null ? ArrayUtil.mergeArrays(new String[]{enteredName}, strings): strings, nameInfo); } }; } private void updateButtons() { setOKActionEnabled(PsiNameHelper.getInstance(myProject).isIdentifier(getEnteredName())); } private void targetClassChanged() { final String targetClassName = getTargetClassName(); myTargetClass = JavaPsiFacade.getInstance(myProject).findClass(targetClassName, GlobalSearchScope.projectScope(myProject)); updateVisibilityPanel(); myIntroduceEnumConstantCb.setEnabled(isSuitableForEnumConstant()); } private boolean isSuitableForEnumConstant() { return EnumConstantsUtil.isSuitableForEnumConstant(getSelectedType(), myTargetClass) && PsiTreeUtil .getParentOfType(myInitializerExpression, PsiEnumConstant.class) == null; } private void enableEnumDependant(boolean enable) { if (enable) { myVPanel.disableAllButPublic(); } else { updateVisibilityPanel(); } myCbNonNls.setEnabled(!enable); } @Override protected JComponent createCenterPanel() { return new JPanel(); } public boolean isDeleteVariable() { return myInvokedOnDeclaration || myCbDeleteVariable != null && myCbDeleteVariable.isSelected(); } public boolean isAnnotateAsNonNls() { return myCbNonNls != null && myCbNonNls.isSelected(); } private void updateCbDeleteVariable() { if (!myCbReplaceAll.isSelected()) { myCbDeleteVariable.makeUnselectable(false); } else { myCbDeleteVariable.makeSelectable(); } } private void updateTypeSelector() { if (myCbReplaceAll != null) { myTypeSelectorManager.setAllOccurrences(myCbReplaceAll.isSelected()); } else { myTypeSelectorManager.setAllOccurrences(false); } } private void updateVisibilityPanel() { if (myTargetClass != null && myTargetClass.isInterface()) { myVPanel.disableAllButPublic(); } else { UIUtil.setEnabled(myVisibilityPanel, true, true); // exclude all modifiers not visible from all occurrences String effectiveVisibility = getEffectiveVisibility(getFieldVisibility(), myOccurrences, myTargetClass, myProject); if (effectiveVisibility != null) { myVPanel.setVisibility(effectiveVisibility); } } } public static String getEffectiveVisibility(String initialVisibility, PsiExpression[] occurrences, PsiClass targetClass, Project project) { final ArrayList<String> visible = new ArrayList<>(); visible.add(PsiModifier.PRIVATE); visible.add(PsiModifier.PROTECTED); visible.add(PsiModifier.PACKAGE_LOCAL); visible.add(PsiModifier.PUBLIC); for (PsiExpression occurrence : occurrences) { final PsiManager psiManager = PsiManager.getInstance(project); for (Iterator<String> iterator = visible.iterator(); iterator.hasNext();) { String modifier = iterator.next(); try { final String modifierText = PsiModifier.PACKAGE_LOCAL.equals(modifier) ? "" : modifier + " "; final PsiField field = JavaPsiFacade .getInstance(psiManager.getProject()).getElementFactory().createFieldFromText(modifierText + "int xxx;", targetClass); if (!JavaResolveUtil.isAccessible(field, targetClass, field.getModifierList(), occurrence, targetClass, null)) { iterator.remove(); } } catch (IncorrectOperationException e) { LOG.error(e); } } } if (!visible.isEmpty() && !visible.contains(initialVisibility)) { return visible.get(0); } return null; } @Override protected void doOKAction() { final String targetClassName = getTargetClassName(); PsiClass newClass = myParentClass; if (!targetClassName.isEmpty() && !Comparing.strEqual(targetClassName, myParentClass.getQualifiedName())) { newClass = JavaPsiFacade.getInstance(myProject).findClass(targetClassName, GlobalSearchScope.projectScope(myProject)); if (newClass == null) { if (Messages.showOkCancelDialog(myProject, RefactoringBundle.message("class.does.not.exist.in.the.project"), IntroduceConstantHandler.REFACTORING_NAME, Messages.getErrorIcon()) != Messages.OK) { return; } myDestinationClass = new BaseExpressionToFieldHandler.TargetDestination(targetClassName, myParentClass); } else { myDestinationClass = new BaseExpressionToFieldHandler.TargetDestination(newClass); } } String fieldName = getEnteredName(); String errorString = null; if (fieldName != null && fieldName.isEmpty()) { errorString = RefactoringBundle.message("no.field.name.specified"); } else if (!PsiNameHelper.getInstance(myProject).isIdentifier(fieldName)) { errorString = RefactoringMessageUtil.getIncorrectIdentifierMessage(fieldName); } else if (newClass != null && !myParentClass.getLanguage().equals(newClass.getLanguage())) { errorString = RefactoringBundle.message("move.to.different.language", UsageViewUtil.getType(myParentClass), myParentClass.getQualifiedName(), newClass.getQualifiedName()); } if (errorString != null) { CommonRefactoringUtil.showErrorMessage( IntroduceFieldHandler.REFACTORING_NAME, errorString, HelpID.INTRODUCE_FIELD, myProject); return; } if (newClass != null) { PsiField oldField = newClass.findFieldByName(fieldName, true); if (oldField != null) { int answer = Messages.showYesNoDialog( myProject, RefactoringBundle.message("field.exists", fieldName, oldField.getContainingClass().getQualifiedName()), IntroduceFieldHandler.REFACTORING_NAME, Messages.getWarningIcon() ); if (answer != Messages.YES) { return; } } } JavaRefactoringSettings.getInstance().INTRODUCE_CONSTANT_VISIBILITY = getFieldVisibility(); RecentsManager.getInstance(myProject).registerRecentEntry(RECENTS_KEY, targetClassName); super.doOKAction(); } @Override public JComponent getPreferredFocusedComponent() { return myNameField.getFocusableComponent(); } private class ChooseClassAction implements ActionListener { @Override public void actionPerformed(ActionEvent e) { TreeClassChooser chooser = TreeClassChooserFactory.getInstance(myProject).createWithInnerClassesScopeChooser(RefactoringBundle.message("choose.destination.class"), GlobalSearchScope.projectScope(myProject), new ClassFilter() { @Override public boolean isAccepted(PsiClass aClass) { return aClass.getParent() instanceof PsiJavaFile || aClass.hasModifierProperty(PsiModifier.STATIC); } }, null); if (myTargetClass != null) { chooser.selectDirectory(myTargetClass.getContainingFile().getContainingDirectory()); } chooser.showDialog(); PsiClass aClass = chooser.getSelected(); if (aClass != null) { myTfTargetClassName.setText(aClass.getQualifiedName()); } } } }
{ "content_hash": "2856a5329068665a6e65ba6c362e6bb5", "timestamp": "", "source": "github", "line_count": 497, "max_line_length": 232, "avg_line_length": 40.9215291750503, "alnum_prop": 0.7113285475464648, "repo_name": "goodwinnk/intellij-community", "id": "c2520c71a602ff4e10b48fb8330ea148abb93071", "size": "20479", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "java/java-impl/src/com/intellij/refactoring/introduceField/IntroduceConstantDialog.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?xml version='1.0' encoding='UTF-8'?> <para xmlns="http://docbook.org/ns/docbook" version="5.0"> <!-- Warning: Do not edit this file. It is automatically generated and your changes will be overwritten. The tool to do so lives in openstack-doc-tools repository. --> <table rules="all" xml:id="config_table_heat_clients_ceilometer"> <caption>Description of ceilometer clients configuration options</caption> <col width="50%"/> <col width="50%"/> <thead> <tr> <th>Configuration option = Default value</th> <th>Description</th> </tr> </thead> <tbody> <tr> <th colspan="2">[clients_ceilometer]</th> </tr> <tr> <td><option>ca_file</option> = <replaceable>None</replaceable></td> <td>(StrOpt) Optional CA cert file to use in SSL connections.</td> </tr> <tr> <td><option>cert_file</option> = <replaceable>None</replaceable></td> <td>(StrOpt) Optional PEM-formatted certificate chain file.</td> </tr> <tr> <td><option>endpoint_type</option> = <replaceable>None</replaceable></td> <td>(StrOpt) Type of endpoint in Identity service catalog to use for communication with the OpenStack service.</td> </tr> <tr> <td><option>insecure</option> = <replaceable>None</replaceable></td> <td>(BoolOpt) If set, then the server's certificate will not be verified.</td> </tr> <tr> <td><option>key_file</option> = <replaceable>None</replaceable></td> <td>(StrOpt) Optional PEM-formatted file that contains the private key.</td> </tr> </tbody> </table> </para>
{ "content_hash": "b2f8af5c17934960dae933a67a144454", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 123, "avg_line_length": 39.714285714285715, "alnum_prop": 0.6127098321342925, "repo_name": "kairoaraujo/openstack-manuals", "id": "34f5321f940b9c8042fd82475bb90a29231e58ce", "size": "1668", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "doc/common/tables/heat-clients_ceilometer.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "10340" }, { "name": "CSS", "bytes": "120983" }, { "name": "HTML", "bytes": "101194" }, { "name": "JavaScript", "bytes": "31040" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in Izv. Donsk. Inst. Sel'sk. Kohz. Melior. 9:47, 54, 58. 1929 #### Original name null ### Remarks null
{ "content_hash": "aceb7a5b432a5e3e9c99e45593a6ab0b", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 58, "avg_line_length": 13.846153846153847, "alnum_prop": 0.6833333333333333, "repo_name": "mdoering/backbone", "id": "6022c955c6043c6e5a35efad5371965b0b5d21e3", "size": "245", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Orobanchaceae/Orobanche/Orobanche brassicae/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package com.jongsoft.harvester.api; import com.jongsoft.harvester.exception.NotFoundException; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; @ControllerAdvice(basePackages = {"com.jongsoft.harvester.api"}) public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler { @ExceptionHandler(value = { NotFoundException.class }) protected ResponseEntity<Object> handleConflict(RuntimeException ex, WebRequest request) { String bodyOfResponse = "This should be application specific"; return handleExceptionInternal(ex, bodyOfResponse, new HttpHeaders(), HttpStatus.NOT_FOUND, request); } }
{ "content_hash": "42d7a7bb193eacf6accb995e68a05c9f", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 109, "avg_line_length": 50.9, "alnum_prop": 0.8231827111984283, "repo_name": "gjong/web-harvester", "id": "b2bdff691aaa339a566c70bcc7617327a92551c9", "size": "1018", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "webbase/src/main/java/com/jongsoft/harvester/api/RestResponseEntityExceptionHandler.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1688" }, { "name": "HTML", "bytes": "5626" }, { "name": "Java", "bytes": "378507" }, { "name": "JavaScript", "bytes": "374633" }, { "name": "Shell", "bytes": "1" } ], "symlink_target": "" }
class CreateActors < ActiveRecord::Migration def change create_table :actors do |t| t.string :first_name t.string :last_name t.string :image t.string :bio t.timestamps end end end
{ "content_hash": "ddb82d712e9bb6e63d1274018aeafc12", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 44, "avg_line_length": 20.181818181818183, "alnum_prop": 0.6306306306306306, "repo_name": "ummahusla/codecademy-exercise-answers", "id": "7bcc379746f9fb955e472c5654979943454e8675", "size": "222", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Web Developer Skills/Learn Ruby on Rails/Unit 04 Associations II/03 Models II/20150408012639_create_actors.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "31931" }, { "name": "HTML", "bytes": "41982" }, { "name": "JavaScript", "bytes": "51754" }, { "name": "Python", "bytes": "68602" }, { "name": "Ruby", "bytes": "9558" } ], "symlink_target": "" }
![Azure Public Test Date](https://azurequickstartsservice.blob.core.windows.net/badges/201-private-endpoint-sql-from-appservice/PublicLastTestDate.svg) ![Azure Public Test Result](https://azurequickstartsservice.blob.core.windows.net/badges/201-private-endpoint-sql-from-appservice/PublicDeployment.svg) ![Azure US Gov Last Test Date](https://azurequickstartsservice.blob.core.windows.net/badges/201-private-endpoint-sql-from-appservice/FairfaxLastTestDate.svg) ![Azure US Gov Last Test Result](https://azurequickstartsservice.blob.core.windows.net/badges/201-private-endpoint-sql-from-appservice/FairfaxDeployment.svg) ![Best Practice Check](https://azurequickstartsservice.blob.core.windows.net/badges/201-private-endpoint-sql-from-appservice/BestPracticeResult.svg) ![Cred Scan Check](https://azurequickstartsservice.blob.core.windows.net/badges/201-private-endpoint-sql-from-appservice/CredScanResult.svg) [![Deploy To Azure](https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/1-CONTRIBUTION-GUIDE/images/deploytoazure.svg?sanitize=true)](https://portal.azure.com/#create/Microsoft.Template/uri/https%3A%2F%2Fraw.githubusercontent.com%2FAzure%2Fazure-quickstart-templates%2Fmaster%2F201-private-endpoint-sql-from-appservice%2Fazuredeploy.json) [![Visualize](https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/1-CONTRIBUTION-GUIDE/images/visualizebutton.svg?sanitize=true)](http://armviz.io/#/?load=https%3A%2F%2Fraw.githubusercontent.com%2FAzure%2Fazure-quickstart-templates%2Fmaster%2F201-private-endpoint-sql-from-appservice%2Fazuredeploy.json) This is a starter template that shows how to consume an Azure SQL private endpoint from a web app ## Architecture Diagram ![architecture diagram](images/webappsqlpvtlink.png) ## Notes [Azure Private Link FAQ](https://docs.microsoft.com/en-us/azure/private-link/private-link-faq) [Private link endpoints template format](https://docs.microsoft.com/en-us/azure/templates/microsoft.network/2020-04-01/privateendpoints)
{ "content_hash": "210106369063152b0087f5d6fd14a0b7", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 360, "avg_line_length": 84.375, "alnum_prop": 0.8222222222222222, "repo_name": "sabbour/azure-quickstart-templates", "id": "b95be30119b6215797b1e304ae59f4ebad40b374", "size": "2076", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "201-private-endpoint-sql-from-appservice/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "208" }, { "name": "Groovy", "bytes": "394" }, { "name": "JavaScript", "bytes": "18742" }, { "name": "PHP", "bytes": "1774" }, { "name": "PowerShell", "bytes": "211961" }, { "name": "Python", "bytes": "106311" }, { "name": "Shell", "bytes": "508563" } ], "symlink_target": "" }
require_relative "test_helper" require_relative "../lib/giblish/resourcepaths" module Giblish class ResourceTests < GiblishTestBase include Giblish::TestUtils def create_resource_dir resource_topdir Dir.exist?(resource_topdir) || FileUtils.mkdir_p(resource_topdir) %i[dir1 dir2 images].each do |dir| src = "#{resource_topdir}/#{dir}" Dir.exist?(src) || FileUtils.mkdir(src) end # create fake custom css file File.write("#{resource_topdir}/dir1/custom.css", "fake custom css") # create fake custom yml file File.write("#{resource_topdir}/dir1/custom.yml", <<~PDF_STYLE) giblish: color: blue: [0, 0, 187] red: [184, 0, 7] lightgrey: [224, 224, 224] font: catalog: # The default font MyDefault: normal: gothic.ttf bold: gothicb.ttf italic: gothici.ttf bold_italic: gothicbi.ttf Arial: normal: arial.ttf bold: arialbd.ttf italic: ariali.ttf bold_italic: arialbi.ttf fallbacks: - Arial main_font_family: MyDefault page: background_color: ffffff layout: portrait margin: 20mm margin_inner: 2.0cm margin_outer: 2.0cm size: A4 numbering-start-at: 1 base: align: left font_color: $giblish_color_lightgrey font_family: $main_font_family font_size: 9 line_height_length: 10.5 line_height: $base_line_height_length / $base_font_size font_size_large: round($base_font_size * 1.25) font_size_small: round($base_font_size * 0.85) font_size_min: $base_font_size * 0.75 font_style: normal border_color: $giblish_color_lightgrey border_radius: 4 border_width: 0.25 vertical_rhythm: $base_line_height_length * 2 / 3 horizontal_rhythm: $base_line_height_length vertical_spacing: $vertical_rhythm link: font_color: $giblish_color_blue literal: font_color: 000000 font_family: Courier font_size: 9 title_page: align: left title: font_size: 30 font_style: bold font_color: $giblish_color_blue top: 80% subtitle: font_size: 15 font_style: bold font_color: 000000 revision: font_size: 15 font_style: bold font_color: 000000 authors: font_size: 15 font_style: bold font_color: 000000 heading: align: left margin_top: $vertical_rhythm * 1.4 margin_bottom: $vertical_rhythm * 0.7 line_height: 1 font_color: $giblish_color_lightgrey font_family: $main_font_family font_style: normal h1_font_size: 34 h1_font_color: $giblish_color_blue h2_font_size: 16 h2_font_color: $giblish_color_blue h3_font_size: 12 h3_font_color: $giblish_color_blue authors: margin_top: $base_font_size * 1.25 font_size: $base_font_size_large font_color: 000000 revision: margin_top: $base_font_size * 1.25 admonition: padding: [0, $horizontal_rhythm, 0, $horizontal_rhythm] border_color: $base_border_color column_rule_color: $base_border_color icon: warning: name: fa-heartbeat stroke_color: $giblish_color_blue size: 20 caution: name: fa-exclamation stroke_color: $giblish_color_blue size: 20 note: name: fa-info-circle stroke_color: $giblish_color_blue size: 20 tip: name: fa-lightbulb-o stroke_color: $giblish_color_blue size: 20 toc: font_family: $heading_font_family font_color: $giblish_color_blue #dot_leader_color: ffffff #dot_leader_content: ' ' dot_leader_levels: 1 indent: $horizontal_rhythm line_height: 1.4 h1_font_style: bold h2_font_style: bold PDF_STYLE # create fake image File.write("#{resource_topdir}/images/fake_image.png", "fake png image") # create fake font File.write("#{resource_topdir}/dir1/fake_font.ttf", "fake font") end def test_copy_resources_absolute TmpDocDir.open(preserve: false) do |tmp_docs| topdir = Pathname.new(tmp_docs.dir) create_resource_dir(topdir / "my/resources") opts = CmdLine.new.parse(%W[-f html -r #{topdir / "my/resources"} -s custom #{topdir} #{topdir / "dst"}]) pb = CopyResourcesPreBuild.new(opts) pb.on_prebuild(nil, nil, nil) r = PathTree.build_from_fs(topdir, prune: true) assert(r.node("dst/web_assets/dir1")) assert(r.node("dst/web_assets/dir1/custom.css")) end end def test_copy_resources_use_working_dir TmpDocDir.open(preserve: false) do |tmp_docs| topdir = Pathname.new(tmp_docs.dir) create_resource_dir(topdir / "my/resources") Dir.chdir(topdir.to_s) do opts = CmdLine.new.parse(%W[-f html -r my/resources -s custom #{topdir} dst]) CopyResourcesPreBuild.new(opts).on_prebuild(nil, nil, nil) r = PathTree.build_from_fs(topdir, prune: true) assert(r.node("dst/web_assets/dir1")) end end end def test_resource_paths_empty TmpDocDir.open(preserve: false) do |tmp_docs| topdir = Pathname.new(tmp_docs.dir) # fake an empty resource dir (topdir / "my/resources").mkpath opts = CmdLine.new.parse(%W[-f html -r #{topdir / "my/resources"} -s custom #{topdir} dst]) # no custom.css -> explode assert_raises(OptionParser::InvalidArgument) { ResourcePaths.new(opts) } opts = CmdLine.new.parse(%W[-f pdf -r #{topdir / "my/resources"} -s custom #{topdir} dst]) # no custom.yml -> explode assert_raises(OptionParser::InvalidArgument) { ResourcePaths.new(opts) } end end def test_resource_paths TmpDocDir.open(preserve: false) do |tmp_docs| topdir = Pathname.new(tmp_docs.dir) copy_test_resources(topdir / "my/resources") opts = CmdLine.new.parse(%W[-f html -r #{topdir / "my/resources"} -s giblish #{topdir} #{topdir / "dst"}]) p = ResourcePaths.new(opts) assert_equal( Pathname.new("web/giblish.css"), p.src_style_path_rel ) assert_equal( Pathname.new("web_assets/web/giblish.css"), p.dst_style_path_rel ) assert_equal( Set[topdir / "my/resources/custom_fonts/urbanist"], p.font_dirs_abs ) assert_equal( topdir / "dst/web_assets", p.dst_resource_dir_abs ) opts = CmdLine.new.parse(%W[-f pdf -r #{topdir / "my/resources"} -s giblish #{topdir} #{topdir / "dst"}]) p = ResourcePaths.new(opts) assert_equal( Pathname.new("pdf/giblish.yml"), p.src_style_path_rel ) assert_equal( Pathname.new("web_assets/pdf/giblish.yml"), p.dst_style_path_rel ) assert_equal( Set[topdir / "my/resources/custom_fonts/urbanist"], p.font_dirs_abs ) end end end end
{ "content_hash": "0cd211a1f45c8bb76484b1093dee249f", "timestamp": "", "source": "github", "line_count": 244, "max_line_length": 114, "avg_line_length": 32.881147540983605, "alnum_prop": 0.5299763180855042, "repo_name": "rillbert/giblish", "id": "1e310407b3362cb717b67a8f102800b3fddbf757", "size": "8023", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "test/resource_test.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "155695" }, { "name": "HTML", "bytes": "21677" }, { "name": "Ruby", "bytes": "271087" }, { "name": "Shell", "bytes": "3182" } ], "symlink_target": "" }
<?php /** * * @package Core_Resource * @author Christian Gijtenbeek <gijtenbeek@terena.org> */ class Core_Resource_UsersRoles extends TA_Model_Resource_Db_Table_Abstract { protected $_name = 'user_role'; protected $_primary = 'user_role_id'; // many to many mapping protected $_referenceMap = array( 'User' => array( 'columns' => array('user_id'), 'refTableClass' => 'Core_Resource_Users', 'refColumns' => array('user_id') ), 'Role' => array( 'columns' => array('role_id'), 'refTableClass' => 'Core_Resource_Roles', 'refColumns' => array('role_id') ) ); }
{ "content_hash": "3c69b04702e7882c65e87b60c0fe2a6a", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 74, "avg_line_length": 19.322580645161292, "alnum_prop": 0.6277128547579299, "repo_name": "Christian-G/terena-core", "id": "6a10fcda611f5589256dea0290289bfe17c11254", "size": "1226", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "application/modules/core/models/resources/UsersRoles.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "64" }, { "name": "CSS", "bytes": "57929" }, { "name": "HTML", "bytes": "298259" }, { "name": "JavaScript", "bytes": "24333" }, { "name": "PHP", "bytes": "1729925" }, { "name": "SQLPL", "bytes": "60140" }, { "name": "Smarty", "bytes": "7111" } ], "symlink_target": "" }
package com.company.ordermanagement.portal.controllers; import com.company.ordermanagement.entity.Product; import com.company.ordermanagement.portal.command.LoginUserCommand; import com.haulmont.cuba.core.app.DataService; import com.haulmont.cuba.core.global.LoadContext; import com.haulmont.cuba.portal.security.PortalSessionProvider; import com.haulmont.cuba.security.entity.User; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import javax.inject.Inject; /** * @author mario */ @Controller public class PortalController { @Inject protected DataService dataService; @RequestMapping(value = "/", method = RequestMethod.GET) public String index(Model model) { if (!PortalSessionProvider.getUserSession().isAuthenticated()) { final LoginUserCommand loginUserCommand = new LoginUserCommand(); model.addAttribute(loginUserCommand); } LoadContext l = LoadContext.create(Product.class).setView("product-view"); l.setQueryString("select p from om$Product p"); model.addAttribute("products", dataService.loadList(l)); return "index"; } }
{ "content_hash": "1bf4cbfd8c5d45895b00a89d1af8bea4", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 82, "avg_line_length": 33.282051282051285, "alnum_prop": 0.7557781201848999, "repo_name": "mariodavid/cuba-ordermanagement", "id": "fdf88866b33cf18ad6049543e63bf1af4e243f98", "size": "1342", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/portal/src/com/company/ordermanagement/portal/controllers/PortalController.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "FreeMarker", "bytes": "7933" }, { "name": "Groovy", "bytes": "2221" }, { "name": "Java", "bytes": "18165" } ], "symlink_target": "" }
.. _relativity: **************************************************************** Relativistic functions (`plasmapy.formulary.relativity`) **************************************************************** .. currentmodule:: plasmapy.formulary.relativity .. automodapi:: plasmapy.formulary.relativity
{ "content_hash": "b352bfca855194e5e18e5124919d2ecc", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 64, "avg_line_length": 33.44444444444444, "alnum_prop": 0.4485049833887043, "repo_name": "StanczakDominik/PlasmaPy", "id": "0ea5df3b631ce852af482bfff96d197734fa3c9c", "size": "301", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "docs/formulary/relativity.rst", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Jupyter Notebook", "bytes": "1285" }, { "name": "Python", "bytes": "2148684" } ], "symlink_target": "" }
#ifndef OVR_Recording_h #define OVR_Recording_h namespace OVR { namespace Recording { enum RecordingMode { RecordingOff = 0x0, RecordForPlayback = 0x1, RecordForLogging = 0x2 }; }} // OVR::Recording #ifdef ENABLE_RECORDING #include "Recording/Recording_Recorder.h" #else // If Recording is not enabled, then stub it out namespace OVR { struct PositionCalibrationReport; namespace Vision { class CameraIntrinsics; class DistortionCoefficients; class Blob; }; namespace Recording { class Recorder { public: OVR_FORCE_INLINE void RecordCameraParams(const Vision::CameraIntrinsics&, const Vision::DistortionCoefficients&) { } OVR_FORCE_INLINE void RecordLedPositions(const Array<PositionCalibrationReport>&) { } OVR_FORCE_INLINE void RecordUserParams(const Vector3f&, float) { } OVR_FORCE_INLINE void RecordDeviceIfcVersion(UByte) { } OVR_FORCE_INLINE void RecordMessage(const Message&) { } OVR_FORCE_INLINE void RecordCameraFrameUsed(UInt32) { } OVR_FORCE_INLINE void RecordVisionSuccess(UInt32) { } template<typename T> OVR_FORCE_INLINE void LogData(const char*, const T&) { } OVR_FORCE_INLINE void SetRecordingMode(RecordingMode) { } OVR_FORCE_INLINE RecordingMode GetRecordingMode() { return RecordingOff; } }; extern Recorder r; OVR_FORCE_INLINE Recorder& GetRecorder() { return r; } }} // namespace OVR::Recording #endif // ENABLE_RECORDING #endif // OVR_Recording_h
{ "content_hash": "1de3fa666bfea1e7259dbded99ce3b6f", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 89, "avg_line_length": 25.491525423728813, "alnum_prop": 0.7121010638297872, "repo_name": "stevespiss/oculus_ros", "id": "fc83270a2bd7e5743b7b4f5a3730ff6303401d43", "size": "2585", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "LibOVR/Src/OVR_Recording.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "604" }, { "name": "C", "bytes": "2077675" }, { "name": "C++", "bytes": "1992898" }, { "name": "CMake", "bytes": "9464" }, { "name": "GLSL", "bytes": "8231" }, { "name": "Objective-C", "bytes": "1376" }, { "name": "Shell", "bytes": "3867" } ], "symlink_target": "" }
#pragma once #include "core_api.h" template <typename T> inline void SAFE_DELETE( T* & object) { if (object) { delete object; object = nullptr; } } template <typename T> inline void SAFE_DELETE( T* && object) { if (object) delete object; } template <typename Base, typename Derived> inline void dynamicCastAndAssign(Base& base, Derived& derived) { static_assert(std::is_base_of<typename Base::element_type, typename Derived::element_type>::value, "dynamicCastAndAssign requires two classes that have an inheritance relationship"); if (auto cast = dynamic_cast<typename Derived::pointer>(base.get())) { base.release(); derived.reset(cast); } } class CORE_API OnScopeExit { public: OnScopeExit(const OnScopeExit& other) = delete; OnScopeExit(OnScopeExit&& other) = delete; OnScopeExit& operator= (const OnScopeExit other) = delete; template<typename T> explicit OnScopeExit(T&& functionToCall); ~OnScopeExit(); private: std::function<void ()> functionToCall_; }; template <typename T> inline OnScopeExit::OnScopeExit(T&& functionToCall) : functionToCall_{std::forward<T>(functionToCall)}{} inline OnScopeExit::~OnScopeExit() { functionToCall_(); } class CORE_API SystemCommandResult { public: int exitCode() const; QStringList standardout() const; QString standardoutOneLine() const; QStringList standarderr() const; operator QString() const; operator QStringList() const; private: friend SystemCommandResult runSystemCommand(const QString& command, const QStringList& arguments, const QString& workingDirectory); int exitCode_{}; QStringList standardout_; QStringList standarderr_; }; inline int SystemCommandResult::exitCode() const { return exitCode_; } inline QStringList SystemCommandResult::standardout() const { return standardout_; } inline QStringList SystemCommandResult::standarderr() const { return standarderr_; } SystemCommandResult CORE_API runSystemCommand(const QString& program, const QStringList& arguments = {}, const QString& workingDirectory = {}); template<typename T> typename std::enable_if<std::is_constructible<bool, T>::value, bool>::type isProvided(T&&t) { return static_cast<bool>(t); } template<typename T> constexpr inline typename std::enable_if<!std::is_constructible<bool, T>::value, bool>::type isProvided(T&&) { return true; }
{ "content_hash": "462e5e8e1baf884307ebe71a9806ff2f", "timestamp": "", "source": "github", "line_count": 89, "max_line_length": 108, "avg_line_length": 26.685393258426966, "alnum_prop": 0.7322105263157894, "repo_name": "Vaishal-shah/Envision", "id": "27f75592f2793c03b36d1ce448acd0082440e937", "size": "4181", "binary": false, "copies": "3", "ref": "refs/heads/development", "path": "Core/src/global.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "780" }, { "name": "C", "bytes": "79038" }, { "name": "C++", "bytes": "8004777" }, { "name": "CMake", "bytes": "77874" }, { "name": "CSS", "bytes": "31" }, { "name": "HTML", "bytes": "2314" }, { "name": "Java", "bytes": "135892" }, { "name": "Python", "bytes": "45530" }, { "name": "Shell", "bytes": "22567" } ], "symlink_target": "" }
package com.wind.oauth.integration; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.annotation.Bean; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.security.web.util.matcher.OrRequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.stereotype.Component; import org.springframework.web.filter.GenericFilterBean; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Map; @Component public class IntegrationAuthenticationFilter extends GenericFilterBean implements ApplicationContextAware { private static final String AUTH_TYPE_PARAMETER = "auth_type"; private static final String OAUTH_TOKEN_URL = "/oauth/token"; @Bean private Collection<IntegrationAuthenticator> getAuthenticators() { Map<String, IntegrationAuthenticator> integrationAuthenticatorMap = applicationContext.getBeansOfType(IntegrationAuthenticator.class); return integrationAuthenticatorMap.values(); } private ApplicationContext applicationContext; private RequestMatcher requestMatcher; public IntegrationAuthenticationFilter() { this.requestMatcher = new OrRequestMatcher( new AntPathRequestMatcher(OAUTH_TOKEN_URL, "GET"), new AntPathRequestMatcher(OAUTH_TOKEN_URL, "POST") ); } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; if (requestMatcher.matches(request)) { //设置集成登录信息 IntegrationAuthentication integrationAuthentication = new IntegrationAuthentication(); integrationAuthentication.setAuthType(request.getParameter(AUTH_TYPE_PARAMETER)); integrationAuthentication.setAuthParameters(request.getParameterMap()); IntegrationAuthenticationContext.set(integrationAuthentication); try { //预处理 this.prepare(integrationAuthentication); filterChain.doFilter(request, response); //后置处理 this.complete(integrationAuthentication); } finally { IntegrationAuthenticationContext.clear(); } } else { filterChain.doFilter(request, response); } } /** * 进行预处理 * * @param integrationAuthentication */ private void prepare(IntegrationAuthentication integrationAuthentication) { for (IntegrationAuthenticator authenticator : getAuthenticators()) { if (authenticator.support(integrationAuthentication)) { authenticator.prepare(integrationAuthentication); } } } /** * 后置处理 * * @param integrationAuthentication */ private void complete(IntegrationAuthentication integrationAuthentication) { for (IntegrationAuthenticator authenticator : getAuthenticators()) { if (authenticator.support(integrationAuthentication)) { authenticator.complete(integrationAuthentication); } } } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } }
{ "content_hash": "b4b3115e974102cff26169a0516b66b7", "timestamp": "", "source": "github", "line_count": 107, "max_line_length": 152, "avg_line_length": 36.91588785046729, "alnum_prop": 0.7255696202531645, "repo_name": "ustcwudi/SpringBoot-Seed", "id": "8d35f88d398c64d51bef236dd55031e9fa24068c", "size": "3998", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/wind/oauth/integration/IntegrationAuthenticationFilter.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "5006" }, { "name": "Java", "bytes": "28268" }, { "name": "Shell", "bytes": "7058" } ], "symlink_target": "" }
package com.zhanjiqiang.qweather.activity; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.text.TextUtils; import android.view.View; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.zhanjiqiang.qweather.R; import com.zhanjiqiang.qweather.service.AutoUpdataService; import com.zhanjiqiang.qweather.utils.HttpCallbackListener; import com.zhanjiqiang.qweather.utils.HttpUtils; import com.zhanjiqiang.qweather.utils.UIUtils; import com.zhanjiqiang.qweather.utils.Utility; import net.youmi.android.banner.AdSize; import net.youmi.android.banner.AdView; /** * @packageName:com.zhanjiqiang.qweather.activity * @className:WeatherActivity * @author:彳亍 * @:2015/3/30 0030 23:15 * @describe:天气界面的活动 */ public class WeatherActivity extends Activity implements View.OnClickListener{ private LinearLayout weatherInfoLayout; /** * 显示城市名称 */ private TextView cityName; /** * 显示发布时间 */ private TextView publishTime; /** * 显示当前日期 */ private TextView data; /** * 显示天气状态 */ private TextView weatherDespText; /** * 显示最低温度 */ private TextView lowTemperature; /** * 显示最高温度 */ private TextView highTemperature; /** * 返回城市选择页的按钮 */ private ImageButton home; /** * 刷新天气的按钮 */ private ImageButton refresh; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initView(); } /** * View初始化 */ public void initView() { setContentView(R.layout.weather_layout); AdView adView = new AdView(UIUtils.getContext(), AdSize.FIT_SCREEN); LinearLayout adLayout = (LinearLayout) findViewById(R.id.aDLayout); adLayout.addView(adView); weatherInfoLayout = (LinearLayout) findViewById(R.id.weather_info_layout); cityName = (TextView) findViewById(R.id.weather_city_name); publishTime = (TextView) findViewById(R.id.weather_publish_data); data = (TextView) findViewById(R.id.weather_data); weatherDespText = (TextView) findViewById(R.id.weather_status); lowTemperature = (TextView) findViewById(R.id.weather_low_temperature); highTemperature = (TextView) findViewById(R.id.weather_high_temperature); String countyCode = getIntent().getStringExtra("county_code"); if (!TextUtils.isEmpty(countyCode)){ publishTime.setText("同步中..."); weatherInfoLayout.setVisibility(View.INVISIBLE); cityName.setVisibility(View.INVISIBLE); queryWeatherCode(countyCode); }else { showWeather(); } home = (ImageButton) findViewById(R.id.weather_swit_city); refresh = (ImageButton) findViewById(R.id.weather_refresh); home.setOnClickListener(this); refresh.setOnClickListener(this); } /** * 从SharedPreferences文件中读取存数的天气信息,并显示在界面上. */ public void showWeather() { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(UIUtils.getContext()); cityName.setText(preferences.getString("city_name","")); publishTime.setText("今天"+preferences.getString("publish_time","")+"发布"); data.setText(preferences.getString("data","")); weatherDespText.setText(preferences.getString("weather","")); lowTemperature.setText(preferences.getString("low_temperature","")); highTemperature.setText(preferences.getString("high_temperature","")); weatherInfoLayout.setVisibility(View.VISIBLE); cityName.setVisibility(View.VISIBLE); Intent intent = new Intent(UIUtils.getContext(), AutoUpdataService.class); startService(intent); } /** * 查询县级代号所对应的天气代号 * @param countyCode 县级代号 */ private void queryWeatherCode(String countyCode) { String address = "http://www.weather.com.cn/data/list3/city"+countyCode+".xml"; queryFomServer(address, "countyCode"); } /** * 查询天气代号所对应的天气 * @param weatherCode */ private void queryWeatherInfo(String weatherCode){ String address = "http://www.weather.com.cn/data/cityinfo/"+weatherCode+".html"; queryFomServer(address, "weatherCode"); } private void queryFomServer(final String address, final String type) { HttpUtils.sendHttpRequest(address, new HttpCallbackListener() { @Override public void onFinsh(final String response) { if ("countyCode".equals(type)){ if (!TextUtils.isEmpty(response)){ //从服务器返回的数据中解析天气代码 String [] array = response.split("\\|"); if (array != null && array.length == 2){ String weatherCode = array[1]; queryWeatherInfo(weatherCode); } } }else if ("weatherCode".equals(type)){ //处理服务器返回的天气信息 Utility.handleWeatherResponse(WeatherActivity.this,response); runOnUiThread(new Runnable() { @Override public void run() { showWeather(); } }); } } @Override public void onError(Exception e) { runOnUiThread(new Runnable() { @Override public void run() { publishTime.setText("同步失败"); Toast.makeText(UIUtils.getContext(),"同步失败",Toast.LENGTH_SHORT).show(); } }); } }); } /** * 按钮的点击事件 * * @param v The view that was clicked. */ @Override public void onClick(View v) { switch (v.getId()){ case R.id.weather_swit_city: Intent intent = new Intent(UIUtils.getContext(),ChooseAreaActivity.class); intent.putExtra("from_weather_activity",true); startActivity(intent); finish(); break; case R.id.weather_refresh: publishTime.setText("同步中..."); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(UIUtils.getContext()); String weatherCode = preferences.getString("weather_code",""); if (!TextUtils.isEmpty(weatherCode)){ queryWeatherInfo(weatherCode); } break; default: break; } } }
{ "content_hash": "c231951c89ebc156b2fa8e2e915db823", "timestamp": "", "source": "github", "line_count": 203, "max_line_length": 116, "avg_line_length": 34.152709359605915, "alnum_prop": 0.6000288475407471, "repo_name": "zhanjiqiang/QWeather", "id": "ad25e86b24f4a212c3bf6494cace0a60851e17cf", "size": "7269", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/zhanjiqiang/qweather/activity/WeatherActivity.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "38930" } ], "symlink_target": "" }
def VIM::has ident # All return values from `evaluate` are strings, and # # "0" evaluates to true in ruby. return VIM::evaluate("has('#{ident}')") != '0' end class OxnzToolkit def initialize end def msg lvl = 'normal', msg msg = '"' + msg + '"' case lvl when 'normal' VIM::command "echo #{msg}" when 'warning' VIM::command "echohl WarningMsg | echo #{msg} | echohl None" when 'error' VIM::command "echohl ErrorMsg | echo #{msg} | echohl None" else msg 'error', "invalid message level: #{lvl}, message: #{msg}" end end def : def rubyinfo msg %{Ruby Info: Version: #{RUBY_VERSION} Platform: #{RUBY_PLATFORM} Release Date: #{RUBY_RELEASE_DATE}} end def errcnf command fail ArgumentError, "command not found: #{command}" end def cmd name commands = { rubyinfo: ->{rubyinfo}, } commands[name.to_sym] or errcnf cmd end def eva expr VIM::evaluate expr end def do name = eva 'a:cmd' args = eva 'a:000' cmd = cmd name if args.length == 0 cmd.call else cmd.call args end end end if __FILE__ == $0 or 'vim-ruby' == $0 begin OxnzToolkit.new.do rescue Interrupt => e $stderr.puts "Interrupted" rescue => e $stderr.puts "#{$0}: #{e}" rescue raise end end
{ "content_hash": "62ed08493e1a380890b4aad8797151a2", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 64, "avg_line_length": 17.771428571428572, "alnum_prop": 0.6302250803858521, "repo_name": "zzqrjcode/dot-files", "id": "b92243865836475c9fb4bc7203e8c65720df6598", "size": "2542", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "vim/plugin/OxnzToolkit.rb", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "16" }, { "name": "Emacs Lisp", "bytes": "15736" }, { "name": "Perl", "bytes": "4098" }, { "name": "Python", "bytes": "51003" }, { "name": "Ruby", "bytes": "2542" }, { "name": "Shell", "bytes": "2592" }, { "name": "VimL", "bytes": "67451" } ], "symlink_target": "" }
require File.expand_path('../boot', __FILE__) # Pick the frameworks you want: require "active_model/railtie" require "active_job/railtie" require "active_record/railtie" require "action_controller/railtie" require "action_mailer/railtie" require "action_view/railtie" require "sprockets/railtie" # require "rails/test_unit/railtie" # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module RailsSpeech class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de # Do not swallow errors in after_commit/after_rollback callbacks. config.active_record.raise_in_transactional_callbacks = true end end
{ "content_hash": "302fc52d7e88e70cc4b8208f5a769ae1", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 99, "avg_line_length": 40.705882352941174, "alnum_prop": 0.736271676300578, "repo_name": "gouf/rails_speech_download_sample", "id": "4401c9ef0e35c3ee96a24175a2265eae787f6c93", "size": "1384", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "config/application.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1889" }, { "name": "CoffeeScript", "bytes": "211" }, { "name": "HTML", "bytes": "5751" }, { "name": "JavaScript", "bytes": "667" }, { "name": "Ruby", "bytes": "44523" } ], "symlink_target": "" }
package com.graphhopper.coll; import com.carrotsearch.hppc.cursors.IntCursor; import java.util.Iterator; /** * Implements the bitset interface via a hash set. It is more efficient for only a few entries. * <p> * * @author Peter Karich */ public class GHTBitSet implements GHBitSet { private final GHIntHashSet tHash; public GHTBitSet(GHIntHashSet set) { tHash = set; } public GHTBitSet(int no) { tHash = new GHIntHashSet(no, 0.7f); } public GHTBitSet() { this(1000); } @Override public final boolean contains(int index) { return tHash.contains(index); } @Override public final void add(int index) { tHash.add(index); } @Override public final String toString() { return tHash.toString(); } @Override public final int getCardinality() { return tHash.size(); } @Override public final void clear() { tHash.clear(); } @Override public void remove(int index) { tHash.remove(index); } @Override public final GHBitSet copyTo(GHBitSet bs) { bs.clear(); if (bs instanceof GHTBitSet) { ((GHTBitSet) bs).tHash.addAll(this.tHash); } else { Iterator<IntCursor> iter = tHash.iterator(); while (iter.hasNext()) { bs.add(iter.next().value); } } return bs; } @Override public int next(int index) { throw new UnsupportedOperationException("Not supported yet."); } }
{ "content_hash": "105c5d0f2aee3d26119491632e832e21", "timestamp": "", "source": "github", "line_count": 77, "max_line_length": 95, "avg_line_length": 20.454545454545453, "alnum_prop": 0.5841269841269842, "repo_name": "prembasumatary/graphhopper", "id": "56d4bcf82ca4dfad3aed37e31723349f1f68beb1", "size": "2385", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "core/src/main/java/com/graphhopper/coll/GHTBitSet.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "23322" }, { "name": "HTML", "bytes": "7785" }, { "name": "Java", "bytes": "2045819" }, { "name": "JavaScript", "bytes": "227020" }, { "name": "Shell", "bytes": "12460" } ], "symlink_target": "" }
/*********************************************************************/ /* Copyright (c) 2011 - 2012, The University of Texas at Austin. */ /* 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 UNIVERSITY OF TEXAS AT */ /* AUSTIN ``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 UNIVERSITY OF TEXAS AT */ /* AUSTIN 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. */ /* */ /* The views and conclusions contained in the software and */ /* documentation are those of the authors and should not be */ /* interpreted as representing official policies, either expressed */ /* or implied, of The University of Texas at Austin. */ /*********************************************************************/ #include "NetworkListenerThread.h" // increment this every time the network protocol changes in a major way #include "NetworkProtocol.h" #include "PixelStream.h" #include "log.h" #include <stdint.h> #define RECEIVE_TIMEOUT_MS 3000 NetworkListenerThread::NetworkListenerThread(int socketDescriptor) : socketDescriptor_(socketDescriptor) , tcpSocket_(new QTcpSocket(this)) // Make sure that tcpSocket_ parent is *this* so it also gets moved to thread! , registeredToEvents_(false) { if( !tcpSocket_->setSocketDescriptor(socketDescriptor_) ) { put_flog(LOG_ERROR, "could not set socket descriptor: %s", tcpSocket_->errorString().toStdString().c_str()); emit(finished()); return; } connect(tcpSocket_, SIGNAL(disconnected()), this, SIGNAL(finished())); connect(tcpSocket_, SIGNAL(readyRead()), this, SLOT(process()), Qt::QueuedConnection); connect(this, SIGNAL(dataAvailable()), this, SLOT(process()), Qt::QueuedConnection); } NetworkListenerThread::~NetworkListenerThread() { put_flog(LOG_DEBUG, ""); // If the sender crashed, we may not recieve the quit message. // We still want to remove this source so that the stream does not get stuck if other // senders are still active / resp. the window gets closed if no more senders contribute to it. if (!pixelStreamUri_.isEmpty()) emit receivedRemovePixelStreamSource(pixelStreamUri_, socketDescriptor_); if( tcpSocket_->state() == QAbstractSocket::ConnectedState ) sendQuit(); delete tcpSocket_; } void NetworkListenerThread::initialize() { sendProtocolVersion(); } void NetworkListenerThread::process() { if(tcpSocket_->bytesAvailable() >= qint64(MessageHeader::serializedSize)) { socketReceiveMessage(); } // send events if needed foreach (const Event& event, events_) { send(event); } events_.clear(); // flush the socket tcpSocket_->flush(); // Finish reading messages from the socket if connection closed if(tcpSocket_->state() != QAbstractSocket::ConnectedState) { while (tcpSocket_->bytesAvailable() >= qint64(MessageHeader::serializedSize)) { socketReceiveMessage(); } emit(finished()); } else if (tcpSocket_->bytesAvailable() >= qint64(MessageHeader::serializedSize)) { emit dataAvailable(); } } void NetworkListenerThread::socketReceiveMessage() { // first, read the message header MessageHeader mh = receiveMessageHeader(); // next, read the actual message QByteArray messageByteArray = receiveMessageBody(mh.size); // got the message handleMessage(mh, messageByteArray); } MessageHeader NetworkListenerThread::receiveMessageHeader() { MessageHeader messageHeader; QDataStream stream(tcpSocket_); stream >> messageHeader; return messageHeader; } QByteArray NetworkListenerThread::receiveMessageBody(const int size) { // next, read the actual message QByteArray messageByteArray; if(size > 0) { messageByteArray = tcpSocket_->read(size); while(messageByteArray.size() < size) { if (!tcpSocket_->waitForReadyRead(RECEIVE_TIMEOUT_MS)) { emit finished(); return QByteArray(); } messageByteArray.append(tcpSocket_->read(size - messageByteArray.size())); } } return messageByteArray; } void NetworkListenerThread::processEvent(Event event) { events_.enqueue(event); emit dataAvailable(); } void NetworkListenerThread::handleMessage(const MessageHeader& messageHeader, const QByteArray& byteArray) { const QString uri(messageHeader.uri); switch(messageHeader.type) { case MESSAGE_TYPE_QUIT: if (pixelStreamUri_ == uri) { emit receivedRemovePixelStreamSource(uri, socketDescriptor_); pixelStreamUri_ = QString(); } break; case MESSAGE_TYPE_PIXELSTREAM_OPEN: if (pixelStreamUri_.isEmpty()) { pixelStreamUri_ = uri; emit receivedAddPixelStreamSource(uri, socketDescriptor_); } break; case MESSAGE_TYPE_PIXELSTREAM_FINISH_FRAME: if (pixelStreamUri_ == uri) { emit receivedPixelStreamFinishFrame(uri, socketDescriptor_); } break; case MESSAGE_TYPE_PIXELSTREAM: handlePixelStreamMessage(uri, byteArray); break; case MESSAGE_TYPE_COMMAND: emit receivedCommand(QString(byteArray.data()), uri); break; case MESSAGE_TYPE_BIND_EVENTS: case MESSAGE_TYPE_BIND_EVENTS_EX: if (registeredToEvents_) { put_flog(LOG_DEBUG, "We are already bound!!"); } else { const bool eventRegistrationExclusive = (messageHeader.type == MESSAGE_TYPE_BIND_EVENTS_EX); emit registerToEvents(pixelStreamUri_, eventRegistrationExclusive, this); } break; default: break; } } void NetworkListenerThread::handlePixelStreamMessage(const QString& uri, const QByteArray& byteArray) { const PixelStreamSegmentParameters* parameters = (const PixelStreamSegmentParameters *)(byteArray.data()); PixelStreamSegment segment; segment.parameters = *parameters; // read image data QByteArray imageData = byteArray.right(byteArray.size() - sizeof(PixelStreamSegmentParameters)); segment.imageData = imageData; if (pixelStreamUri_ == uri) { emit(receivedPixelStreamSegement(uri, socketDescriptor_, segment)); } else { put_flog(LOG_INFO, "received PixelStreamSegement from incorrect uri: %s", uri.toLocal8Bit().constData()); } } void NetworkListenerThread::pixelStreamerClosed(QString uri) { if (uri == pixelStreamUri_) { emit(finished()); } } void NetworkListenerThread::eventRegistrationReply(QString uri, bool success) { if (uri == pixelStreamUri_) { registeredToEvents_ = success; sendBindReply( registeredToEvents_ ); } } void NetworkListenerThread::sendProtocolVersion() { const int32_t protocolVersion = NETWORK_PROTOCOL_VERSION; tcpSocket_->write((char *)&protocolVersion, sizeof(int32_t)); tcpSocket_->flush(); while(tcpSocket_->bytesToWrite() > 0) { tcpSocket_->waitForBytesWritten(); } } void NetworkListenerThread::sendBindReply(const bool successful) { // send message header MessageHeader mh(MESSAGE_TYPE_BIND_EVENTS_REPLY, sizeof(bool)); send(mh); tcpSocket_->write((const char *)&successful, sizeof(bool)); // we want the message to be sent immediately tcpSocket_->flush(); while(tcpSocket_->bytesToWrite() > 0) { tcpSocket_->waitForBytesWritten(); } } void NetworkListenerThread::send(const Event& event) { // send message header MessageHeader mh(MESSAGE_TYPE_EVENT, Event::serializedSize); send(mh); { QDataStream stream(tcpSocket_); stream << event; } // we want the message to be sent immediately tcpSocket_->flush(); while(tcpSocket_->bytesToWrite() > 0) { tcpSocket_->waitForBytesWritten(); } } void NetworkListenerThread::sendQuit() { MessageHeader mh(MESSAGE_TYPE_QUIT, 0); send(mh); // we want the message to be sent immediately tcpSocket_->flush(); while(tcpSocket_->bytesToWrite() > 0) { tcpSocket_->waitForBytesWritten(); } } bool NetworkListenerThread::send(const MessageHeader& messageHeader) { QDataStream stream(tcpSocket_); stream << messageHeader; return stream.status() == QDataStream::Ok; }
{ "content_hash": "c76aaca905c2b6e987ed09b7dba24dca", "timestamp": "", "source": "github", "line_count": 336, "max_line_length": 117, "avg_line_length": 30.976190476190474, "alnum_prop": 0.6119331283627979, "repo_name": "shuaibarshad/KAUST-DisplayCluster", "id": "ce1d2996af424ed8c7a5e94f06328ec431a961b7", "size": "10408", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/core/NetworkListenerThread.cpp", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C", "bytes": "15548" }, { "name": "C++", "bytes": "1523018" }, { "name": "CSS", "bytes": "11873" }, { "name": "JavaScript", "bytes": "3333" }, { "name": "Objective-C", "bytes": "3692" }, { "name": "Python", "bytes": "97582" } ], "symlink_target": "" }
use std::fmt::Debug; use std::f64::consts::PI; pub trait ActivationFunction: Clone + Debug + Send + Sized + PartialEq + Eq { fn formula_gnuplot(&self, x: String) -> String; fn name(&self) -> String; fn calculate(&self, x: f64) -> f64; } #[inline(always)] fn bipolar_debug_check(x: f64) -> f64 { debug_assert!(x >= -1.0 && x <= 1.0); x } /// Clips the value of `x` into the range [-1, 1]. fn bipolar_clip(x: f64) -> f64 { if x > 1.0 { 1.0 } else if x < -1.0 { -1.0 } else { x } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub enum GeometricActivationFunction { Linear, LinearBipolarClipped, LinearClipped, Absolute, Gaussian, BipolarGaussian, BipolarSigmoid, Sine, Cosine, Constant1, } impl ActivationFunction for GeometricActivationFunction { fn calculate(&self, x: f64) -> f64 { match *self { GeometricActivationFunction::Linear => x, GeometricActivationFunction::LinearBipolarClipped => { bipolar_debug_check(bipolar_clip(x)) } GeometricActivationFunction::LinearClipped => x.min(1.0).max(0.0), GeometricActivationFunction::Absolute => x.abs(), GeometricActivationFunction::Gaussian => (-((x * 2.5).powi(2))).exp(), GeometricActivationFunction::BipolarGaussian => { bipolar_debug_check(2.0 * (-((x * 2.5).powi(2))).exp() - 1.0) } GeometricActivationFunction::BipolarSigmoid => { bipolar_debug_check((2.0 / (1.0 + (-4.9 * x).exp())) - 1.0) } GeometricActivationFunction::Sine => bipolar_debug_check((2.0 * PI * x).sin()), GeometricActivationFunction::Cosine => bipolar_debug_check(2.0 * PI * x.cos()), GeometricActivationFunction::Constant1 => 1.0, } } fn formula_gnuplot(&self, x: String) -> String { match *self { GeometricActivationFunction::Linear => format!("{}", x), GeometricActivationFunction::LinearBipolarClipped => { format!("max(-1.0, min(1.0, {}))", x) } GeometricActivationFunction::LinearClipped => format!("max(0.0, min(1.0, {}))", x), GeometricActivationFunction::Absolute => format!("abs({})", x), GeometricActivationFunction::Gaussian => format!("(exp(-((({}) * 2.5)**2.0))", x), GeometricActivationFunction::BipolarGaussian => { format!("2.0 * exp(-((({}) * 2.5)**2.0)) - 1.0", x) } GeometricActivationFunction::BipolarSigmoid => { format!("2.0 / (1.0 + exp(-4.9 * ({}))) - 1.0", x) } GeometricActivationFunction::Sine => format!("sin({})", x), GeometricActivationFunction::Cosine => format!("cos({})", x), GeometricActivationFunction::Constant1 => format!("1.0"), } } fn name(&self) -> String { match *self { GeometricActivationFunction::Linear => "Linear", GeometricActivationFunction::LinearBipolarClipped => "LinearBipolarClipped", GeometricActivationFunction::LinearClipped => "LinearClipped", GeometricActivationFunction::Absolute => "Absolute", GeometricActivationFunction::Gaussian => "Gaussian", GeometricActivationFunction::BipolarGaussian => "BipolarGaussian", GeometricActivationFunction::BipolarSigmoid => "BipolarSigmoid", GeometricActivationFunction::Sine => "Sine", GeometricActivationFunction::Cosine => "Consine", GeometricActivationFunction::Constant1 => "1.0", }.to_string() } } #[test] fn test_bipolar_linear_clipped() { assert_eq!( 0.0, GeometricActivationFunction::LinearBipolarClipped.calculate(0.0) ); assert_eq!( 1.0, GeometricActivationFunction::LinearBipolarClipped.calculate(1.0) ); assert_eq!( -1.0, GeometricActivationFunction::LinearBipolarClipped.calculate(-1.0) ); assert_eq!( 0.5, GeometricActivationFunction::LinearBipolarClipped.calculate(0.5) ); assert_eq!( -0.5, GeometricActivationFunction::LinearBipolarClipped.calculate(-0.5) ); assert_eq!( 1.0, GeometricActivationFunction::LinearBipolarClipped.calculate(1.1) ); assert_eq!( -1.0, GeometricActivationFunction::LinearBipolarClipped.calculate(-1.1) ); } #[test] fn test_linear_clipped() { assert_eq!( 0.0, GeometricActivationFunction::LinearClipped.calculate(0.0) ); assert_eq!( 1.0, GeometricActivationFunction::LinearClipped.calculate(1.0) ); assert_eq!( 0.0, GeometricActivationFunction::LinearClipped.calculate(-1.0) ); assert_eq!( 0.5, GeometricActivationFunction::LinearClipped.calculate(0.5) ); assert_eq!( 0.0, GeometricActivationFunction::LinearClipped.calculate(-0.5) ); assert_eq!( 1.0, GeometricActivationFunction::LinearClipped.calculate(1.1) ); assert_eq!( 0.0, GeometricActivationFunction::LinearClipped.calculate(-1.1) ); } #[test] fn test_constant1() { assert_eq!(1.0, GeometricActivationFunction::Constant1.calculate(0.0)); assert_eq!(1.0, GeometricActivationFunction::Constant1.calculate(-1.0)); assert_eq!(1.0, GeometricActivationFunction::Constant1.calculate(1.0)); }
{ "content_hash": "44bf4ed49918647f42067104260c7f64", "timestamp": "", "source": "github", "line_count": 170, "max_line_length": 95, "avg_line_length": 33.088235294117645, "alnum_prop": 0.5898666666666667, "repo_name": "mneumann/cppn-rs", "id": "98c6c682b3171c4ce42cff22190e869080f3d76d", "size": "5625", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/activation_function.rs", "mode": "33188", "license": "mit", "language": [ { "name": "Rust", "bytes": "31547" } ], "symlink_target": "" }
export { default } from './RadioButton.js';
{ "content_hash": "d4aab4fd477e574082d4996cdebdeea0", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 43, "avg_line_length": 44, "alnum_prop": 0.6818181818181818, "repo_name": "wix/wix-style-react", "id": "f0fc8d2503d96a6ea39851a8d31d1a2e99daf450", "size": "44", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "packages/wix-style-react/src/RadioGroup/RadioButton/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "325595" }, { "name": "HTML", "bytes": "20584" }, { "name": "JavaScript", "bytes": "4465095" }, { "name": "Shell", "bytes": "4264" }, { "name": "TypeScript", "bytes": "219813" } ], "symlink_target": "" }
package org.apache.hadoop.yarn.client.api.impl; import com.google.common.annotations.VisibleForTesting; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.classification.InterfaceAudience.Private; import org.apache.hadoop.classification.InterfaceStability.Unstable; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.Text; import org.apache.hadoop.ipc.RPC; import org.apache.hadoop.yarn.api.ApplicationClientProtocol; import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationAttemptReportRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationAttemptReportResponse; import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationAttemptsRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationAttemptsResponse; import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationReportRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationReportResponse; import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationsRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationsResponse; import org.apache.hadoop.yarn.api.protocolrecords.GetClusterMetricsRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetClusterMetricsResponse; import org.apache.hadoop.yarn.api.protocolrecords.GetClusterNodesRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetClusterNodesResponse; import org.apache.hadoop.yarn.api.protocolrecords.GetContainerReportRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetContainerReportResponse; import org.apache.hadoop.yarn.api.protocolrecords.GetContainersRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetContainersResponse; import org.apache.hadoop.yarn.api.protocolrecords.GetDelegationTokenRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetDelegationTokenResponse; import org.apache.hadoop.yarn.api.protocolrecords.GetNewApplicationRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetNewApplicationResponse; import org.apache.hadoop.yarn.api.protocolrecords.GetQueueInfoRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetQueueUserAclsInfoRequest; import org.apache.hadoop.yarn.api.protocolrecords.KillApplicationRequest; import org.apache.hadoop.yarn.api.protocolrecords.KillApplicationResponse; import org.apache.hadoop.yarn.api.protocolrecords.MoveApplicationAcrossQueuesRequest; import org.apache.hadoop.yarn.api.protocolrecords.SubmitApplicationRequest; import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; import org.apache.hadoop.yarn.api.records.ApplicationAttemptReport; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.ApplicationReport; import org.apache.hadoop.yarn.api.records.ApplicationSubmissionContext; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.api.records.ContainerReport; import org.apache.hadoop.yarn.api.records.NodeReport; import org.apache.hadoop.yarn.api.records.NodeState; import org.apache.hadoop.yarn.api.records.QueueInfo; import org.apache.hadoop.yarn.api.records.QueueUserACLInfo; import org.apache.hadoop.yarn.api.records.Token; import org.apache.hadoop.yarn.api.records.YarnApplicationState; import org.apache.hadoop.yarn.api.records.YarnClusterMetrics; import org.apache.hadoop.yarn.client.ClientRMProxy; import org.apache.hadoop.yarn.client.api.AHSClient; import org.apache.hadoop.yarn.client.api.YarnClient; import org.apache.hadoop.yarn.client.api.YarnClientApplication; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.exceptions.ApplicationIdNotProvidedException; import org.apache.hadoop.yarn.exceptions.ApplicationNotFoundException; import org.apache.hadoop.yarn.exceptions.YarnException; import org.apache.hadoop.yarn.exceptions.YarnRuntimeException; import org.apache.hadoop.yarn.security.AMRMTokenIdentifier; import org.apache.hadoop.yarn.util.ConverterUtils; import org.apache.hadoop.yarn.util.Records; import java.io.IOException; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; import java.util.Set; @Private @Unstable public class YarnClientImpl extends YarnClient { private static final Log LOG = LogFactory.getLog(YarnClientImpl.class); protected ApplicationClientProtocol rmClient; protected long submitPollIntervalMillis; private long asyncApiPollIntervalMillis; private long asyncApiPollTimeoutMillis; protected AHSClient historyClient; private boolean historyServiceEnabled; private static final String ROOT = "root"; public YarnClientImpl() { super(YarnClientImpl.class.getName()); } @SuppressWarnings("deprecation") @Override protected void serviceInit(Configuration conf) throws Exception { asyncApiPollIntervalMillis = conf.getLong( YarnConfiguration.YARN_CLIENT_APPLICATION_CLIENT_PROTOCOL_POLL_INTERVAL_MS, YarnConfiguration.DEFAULT_YARN_CLIENT_APPLICATION_CLIENT_PROTOCOL_POLL_INTERVAL_MS); asyncApiPollTimeoutMillis = conf.getLong( YarnConfiguration.YARN_CLIENT_APPLICATION_CLIENT_PROTOCOL_POLL_TIMEOUT_MS, YarnConfiguration.DEFAULT_YARN_CLIENT_APPLICATION_CLIENT_PROTOCOL_POLL_TIMEOUT_MS); submitPollIntervalMillis = asyncApiPollIntervalMillis; if (conf .get(YarnConfiguration.YARN_CLIENT_APP_SUBMISSION_POLL_INTERVAL_MS) != null) { submitPollIntervalMillis = conf.getLong( YarnConfiguration.YARN_CLIENT_APP_SUBMISSION_POLL_INTERVAL_MS, YarnConfiguration.DEFAULT_YARN_CLIENT_APPLICATION_CLIENT_PROTOCOL_POLL_INTERVAL_MS); } if (conf.getBoolean(YarnConfiguration.APPLICATION_HISTORY_ENABLED, YarnConfiguration.DEFAULT_APPLICATION_HISTORY_ENABLED)) { historyServiceEnabled = true; historyClient = AHSClientImpl.createAHSClient(); historyClient.init(getConfig()); } super.serviceInit(conf); } @Override protected void serviceStart() throws Exception { try { rmClient = ClientRMProxy .createRMProxy(getConfig(), ApplicationClientProtocol.class); if (historyServiceEnabled) { historyClient.start(); } } catch (IOException e) { throw new YarnRuntimeException(e); } super.serviceStart(); } @Override protected void serviceStop() throws Exception { if (this.rmClient != null) { RPC.stopProxy(this.rmClient); } if (historyServiceEnabled) { historyClient.stop(); } super.serviceStop(); } private GetNewApplicationResponse getNewApplication() throws YarnException, IOException { GetNewApplicationRequest request = Records.newRecord(GetNewApplicationRequest.class); return rmClient.getNewApplication(request); } @Override public YarnClientApplication createApplication() throws YarnException, IOException { ApplicationSubmissionContext context = Records.newRecord(ApplicationSubmissionContext.class); GetNewApplicationResponse newApp = getNewApplication(); ApplicationId appId = newApp.getApplicationId(); context.setApplicationId(appId); return new YarnClientApplication(newApp, context); } @Override public ApplicationId submitApplication( ApplicationSubmissionContext appContext) throws YarnException, IOException { ApplicationId applicationId = appContext.getApplicationId(); if (applicationId == null) { throw new ApplicationIdNotProvidedException( "ApplicationId is not provided in ApplicationSubmissionContext"); } SubmitApplicationRequest request = Records.newRecord(SubmitApplicationRequest.class); request.setApplicationSubmissionContext(appContext); //TODO: YARN-1763:Handle RM failovers during the submitApplication call. rmClient.submitApplication(request); int pollCount = 0; long startTime = System.currentTimeMillis(); while (true) { try { YarnApplicationState state = getApplicationReport(applicationId).getYarnApplicationState(); if (!state.equals(YarnApplicationState.NEW) && !state.equals(YarnApplicationState.NEW_SAVING)) { LOG.info("Submitted application " + applicationId); break; } long elapsedMillis = System.currentTimeMillis() - startTime; if (enforceAsyncAPITimeout() && elapsedMillis >= asyncApiPollTimeoutMillis) { throw new YarnException("Timed out while waiting for application " + applicationId + " to be submitted successfully"); } // Notify the client through the log every 10 poll, in case the client // is blocked here too long. if (++pollCount % 10 == 0) { LOG.info("Application submission is not finished, " + "submitted application " + applicationId + " is still in " + state); } try { Thread.sleep(submitPollIntervalMillis); } catch (InterruptedException ie) { LOG.error( "Interrupted while waiting for application " + applicationId + " to be successfully submitted."); } } catch (ApplicationNotFoundException ex) { // FailOver or RM restart happens before RMStateStore saves // ApplicationState LOG.info("Re-submit application " + applicationId + "with the " + "same ApplicationSubmissionContext"); rmClient.submitApplication(request); } } return applicationId; } @Override public void killApplication(ApplicationId applicationId) throws YarnException, IOException { KillApplicationRequest request = Records.newRecord(KillApplicationRequest.class); request.setApplicationId(applicationId); try { int pollCount = 0; long startTime = System.currentTimeMillis(); while (true) { KillApplicationResponse response = rmClient.forceKillApplication(request); if (response.getIsKillCompleted()) { LOG.info("Killed application " + applicationId); break; } long elapsedMillis = System.currentTimeMillis() - startTime; if (enforceAsyncAPITimeout() && elapsedMillis >= this.asyncApiPollTimeoutMillis) { throw new YarnException("Timed out while waiting for application " + applicationId + " to be killed."); } if (++pollCount % 10 == 0) { LOG.info( "Waiting for application " + applicationId + " to be killed."); } Thread.sleep(asyncApiPollIntervalMillis); } } catch (InterruptedException e) { LOG.error("Interrupted while waiting for application " + applicationId + " to be killed."); } } @VisibleForTesting boolean enforceAsyncAPITimeout() { return asyncApiPollTimeoutMillis >= 0; } @Override public ApplicationReport getApplicationReport(ApplicationId appId) throws YarnException, IOException { GetApplicationReportResponse response = null; try { GetApplicationReportRequest request = Records.newRecord(GetApplicationReportRequest.class); request.setApplicationId(appId); response = rmClient.getApplicationReport(request); } catch (YarnException e) { if (!historyServiceEnabled) { // Just throw it as usual if historyService is not enabled. throw e; } // Even if history-service is enabled, treat all exceptions still the same // except the following if (!(e.getClass() == ApplicationNotFoundException.class)) { throw e; } return historyClient.getApplicationReport(appId); } return response.getApplicationReport(); } public org.apache.hadoop.security.token.Token<AMRMTokenIdentifier> getAMRMToken( ApplicationId appId) throws YarnException, IOException { Token token = getApplicationReport(appId).getAMRMToken(); org.apache.hadoop.security.token.Token<AMRMTokenIdentifier> amrmToken = null; if (token != null) { amrmToken = ConverterUtils.convertFromYarn(token, (Text) null); } return amrmToken; } @Override public List<ApplicationReport> getApplications() throws YarnException, IOException { return getApplications(null, null); } @Override public List<ApplicationReport> getApplications(Set<String> applicationTypes) throws YarnException, IOException { return getApplications(applicationTypes, null); } @Override public List<ApplicationReport> getApplications( EnumSet<YarnApplicationState> applicationStates) throws YarnException, IOException { return getApplications(null, applicationStates); } @Override public List<ApplicationReport> getApplications(Set<String> applicationTypes, EnumSet<YarnApplicationState> applicationStates) throws YarnException, IOException { GetApplicationsRequest request = GetApplicationsRequest.newInstance(applicationTypes, applicationStates); GetApplicationsResponse response = rmClient.getApplications(request); return response.getApplicationList(); } @Override public YarnClusterMetrics getYarnClusterMetrics() throws YarnException, IOException { GetClusterMetricsRequest request = Records.newRecord(GetClusterMetricsRequest.class); GetClusterMetricsResponse response = rmClient.getClusterMetrics(request); return response.getClusterMetrics(); } @Override public List<NodeReport> getNodeReports(NodeState... states) throws YarnException, IOException { EnumSet<NodeState> statesSet = (states.length == 0) ? EnumSet.allOf(NodeState.class) : EnumSet.noneOf(NodeState.class); for (NodeState state : states) { statesSet.add(state); } GetClusterNodesRequest request = GetClusterNodesRequest.newInstance(statesSet); GetClusterNodesResponse response = rmClient.getClusterNodes(request); return response.getNodeReports(); } @Override public Token getRMDelegationToken(Text renewer) throws YarnException, IOException { /* get the token from RM */ GetDelegationTokenRequest rmDTRequest = Records.newRecord(GetDelegationTokenRequest.class); rmDTRequest.setRenewer(renewer.toString()); GetDelegationTokenResponse response = rmClient.getDelegationToken(rmDTRequest); return response.getRMDelegationToken(); } private GetQueueInfoRequest getQueueInfoRequest(String queueName, boolean includeApplications, boolean includeChildQueues, boolean recursive) { GetQueueInfoRequest request = Records.newRecord(GetQueueInfoRequest.class); request.setQueueName(queueName); request.setIncludeApplications(includeApplications); request.setIncludeChildQueues(includeChildQueues); request.setRecursive(recursive); return request; } @Override public QueueInfo getQueueInfo(String queueName) throws YarnException, IOException { GetQueueInfoRequest request = getQueueInfoRequest(queueName, true, false, false); Records.newRecord(GetQueueInfoRequest.class); return rmClient.getQueueInfo(request).getQueueInfo(); } @Override public List<QueueUserACLInfo> getQueueAclsInfo() throws YarnException, IOException { GetQueueUserAclsInfoRequest request = Records.newRecord(GetQueueUserAclsInfoRequest.class); return rmClient.getQueueUserAcls(request).getUserAclsInfoList(); } @Override public List<QueueInfo> getAllQueues() throws YarnException, IOException { List<QueueInfo> queues = new ArrayList<QueueInfo>(); QueueInfo rootQueue = rmClient.getQueueInfo(getQueueInfoRequest(ROOT, false, true, true)) .getQueueInfo(); getChildQueues(rootQueue, queues, true); return queues; } @Override public List<QueueInfo> getRootQueueInfos() throws YarnException, IOException { List<QueueInfo> queues = new ArrayList<QueueInfo>(); QueueInfo rootQueue = rmClient.getQueueInfo(getQueueInfoRequest(ROOT, false, true, true)) .getQueueInfo(); getChildQueues(rootQueue, queues, false); return queues; } @Override public List<QueueInfo> getChildQueueInfos(String parent) throws YarnException, IOException { List<QueueInfo> queues = new ArrayList<QueueInfo>(); QueueInfo parentQueue = rmClient.getQueueInfo(getQueueInfoRequest(parent, false, true, false)) .getQueueInfo(); getChildQueues(parentQueue, queues, true); return queues; } private void getChildQueues(QueueInfo parent, List<QueueInfo> queues, boolean recursive) { List<QueueInfo> childQueues = parent.getChildQueues(); for (QueueInfo child : childQueues) { queues.add(child); if (recursive) { getChildQueues(child, queues, recursive); } } } @Private @VisibleForTesting public void setRMClient(ApplicationClientProtocol rmClient) { this.rmClient = rmClient; } @Override public ApplicationAttemptReport getApplicationAttemptReport( ApplicationAttemptId appAttemptId) throws YarnException, IOException { try { GetApplicationAttemptReportRequest request = Records.newRecord(GetApplicationAttemptReportRequest.class); request.setApplicationAttemptId(appAttemptId); GetApplicationAttemptReportResponse response = rmClient.getApplicationAttemptReport(request); return response.getApplicationAttemptReport(); } catch (YarnException e) { if (!historyServiceEnabled) { // Just throw it as usual if historyService is not enabled. throw e; } // Even if history-service is enabled, treat all exceptions still the same // except the following if (e.getClass() != ApplicationNotFoundException.class) { throw e; } return historyClient.getApplicationAttemptReport(appAttemptId); } } @Override public List<ApplicationAttemptReport> getApplicationAttempts( ApplicationId appId) throws YarnException, IOException { try { GetApplicationAttemptsRequest request = Records.newRecord(GetApplicationAttemptsRequest.class); request.setApplicationId(appId); GetApplicationAttemptsResponse response = rmClient.getApplicationAttempts(request); return response.getApplicationAttemptList(); } catch (YarnException e) { if (!historyServiceEnabled) { // Just throw it as usual if historyService is not enabled. throw e; } // Even if history-service is enabled, treat all exceptions still the same // except the following if (e.getClass() != ApplicationNotFoundException.class) { throw e; } return historyClient.getApplicationAttempts(appId); } } @Override public ContainerReport getContainerReport(ContainerId containerId) throws YarnException, IOException { try { GetContainerReportRequest request = Records.newRecord(GetContainerReportRequest.class); request.setContainerId(containerId); GetContainerReportResponse response = rmClient.getContainerReport(request); return response.getContainerReport(); } catch (YarnException e) { if (!historyServiceEnabled) { // Just throw it as usual if historyService is not enabled. throw e; } // Even if history-service is enabled, treat all exceptions still the same // except the following if (e.getClass() != ApplicationNotFoundException.class) { throw e; } return historyClient.getContainerReport(containerId); } } @Override public List<ContainerReport> getContainers( ApplicationAttemptId applicationAttemptId) throws YarnException, IOException { try { GetContainersRequest request = Records.newRecord(GetContainersRequest.class); request.setApplicationAttemptId(applicationAttemptId); GetContainersResponse response = rmClient.getContainers(request); return response.getContainerList(); } catch (YarnException e) { if (!historyServiceEnabled) { // Just throw it as usual if historyService is not enabled. throw e; } // Even if history-service is enabled, treat all exceptions still the same // except the following if (e.getClass() != ApplicationNotFoundException.class) { throw e; } return historyClient.getContainers(applicationAttemptId); } } @Override public void moveApplicationAcrossQueues(ApplicationId appId, String queue) throws YarnException, IOException { MoveApplicationAcrossQueuesRequest request = MoveApplicationAcrossQueuesRequest.newInstance(appId, queue); rmClient.moveApplicationAcrossQueues(request); } }
{ "content_hash": "ebbac4180c7ff8ae11c9822424e59e21", "timestamp": "", "source": "github", "line_count": 552, "max_line_length": 94, "avg_line_length": 37.8731884057971, "alnum_prop": 0.7369654644599637, "repo_name": "srijeyanthan/hops", "id": "d9c9d467c2bdd90367335caa95c7a8c13864d9ea", "size": "21712", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/api/impl/YarnClientImpl.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AspectJ", "bytes": "31146" }, { "name": "Batchfile", "bytes": "49561" }, { "name": "C", "bytes": "1065087" }, { "name": "C++", "bytes": "81364" }, { "name": "CMake", "bytes": "32686" }, { "name": "CSS", "bytes": "42221" }, { "name": "HTML", "bytes": "2031435" }, { "name": "Java", "bytes": "36323051" }, { "name": "JavaScript", "bytes": "4688" }, { "name": "Perl", "bytes": "18992" }, { "name": "Protocol Buffer", "bytes": "147182" }, { "name": "Python", "bytes": "11309" }, { "name": "Shell", "bytes": "159501" }, { "name": "TeX", "bytes": "19322" }, { "name": "XSLT", "bytes": "36114" } ], "symlink_target": "" }
FROM balenalib/photon-xavier-nx-debian:sid-build # remove several traces of debian python RUN apt-get purge -y python.* # http://bugs.python.org/issue19846 # > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK. ENV LANG C.UTF-8 # key 63C7CC90: public key "Simon McVittie <smcv@pseudorandom.co.uk>" imported # key 3372DCFA: public key "Donald Stufft (dstufft) <donald@stufft.io>" imported RUN gpg --batch --keyserver keyring.debian.org --recv-keys 4DE8FF2A63C7CC90 \ && gpg --batch --keyserver keyserver.ubuntu.com --recv-key 6E3CBCE93372DCFA \ && gpg --batch --keyserver keyserver.ubuntu.com --recv-keys 0x52a43a1e4b77b059 ENV PYTHON_VERSION 3.9.10 # if this is called "PIP_VERSION", pip explodes with "ValueError: invalid truth value '<VERSION>'" ENV PYTHON_PIP_VERSION 21.3.1 ENV SETUPTOOLS_VERSION 60.5.4 RUN set -x \ && curl -SLO "http://resin-packages.s3.amazonaws.com/python/v$PYTHON_VERSION/Python-$PYTHON_VERSION.linux-aarch64-libffi3.3.tar.gz" \ && echo "2a4413484a3a61acc537cc11b0c96d5a11cee79b14fe8558ffdde8049f025fd4 Python-$PYTHON_VERSION.linux-aarch64-libffi3.3.tar.gz" | sha256sum -c - \ && tar -xzf "Python-$PYTHON_VERSION.linux-aarch64-libffi3.3.tar.gz" --strip-components=1 \ && rm -rf "Python-$PYTHON_VERSION.linux-aarch64-libffi3.3.tar.gz" \ && ldconfig \ && if [ ! -e /usr/local/bin/pip3 ]; then : \ && curl -SLO "https://raw.githubusercontent.com/pypa/get-pip/430ba37776ae2ad89f794c7a43b90dc23bac334c/get-pip.py" \ && echo "19dae841a150c86e2a09d475b5eb0602861f2a5b7761ec268049a662dbd2bd0c get-pip.py" | sha256sum -c - \ && python3 get-pip.py \ && rm get-pip.py \ ; fi \ && pip3 install --no-cache-dir --upgrade --force-reinstall pip=="$PYTHON_PIP_VERSION" setuptools=="$SETUPTOOLS_VERSION" \ && find /usr/local \ \( -type d -a -name test -o -name tests \) \ -o \( -type f -a -name '*.pyc' -o -name '*.pyo' \) \ -exec rm -rf '{}' + \ && cd / \ && rm -rf /usr/src/python ~/.cache # install "virtualenv", since the vast majority of users of this image will want it RUN pip3 install --no-cache-dir virtualenv ENV PYTHON_DBUS_VERSION 1.2.18 # install dbus-python dependencies RUN apt-get update && apt-get install -y --no-install-recommends \ libdbus-1-dev \ libdbus-glib-1-dev \ && rm -rf /var/lib/apt/lists/* \ && apt-get -y autoremove # install dbus-python RUN set -x \ && mkdir -p /usr/src/dbus-python \ && curl -SL "http://dbus.freedesktop.org/releases/dbus-python/dbus-python-$PYTHON_DBUS_VERSION.tar.gz" -o dbus-python.tar.gz \ && curl -SL "http://dbus.freedesktop.org/releases/dbus-python/dbus-python-$PYTHON_DBUS_VERSION.tar.gz.asc" -o dbus-python.tar.gz.asc \ && gpg --verify dbus-python.tar.gz.asc \ && tar -xzC /usr/src/dbus-python --strip-components=1 -f dbus-python.tar.gz \ && rm dbus-python.tar.gz* \ && cd /usr/src/dbus-python \ && PYTHON_VERSION=$(expr match "$PYTHON_VERSION" '\([0-9]*\.[0-9]*\)') ./configure \ && make -j$(nproc) \ && make install -j$(nproc) \ && cd / \ && rm -rf /usr/src/dbus-python # make some useful symlinks that are expected to exist RUN cd /usr/local/bin \ && ln -sf pip3 pip \ && { [ -e easy_install ] || ln -s easy_install-* easy_install; } \ && ln -sf idle3 idle \ && ln -sf pydoc3 pydoc \ && ln -sf python3 python \ && ln -sf python3-config python-config # set PYTHONPATH to point to dist-packages ENV PYTHONPATH /usr/lib/python3/dist-packages:$PYTHONPATH CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@python.sh" \ && echo "Running test-stack@python" \ && chmod +x test-stack@python.sh \ && bash test-stack@python.sh \ && rm -rf test-stack@python.sh RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v8 \nOS: Debian Sid \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nPython v3.9.10, Pip v21.3.1, Setuptools v60.5.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
{ "content_hash": "9498d7f8ae828ea3752302cdb78db7c2", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 708, "avg_line_length": 50.873684210526314, "alnum_prop": 0.7032898820608318, "repo_name": "resin-io-library/base-images", "id": "e298bca115bc34d91a76b40f0f78ac31f2a47d9d", "size": "4854", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "balena-base-images/python/photon-xavier-nx/debian/sid/3.9.10/build/Dockerfile", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "71234697" }, { "name": "JavaScript", "bytes": "13096" }, { "name": "Shell", "bytes": "12051936" }, { "name": "Smarty", "bytes": "59789" } ], "symlink_target": "" }
package net.sourceforge.thegreymenstool.dao; import net.sourceforge.thegreymenstool.domain.ActivityType; import net.sourceforge.thegreymenstool.domain.Project; /** * Data access object for {@link Project} related access. * * @author bruelle * */ public interface ActivityTypeDao extends NamedObjectDao<ActivityType>{ }
{ "content_hash": "b8e7b59269d0dffb2440bc83dd510bef", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 70, "avg_line_length": 26.153846153846153, "alnum_prop": 0.7617647058823529, "repo_name": "bruelle/greymenstool", "id": "53b491a63a8ac53c1930c29d1b0e6574d5f64b14", "size": "340", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "TheGreyMensTool/src/main/java/net/sourceforge/thegreymenstool/dao/ActivityTypeDao.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "D", "bytes": "690" }, { "name": "Java", "bytes": "45066" } ], "symlink_target": "" }
An Android library that scans for Bluetooth Low Energy beacons, parses them into known entities, and provides interfaces to them to the application. It can recognize the following beacon formats: - Eddystone: URL, UID, EID, Telemetry, encrypted TLM - iBeacon, AltBeacon - Estimote Nearable - URIBeacon - any other generic BLE devices. Unlike other SDK's out there, it has the following benefits: - it's not tied or locked-in to a specific beacon manufacturer or protocol - supports rotating MAC addresses, for beacons that are identifiable otherwise (iBeacon, Eddystone UID, Nearable...) - doesn't require any developer account (unless you plan to use the cloud features, ofcourse) - uses optimized parsing, saving battery life: no memory allocations occur while scanning the same beacons over time, and native Android 5.0 BLE API is used when available. For iBeacon devices, there's also the optional **onebeacon-android-cloud** library, which allows attaching generic data to a beacon and synchronizing it to the cloud, namespaced to your own application package. It can be used to make beacons a data input source in your apps without the need of a dedicated web-service. ## How do I get started? Clone this repository and check out the samples. The library is provided as a local Maven repository and the samples are ready to build as they are. ## Quick API help Check the base-service sample and examine the **onebeacon-android** classes in your favorite IDE. There is a JavaDoc archive right next to the library, in case it's not picked up automatically you can attach it yourself. ### Interfaces to beacon sub-types - **Beacon** - base entity, having address, RSSI, samples count, and potential generic data - **EddystoneTelemetry** / **EddystoneEncryptedTLM** - telemetry info - **Rangeable** - a beacon that supports ranging and distance estimation - all Eddystone frame types: ***EddystoneEID*** / ***EddystoneUID*** / ***EddystoneURL*** - **Apple_iBeacon** - a rangeable that contains a UUID, a major ID and a minor ID - ***Nearable*** ### Monitors and beacons A Monitor is responsible for dispatching back beacon events to your caller. You just set the desired callbacks on it, and start it, handling the callbacks, seeing if you already know about that beacon, what has happened to it, and so on. A wrapper around this is the ***BeaconsMonitor*** utility class, which will provide you with a set of detected beacons, and translate back beacon events to more discrete methods which you can override. To create and start a ***BeaconsMonitor*** all you have to do is subclass it and instantiate it with the current context. It literally takes a single line of code in your app to make it beacon-aware! ### How to do "ranging" and "filtering" like on iOS? Ranging is simply done by handling the ***onBeaconChangedRange*** event on your BeaconsMonitor subclass. Since it sends out a Rangeable entity, you can check its previous range and the current range to emulate iOS's entering/exiting zones. Filtering is not relevant under Android, because the native LE scanner will find always find and report all detected BLE packets for iBeacon or other custom beacon types, and it is not so useful to try and filter at that level. Instead, you should just ignore the beacons that you are not interested in, based on either their type or their properties. ## Library design The library consists of: - a background service that has two roles: - provider: does background LE scanning, parses data of discovered packets, manages beacons lifecycle; - client: communicates with the best provider available, and back to the app through the public API Usually the client and server are in the same process, so the data flows directly from the service back to the application, but IPC is supported if there's more than one app installed, signed with the same key and having the same declared special permission value. - an optimized packet parsing engine - implementations of Parcelable beacon types, each exposing its own API through an interface. - a simple but powerful API that allows easily creating a Beacons Monitor and simply receiving callbacks when they are found or something about them changes (like their computed Range, estimated distance, RSSI, etc) ## How much battery does the scanning eat? The scanning power consumption is optimized natively when running on Android 5.0 or newer, and emulated on older Android versions by pausing the scan. The SDK offers the possibility to change the current scanning mode between: - low power (background mode) - balanced - low latency (useful if app is in foreground and fast beacon input is needed) ## How do I use the cloud features? You will need to create a developer account in our cloud console in order to use this library in your own apps. Please read the [Getting started wiki page](https://github.com/Codefy/onebeacon-android/wiki/Getting-started) ## Compatibility The library is compatible with Android API 5 or newer. However it will only start the beacon scanning if the Android device supports this feature, which was introduced with Android 4.3, and if the hardware supports it. ## Changelog 1.0.26 (April 15th 2016) - added support for Eddystone EID and encrypted TLM frames
{ "content_hash": "9af539cc8fa44cc65bfcc72fac907060", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 351, "avg_line_length": 82.59375, "alnum_prop": 0.7807415815361332, "repo_name": "Codefy/onebeacon-android", "id": "46888c679f47a06756a2d3ce7347007d4ea2a812", "size": "5328", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = require("@firebase/util"); var Repo_1 = require("./Repo"); var util_2 = require("./util/util"); var parser_1 = require("./util/libs/parser"); var validation_1 = require("./util/validation"); require("./Repo_transaction"); /** @const {string} */ var DATABASE_URL_OPTION = 'databaseURL'; var _staticInstance; /** * Creates and caches Repo instances. */ var RepoManager = /** @class */ (function () { function RepoManager() { /** * @private {!Object.<string, Object<string, !fb.core.Repo>>} */ this.repos_ = {}; /** * If true, new Repos will be created to use ReadonlyRestClient (for testing purposes). * @private {boolean} */ this.useRestClient_ = false; } RepoManager.getInstance = function () { if (!_staticInstance) { _staticInstance = new RepoManager(); } return _staticInstance; }; // TODO(koss): Remove these functions unless used in tests? RepoManager.prototype.interrupt = function () { for (var appName in this.repos_) { for (var dbUrl in this.repos_[appName]) { this.repos_[appName][dbUrl].interrupt(); } } }; RepoManager.prototype.resume = function () { for (var appName in this.repos_) { for (var dbUrl in this.repos_[appName]) { this.repos_[appName][dbUrl].resume(); } } }; /** * This function should only ever be called to CREATE a new database instance. * * @param {!FirebaseApp} app * @return {!Database} */ RepoManager.prototype.databaseFromApp = function (app, url) { var dbUrl = url || app.options[DATABASE_URL_OPTION]; if (dbUrl === undefined) { util_2.fatal("Can't determine Firebase Database URL. Be sure to include " + DATABASE_URL_OPTION + ' option when calling firebase.intializeApp().'); } var parsedUrl = parser_1.parseRepoInfo(dbUrl); var repoInfo = parsedUrl.repoInfo; validation_1.validateUrl('Invalid Firebase Database URL', 1, parsedUrl); if (!parsedUrl.path.isEmpty()) { util_2.fatal('Database URL must point to the root of a Firebase Database ' + '(not including a child path).'); } var repo = this.createRepo(repoInfo, app); return repo.database; }; /** * Remove the repo and make sure it is disconnected. * * @param {!Repo} repo */ RepoManager.prototype.deleteRepo = function (repo) { var appRepos = util_1.safeGet(this.repos_, repo.app.name); // This should never happen... if (!appRepos || util_1.safeGet(appRepos, repo.repoInfo_.toURLString()) !== repo) { util_2.fatal("Database " + repo.app.name + "(" + repo.repoInfo_ + ") has already been deleted."); } repo.interrupt(); delete appRepos[repo.repoInfo_.toURLString()]; }; /** * Ensures a repo doesn't already exist and then creates one using the * provided app. * * @param {!RepoInfo} repoInfo The metadata about the Repo * @param {!FirebaseApp} app * @return {!Repo} The Repo object for the specified server / repoName. */ RepoManager.prototype.createRepo = function (repoInfo, app) { var appRepos = util_1.safeGet(this.repos_, app.name); if (!appRepos) { appRepos = {}; this.repos_[app.name] = appRepos; } var repo = util_1.safeGet(appRepos, repoInfo.toURLString()); if (repo) { util_2.fatal('Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.'); } repo = new Repo_1.Repo(repoInfo, this.useRestClient_, app); appRepos[repoInfo.toURLString()] = repo; return repo; }; /** * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos. * @param {boolean} forceRestClient */ RepoManager.prototype.forceRestClient = function (forceRestClient) { this.useRestClient_ = forceRestClient; }; return RepoManager; }()); exports.RepoManager = RepoManager; //# sourceMappingURL=RepoManager.js.map
{ "content_hash": "5179457fc926bcbfd7d4364a7a9e227b", "timestamp": "", "source": "github", "line_count": 119, "max_line_length": 148, "avg_line_length": 36.94117647058823, "alnum_prop": 0.5925841674249318, "repo_name": "aggiedefenders/aggiedefenders.github.io", "id": "33190e73cabc4ab3978b5cb04ae0f37dd4dacde0", "size": "4989", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "node_modules/@firebase/database/dist/cjs/src/core/RepoManager.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "3278" }, { "name": "JavaScript", "bytes": "135995" } ], "symlink_target": "" }
#include <linux/kernel.h> #include <linux/init.h> #include <linux/module.h> #include <linux/netlink.h> #include <linux/jhash.h> #include <linux/netfilter.h> #include <linux/netfilter/nf_tables.h> #include <net/netfilter/nf_tables.h> #include <net/netfilter/nf_queue.h> static u32 jhash_initval __read_mostly; struct nft_queue { u16 queuenum; u16 queues_total; u16 flags; }; static void nft_queue_eval(const struct nft_expr *expr, struct nft_regs *regs, const struct nft_pktinfo *pkt) { struct nft_queue *priv = nft_expr_priv(expr); u32 queue = priv->queuenum; u32 ret; if (priv->queues_total > 1) { if (priv->flags & NFT_QUEUE_FLAG_CPU_FANOUT) { int cpu = smp_processor_id(); queue = priv->queuenum + cpu % priv->queues_total; } else { queue = nfqueue_hash(pkt->skb, queue, priv->queues_total, pkt->ops->pf, jhash_initval); } } ret = NF_QUEUE_NR(queue); if (priv->flags & NFT_QUEUE_FLAG_BYPASS) ret |= NF_VERDICT_FLAG_QUEUE_BYPASS; regs->verdict.code = ret; } static const struct nla_policy nft_queue_policy[NFTA_QUEUE_MAX + 1] = { [NFTA_QUEUE_NUM] = { .type = NLA_U16 }, [NFTA_QUEUE_TOTAL] = { .type = NLA_U16 }, [NFTA_QUEUE_FLAGS] = { .type = NLA_U16 }, }; static int nft_queue_init(const struct nft_ctx *ctx, const struct nft_expr *expr, const struct nlattr * const tb[]) { struct nft_queue *priv = nft_expr_priv(expr); if (tb[NFTA_QUEUE_NUM] == NULL) return -EINVAL; init_hashrandom(&jhash_initval); priv->queuenum = ntohs(nla_get_be16(tb[NFTA_QUEUE_NUM])); if (tb[NFTA_QUEUE_TOTAL] != NULL) priv->queues_total = ntohs(nla_get_be16(tb[NFTA_QUEUE_TOTAL])); if (tb[NFTA_QUEUE_FLAGS] != NULL) { priv->flags = ntohs(nla_get_be16(tb[NFTA_QUEUE_FLAGS])); if (priv->flags & ~NFT_QUEUE_FLAG_MASK) return -EINVAL; } return 0; } static int nft_queue_dump(struct sk_buff *skb, const struct nft_expr *expr) { const struct nft_queue *priv = nft_expr_priv(expr); if (nla_put_be16(skb, NFTA_QUEUE_NUM, htons(priv->queuenum)) || nla_put_be16(skb, NFTA_QUEUE_TOTAL, htons(priv->queues_total)) || nla_put_be16(skb, NFTA_QUEUE_FLAGS, htons(priv->flags))) goto nla_put_failure; return 0; nla_put_failure: return -1; } static struct nft_expr_type nft_queue_type; static const struct nft_expr_ops nft_queue_ops = { .type = &nft_queue_type, .size = NFT_EXPR_SIZE(sizeof(struct nft_queue)), .eval = nft_queue_eval, .init = nft_queue_init, .dump = nft_queue_dump, }; static struct nft_expr_type nft_queue_type __read_mostly = { .name = "queue", .ops = &nft_queue_ops, .policy = nft_queue_policy, .maxattr = NFTA_QUEUE_MAX, .owner = THIS_MODULE, }; static int __init nft_queue_module_init(void) { return nft_register_expr(&nft_queue_type); } static void __exit nft_queue_module_exit(void) { nft_unregister_expr(&nft_queue_type); } module_init(nft_queue_module_init); module_exit(nft_queue_module_exit); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Eric Leblond <eric@regit.org>"); MODULE_ALIAS_NFT_EXPR("queue");
{ "content_hash": "efbbf56cb48f525e35a68a5697bebc8e", "timestamp": "", "source": "github", "line_count": 123, "max_line_length": 75, "avg_line_length": 24.70731707317073, "alnum_prop": 0.6683119447186574, "repo_name": "publicloudapp/csrutil", "id": "96805d21d618b7be7f0b802e4738d4d2afa6de7f", "size": "3383", "binary": false, "copies": "611", "ref": "refs/heads/master", "path": "linux-4.3/net/netfilter/nft_queue.c", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "3984" }, { "name": "Awk", "bytes": "29136" }, { "name": "C", "bytes": "532969471" }, { "name": "C++", "bytes": "3352303" }, { "name": "Clojure", "bytes": "1489" }, { "name": "Cucumber", "bytes": "4701" }, { "name": "Groff", "bytes": "46775" }, { "name": "Lex", "bytes": "55199" }, { "name": "Makefile", "bytes": "1576284" }, { "name": "Objective-C", "bytes": "521540" }, { "name": "Perl", "bytes": "715196" }, { "name": "Perl6", "bytes": "3783" }, { "name": "Python", "bytes": "273092" }, { "name": "Shell", "bytes": "343618" }, { "name": "SourcePawn", "bytes": "4687" }, { "name": "UnrealScript", "bytes": "12797" }, { "name": "XS", "bytes": "1239" }, { "name": "Yacc", "bytes": "114559" } ], "symlink_target": "" }
# This will single-thread multiple runs of randomized configuration files of Societies # on the supercomputer cluster. # # Last revised: BRH 08.06.2018 # (note: check out this link for picky rules about math and variables in bash shell scripts: # http://faculty.salina.k-state.edu/tim/unix_sg/bash/math.html) cd ~/SocietiesABM/ ############################################################################ # OPTIONAL commandline arguments. # # The number before the colon is the order of the passed parameter on the command line. # The number after the colon and the "-" is the default if no parameters are passed. # num_random_conf_files=${1:-001} num_random_runs=${2:-002} num_days=${3:-100} trade=${4:-True} devices=${5:-True} tools_only=${6:-False} num_agents=${7:-8} let num_resources=${8:-4} #"let" is used so that math can be performed with the variable later # if NUM_RESOURCES < 6 then resources_in_tool is 1 less than NUM_RESOURCES # otherwise, it can be passed as a parameter with the default = 5 if [ $num_resources -lt 6 ]; then let resources_in_tool=$num_resources-1 else let resources_in_tool=${9:-5} fi let num_device_components=$resources_in_tool+1 # The default is for device components to be 1 more than tool components # ############################################################################ ############################################################################################################# # Control amount of random variation within one config file by uncommenting the appropriate option: # Option 1: The same configuration will have random results. # Option 2: No variation - used for testing. (comment out Option 1 and uncomment out Option 2, if needed) ############################################################################################################# ############################################################################################################# # Option 1 ############################################################################################################## # seed=" " ############################################################################################################# # Option 2 ############################################################################################################# seed=" -S 50" #Set the random seed so that societies' results will be the same if all parameters are the same ################################################################################################################# # BEGIN SPECIFIC CODE FOR USER TEST. # UTEST_1: ################################################################################################################# sim_name=UTEST_1 #Begin run log StartDay=$(date +%D) StartTime=$(date +%T) ((totaltime=0)) echo " ***************************************************************************** * "$sim_name" BEGINS: "$StartDay" "$StartTime". * * NUM_DAYS = "$num_days" * NUM_AGENTS = "$num_agents" * NUM_RESOURCES = "$num_resources" * RESOURCES_IN_TOOL = "$resources_in_tool" * TOOLS_ONLY = "$tools_only" * TRADE = "$trade" * DEVICES = "$devices" * * ***************************************************************************** "| tee _Results/"$sim_name".log echo "UniqueKey,Config,Run,Seconds,Minutes" > _Results/"$sim_name"_runtime.csv #################################################################################### # Begin LOOP 1: create a randomized configuration file. # The formatting of the iterator as %03g gives it leading zeros: 001,002, etc. for X in $(seq -f "%03g" 1 $num_random_conf_files) do ################################################################################# # Create config file with input parameters. # Default values are found in ./Configs/default.conf # Name the config file based on run number ################################################################################# config="$sim_name"_"$X" ################################################################################# # Create a UniqueKey to save the parameters for each unique config of parameters ################################################################################# UniqueKey=$(date +%d%m%Y%H%M%S%N) echo " ***************************************************************************** "CONFIG = "$config" Unique Key = "$UniqueKey"" ***************************************************************************** " | tee -a _Results/"$sim_name".log echo " START_DAY = 0 DAY_LENGTH = 600 TRADE_EXISTS = "$trade" DEVICES_EXIST = "$devices" TOOLS_ONLY = "$tools_only" NUM_DAYS = "$num_days" NUM_AGENTS = "$num_agents" NUM_RESOURCES = "$num_resources" RESOURCES_IN_TOOL = "$resources_in_tool" NUM_DEVICE_COMPONENTS = "$num_device_components" MENU_SIZE = 4 RES_TRADE_ROUNDS = 12 RES_TRADE_ATTEMPTS = 8 DEVICE_TRADE_ROUNDS = 12 DEVICE_TRADE_ATTEMPTS = 4 DEVICE_TRADE_MEMORY_LENGTH = 5 DEVICE_PRODUCTION_MEMORY_LENGTH = 5 NUM_AGENT_GROUPS = 1 MIN_RES_UTIL = 1.0 MAX_RES_EFFORT = 9.0 MIN_RES_EFFORT = 3.0 MAX_DEVICE_EFFORT = 27.0 MIN_DEVICE_EFFORT = 9.0 TOOL_FACTOR = 3.0 MACHINE_FACTOR = 9.0 FACTORY_FACTOR = 27.0 INDUSTRY_FACTOR = 81.0 TOOL_LIFETIME = 150.0 MACHINE_LIFETIME = 300.0 FACTORY_LIFETIME = 600.0 INDUSTRY_LIFETIME = 1200.0 MAX_RES_EXPERIENCE = 600.0 MAX_DEVICE_EXPERIENCE = 40.0 INVENTOR_DEVICE_EXPERIENCE = 6 MIN_HELD_DEVICE_EXPERIENCE = 2 DAYS_OF_DEVICE_TO_HOLD = 2 DAILY_EXP_PENALTY = 3.0 DAILY_DEVICE_DECAY = 3 MIN_RES_HELD_FOR_DEVICE_CONSIDERATION = 3 TRADE_EPSILON = .1 TOOL_PROBABILITY_FACTOR = .000075 DEVICE_PROBABILITY_FACTOR = .00125 PRODUCTION_EPSILON = 0 DEV_MACHINE_FACTOR = .1 DEV_MACHINE_LIFETIME = 1 DEV_FACTORY_FACTOR = .1 DEV_FACTORY_LIFETIME = 1 MIN_DEVICE_FOR_DEV_DEVICE_CONSIDERATION = 10000 OTHER_MARKETS = False " > Configs/"$config".conf ###################################################################################### # Save the entire configuration to the log file. ###################################################################################### cat Configs/"$config".conf | tee -a _Results/"$sim_name".log # Begin random runs using the same configuration file. # The formatting of the iterator (run) as %03g gives it leading zeros: 001,002, etc. for run in $(seq -f "%03g" 1 $num_random_runs) do ### SOCIETIES COMMAND-LINE ARGUMENTS: # 1. -p Name of the configuration (without Configs/ path and without .conf extention) # # 2. -s Name of the save folder. # # 3. -t tracks sequential run numbers in the results directories # # 4. -d provides a unique batch ID that will be used to join the output measures # with the config file dimensions (societies v1.5 and higher) # 5. -v is the level of log messages to be printed to the log file. 0 is none. # Start the clock for this run of societies. SECONDS=0 # The & before the re-direction (">>") will send error messages to the stdout file as well. ./societies -v 0 -p "$config" -s _Results/"$sim_name"/"$config" -d B"$UniqueKey" -t "$run" "$seed" 1>> _Results/"$sim_name"_run.log # Stop the clock after societies finishes ((duration=$SECONDS)) ((duration_min=$duration/60)) # Add this run time to the total time of the simulation. ((totaltime=$totaltime+$duration)) echo "B"$UniqueKey",$config,$run,$duration,$duration_min" >> _Results/"$sim_name"_runtime.csv done #Done with loop over one run of one randomly generated configuration rm ./Configs/"$config".conf rm ./Configs/"$config"_AgentValues.aconf done #Done with all runs of one randomly generated configuration EndDay=$(date +%D) EndTime=$(date +%T) ((totalminutes=$totaltime/60)) echo " ***************************************************************************** * "$sim_name" * ENDED at "$EndDay" "$EndTime" * Total Duration: $totaltime seconds ($totalminutes minutes) * ***************************************************************************** " | tee -a _Results/"$sim_name".log ######################################################################################### # Concatenate and save all of the output files. # # FYI: the head command saves the header row from the first individual long_output file. # FYI: the grep -v command strips out all of the header rows (starts with UniqueKey) # from the individual long_output files. BRH 3.20.2017 ######################################################################################### cd ~/SocietiesABM/_Results/ cat ./$sim_name/*/*/IOMatrix.csv | head -n 1 > temp1 cat ./$sim_name/*/*/IOMatrix.csv | grep -v UniqueKey >> temp2 cat temp1 temp2 > ./$sim_name/IOMatrixAll.csv rm temp1 temp2 cat ./$sim_name/*/*/DeviceRecipes.csv | head -n 1 > temp1 cat ./$sim_name/*/*/DeviceRecipes.csv | grep -v UniqueKey >> temp2 cat temp1 temp2 > ./$sim_name/DeviceRecipes.csv rm temp1 temp2 cat ./$sim_name/*/*/long_output.csv | head -n 1 > temp1 cat ./$sim_name/*/*/long_output.csv | grep -v UniqueKey >> temp2 cat temp1 temp2 > ./$sim_name/long_output_all.csv rm temp1 temp2 cat ./$sim_name/*/*/unitsGathered.csv | head -n 1 > temp1 cat ./$sim_name/*/*/unitsGathered.csv | grep -v UniqueKey >> temp2 cat temp1 temp2 > ./$sim_name/unitsGathered_all.csv rm temp1 temp2 # Print out runtimes. echo " Runtime statistics: " | tee -a $sim_name.log column -s , -t < "$sim_name"_runtime.csv | tee -a $sim_name.log # Print out a summary of resources gathered. echo " Units Gathered in all runs: " | tee -a $sim_name.log column -s , -t < ./$sim_name/unitsGathered_all.csv | tee -a $sim_name.log ################################################################################################ # # Save all of the relevant UniqueKey entries with the output. # ################################################################################################ # Create the file to record all of the configuration parameters in a database. # This only needs to be run if this file has been deleted or to start a fresh file. ################################################################################################ echo "UniqueKey,ConfigName,Group_Num,NUM_AGENTS,NUM_RESOURCES,NUM_AGENT_GROUPS,TRADE_EXISTS,DEVICES_EXIST,TOOLS_ONLY, \ NUM_DAYS,START_DAY,DAY_LENGTH,RES_TRADE_ROUNDS,RES_TRADE_ATTEMPTS,DEVICE_TRADE_ROUNDS,DEVICE_TRADE_ATTEMPTS, \ MENU_SIZE,DEVICE_TRADE_MEMORY_LENGTH,DEVICE_PRODUCTION_MEMORY_LENGTH,MIN_DEVICE_FOR_DEV_DEVICE_CONSIDERATION, \ MIN_RES_HELD_FOR_DEVICE_CONSIDERATION,DAILY_EXP_PENALTY,PRODUCTION_EPSILON,RESOURCES_IN_TOOL,MAX_RES_EXPERIENCE, \ INVENTOR_DEVICE_EXPERIENCE,NUM_DEVICE_COMPONENTS,MAX_DEVICE_EXPERIENCE,DAILY_DEVICE_DECAY,MIN_HELD_DEVICE_EXPERIENCE, \ MAX_RES_EFFORT,MIN_RES_EFFORT,MAX_DEVICE_EFFORT,MIN_DEVICE_EFFORT,MIN_RES_UTIL,TRADE_EPSILON,TOOL_PROBABILITY_FACTOR, \ DEVICE_PROBABILITY_FACTOR,TOOL_FACTOR,TOOL_LIFETIME,MACHINE_FACTOR,MACHINE_LIFETIME,FACTORY_FACTOR,FACTORY_LIFETIME, \ INDUSTRY_FACTOR,INDUSTRY_LIFETIME,DEV_MACHINE_FACTOR,DEV_MACHINE_LIFETIME,DEV_FACTORY_FACTOR,DEV_FACTORY_LIFETIME, \ DAYS_OF_DEVICE_TO_HOLD,REMOVE_RES,RES_TO_REMOVE,REMOVE_RES_DAY,ELIMINATE_RESERVES,REMOVE_AGENT,AGENT_TO_REMOVE, \ REMOVE_AGENT_DAY,END_SAVE,SAVE_FOLDER,SAVE_DAY_STATUS,DAY_STATUS_SAVE_FOLDER,DAY_FOR_SAVE,DAY_STATUS_LOAD_FOLDER, \ SIM_NAME,SIM_SAVE_FOLDER,SAVE_TRADES,PARALLEL_TRADES" > ~/SocietiesABM/_Results/ukey_header.csv grep $sim_name\/ UniqueKeyFile.csv > temp2 cat ~/SocietiesABM/_Results/ukey_header.csv temp2 > ./$sim_name/UniqueKeyFile.csv rm temp2 mv $sim_name.log ./$sim_name/$sim_name.log mv "$sim_name"_run.log ./$sim_name/"$sim_name"_run.log mv "$sim_name"_runtime.csv ./$sim_name/"$sim_name"_runtime.csv savedate=$(date +%d%m%Y%H%M%S) mv $sim_name $sim_name.$savedate
{ "content_hash": "854095d9171d43ca6290f7f0469e0ec7", "timestamp": "", "source": "github", "line_count": 299, "max_line_length": 132, "avg_line_length": 38.99665551839465, "alnum_prop": 0.5606346483704975, "repo_name": "bhaney22/SocietiesABM", "id": "6d66fa40358a0a181b0b2f7dede2d0303d735fb3", "size": "11660", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "runUTEST1.sh", "mode": "33261", "license": "mit", "language": [ { "name": "C", "bytes": "63" }, { "name": "C++", "bytes": "368532" }, { "name": "Makefile", "bytes": "1150" }, { "name": "Python", "bytes": "48257" }, { "name": "Shell", "bytes": "121926" } ], "symlink_target": "" }
package org.waveprotocol.wave.examples.fedone.persistence; import com.google.inject.AbstractModule; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.inject.name.Named; import org.waveprotocol.wave.crypto.CertPathStore; import org.waveprotocol.wave.examples.fedone.persistence.memory.MemoryStore; import org.waveprotocol.wave.examples.fedone.persistence.mongodb.MongoDbProvider; /** * Module for setting up the different persistence stores. * * @author ljvderijk@google.com (Lennard de Rijk) * * The valid names for the cert store are * 'memory' and 'mongodb' * * The valid names for the attachment store are * 'disk' and 'mongodb' * */ public class PersistenceModule extends AbstractModule { /** * Type of persistence to use for the {@link CertPathStore}. */ private final String certPathStoreType; private final String attachmentStoreType; private MongoDbProvider mongoDbProvider; @Inject public PersistenceModule( @Named("cert_path_store_type") String certPathStoreType, @Named("attachment_store_type") String attachmentStoreType) { this.certPathStoreType = certPathStoreType; this.attachmentStoreType = attachmentStoreType; } /** * Returns a {@link MongoDbProvider} instance. */ public MongoDbProvider getMongoDbProvider() { if (mongoDbProvider == null) { mongoDbProvider = new MongoDbProvider(); } return mongoDbProvider; } @Override protected void configure() { bindCertPathStore(); bindAttachmentStore(); } /** * Binds the CertPathStore implementation to the store specified in the * properties. */ private void bindCertPathStore() { if (certPathStoreType.equalsIgnoreCase("memory")) { bind(CertPathStore.class).to(MemoryStore.class).in(Singleton.class); } else if (certPathStoreType.equalsIgnoreCase("mongodb")) { MongoDbProvider mongoDbProvider = getMongoDbProvider(); bind(CertPathStore.class).toInstance(mongoDbProvider.provideMongoDbStore()); } else { throw new RuntimeException("Invalid certificate path type: '" + certPathStoreType + "'"); } } private void bindAttachmentStore() { if (attachmentStoreType.equalsIgnoreCase("disk")) { bind(AttachmentStore.class).to(FileBasedAttachmentStore.class).in(Singleton.class); } else if (attachmentStoreType.equalsIgnoreCase("mongodb")) { MongoDbProvider mongoDbProvider = getMongoDbProvider(); bind(AttachmentStore.class).toInstance(mongoDbProvider.provideMongoDbStore()); } else { throw new RuntimeException("Invalid attachment store type: '" + attachmentStoreType + "'"); } } }
{ "content_hash": "f76d28d12a112a3ea7b636e24ff35f29", "timestamp": "", "source": "github", "line_count": 85, "max_line_length": 97, "avg_line_length": 31.564705882352943, "alnum_prop": 0.7316436824450242, "repo_name": "jkatzer/jkatzer-wave", "id": "7bf4922fad4ae089ee7581172a62f17195423122", "size": "3282", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/org/waveprotocol/wave/examples/fedone/persistence/PersistenceModule.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "264339" }, { "name": "Java", "bytes": "1152947" }, { "name": "Makefile", "bytes": "2128" }, { "name": "Protocol Buffer", "bytes": "24792" }, { "name": "Python", "bytes": "72885" }, { "name": "Shell", "bytes": "9397" } ], "symlink_target": "" }
 #pragma once #include <aws/workmail/WorkMail_EXPORTS.h> #include <aws/workmail/WorkMailRequest.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <utility> namespace Aws { namespace WorkMail { namespace Model { /** */ class AWS_WORKMAIL_API ListMobileDeviceAccessRulesRequest : public WorkMailRequest { public: ListMobileDeviceAccessRulesRequest(); // Service request name is the Operation name which will send this request out, // each operation should has unique request name, so that we can get operation's name from this request. // Note: this is not true for response, multiple operations may have the same response name, // so we can not get operation's name from response. inline virtual const char* GetServiceRequestName() const override { return "ListMobileDeviceAccessRules"; } Aws::String SerializePayload() const override; Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override; /** * <p>The Amazon WorkMail organization for which to list the rules.</p> */ inline const Aws::String& GetOrganizationId() const{ return m_organizationId; } /** * <p>The Amazon WorkMail organization for which to list the rules.</p> */ inline bool OrganizationIdHasBeenSet() const { return m_organizationIdHasBeenSet; } /** * <p>The Amazon WorkMail organization for which to list the rules.</p> */ inline void SetOrganizationId(const Aws::String& value) { m_organizationIdHasBeenSet = true; m_organizationId = value; } /** * <p>The Amazon WorkMail organization for which to list the rules.</p> */ inline void SetOrganizationId(Aws::String&& value) { m_organizationIdHasBeenSet = true; m_organizationId = std::move(value); } /** * <p>The Amazon WorkMail organization for which to list the rules.</p> */ inline void SetOrganizationId(const char* value) { m_organizationIdHasBeenSet = true; m_organizationId.assign(value); } /** * <p>The Amazon WorkMail organization for which to list the rules.</p> */ inline ListMobileDeviceAccessRulesRequest& WithOrganizationId(const Aws::String& value) { SetOrganizationId(value); return *this;} /** * <p>The Amazon WorkMail organization for which to list the rules.</p> */ inline ListMobileDeviceAccessRulesRequest& WithOrganizationId(Aws::String&& value) { SetOrganizationId(std::move(value)); return *this;} /** * <p>The Amazon WorkMail organization for which to list the rules.</p> */ inline ListMobileDeviceAccessRulesRequest& WithOrganizationId(const char* value) { SetOrganizationId(value); return *this;} private: Aws::String m_organizationId; bool m_organizationIdHasBeenSet; }; } // namespace Model } // namespace WorkMail } // namespace Aws
{ "content_hash": "0f801438fce2e04f5253a903b4fe8723", "timestamp": "", "source": "github", "line_count": 82, "max_line_length": 140, "avg_line_length": 34.48780487804878, "alnum_prop": 0.71004243281471, "repo_name": "awslabs/aws-sdk-cpp", "id": "6be15462e33a6ca81d2a26582d763902afb1db1c", "size": "2947", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "aws-cpp-sdk-workmail/include/aws/workmail/model/ListMobileDeviceAccessRulesRequest.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "7596" }, { "name": "C++", "bytes": "61740540" }, { "name": "CMake", "bytes": "337520" }, { "name": "Java", "bytes": "223122" }, { "name": "Python", "bytes": "47357" } ], "symlink_target": "" }
<rss> <item> <title>queen latifah bonds with dolly parton over breasts</title> <link> http://rssfeeds.usatoday.com/~r/usatoday-lifetopstories/~3/7mn2ddit92c/1 </link> <pubDate>24 May 2011 22:01:00 +0000</pubDate> <category> <![CDATA[ entertainment ]]> </category> <description> <![CDATA[ queen latifah has nothing but nice things to say about her idol, dolly parton. ]]> </description> </item> <item> <title>earthquakes shake australia, new zealand</title> <link> http://rssfeeds.usatoday.com/~r/usatodaycomworld-topstories/~3/ijvd0wraxyk/2011-04-16-australia-quakes.htm </link> <pubDate>16 Apr 2011 12:12:00 +0000</pubDate> <category> <![CDATA[ world ]]> </category> <description> <![CDATA[ moderate earthquakes rattled parts of australia and new zealand on saturday, including the devastated city of christchurch where power was cut ... ]]> </description> </item> <item> <title>kuwait cabinet quits to avoid ministers' grilling</title> <link> http://feeds.nytimes.com/click.phdo?i=0c3ddad0e1bb87c83d7274065cd92228 </link> <pubDate>01 Apr 2011 06:26:22 +0000</pubDate> <category> <![CDATA[ world ]]> </category> <description> <![CDATA[ kuwait's cabinet resigned as expected thursday to avoid a grilling by parliament of three ministers, all members of the ruling al-sabah family, amid calls for political and economic reform. ]]> </description> </item> <item> <title>nick jonas is doing just fine on his own</title> <link> http://rssfeeds.usatoday.com/~r/usatoday-lifetopstories/~3/gdtju9feivs/2011-06-08-nick-jonas_n.htm </link> <pubDate>08 Jun 2011 18:41:16 +0000</pubDate> <category> <![CDATA[ entertainment ]]> </category> <description> <![CDATA[ the youngest jobro is branching out into writing, producing and performing onstage. ]]> </description> </item> <item> <title>"silent" strokes less common in physically fit</title> <link> http://feeds.reuters.com/~r/reuters/healthnews/~3/l7lbnwya9-s/us-strokes-physically-fit-idustre7576dc20110608 </link> <pubDate>08 Jun 2011 22:21:40 +0000</pubDate> <category> <![CDATA[ health ]]> </category> <description> <![CDATA[ people who participate in vigorous activity are less likely to experience so-called "silent" strokes, new study findings report. ]]> </description> </item> <item> <title>vcu vexes no. 1 kansas to earn school's first trip to final four</title> <link> http://rssfeeds.usatoday.com/~r/usatodaycomsports-topstories/~3/uoleclxlg3a/2011-03-27-vcu-kansas_n.htm </link> <pubDate>28 Mar 2011 01:08:45 +0000</pubDate> <category> <![CDATA[ sport ]]> </category> <description> <![CDATA[ virginia commonwealth has done the unthinkable. the rams stunned no. 1 seed kansas 71-61 in san antonio on sunday to earn the school's first-ever ... ]]> </description> </item> <item> <title>icloud stores all info on all devices</title> <link> http://rssfeeds.usatoday.com/~r/usatoday-techtopstories/~3/n3um43dxzlo/2011-06-07-more-on-icloud-baig_n.htm </link> <pubDate>07 Jun 2011 21:47:50 +0000</pubDate> <category> <![CDATA[ sci_tech ]]> </category> <description> <![CDATA[ apple stole the thunder on clouds at its worldwide developers conference in san francisco. ]]> </description> </item> <item> <title>texas lawmakers may need special session for budget</title> <link> http://feeds.reuters.com/~r/reuters/domesticnews/~3/4ynawfrprks/us-texas-budget-idustre74t3ys20110530 </link> <pubDate>30 May 2011 23:17:30 +0000</pubDate> <category> <![CDATA[ us ]]> </category> <description> <![CDATA[ texas lawmakers could be headed to a special legislative session as early as tuesday after a late-night filibuster on sunday delayed a bill linked to the state budget, officials said. ]]> </description> </item> <item> <title>soccer: manchester united deflates chelsea title hopes</title> <link> http://feeds1.nytimes.com/~r/nyt/rss/sports/~3/mx3te0ffj7k/09iht-goal09.html </link> <pubDate>09 May 2011 09:20:06 +0000</pubDate> <category> <![CDATA[ sport ]]> </category> <description> <![CDATA[ united needs just one more point to reclaim the premier league title after defeating chelsea, 2-1. ]]> </description> </item> <item> <title>lindsay lohan avoids criminal charge in betty ford quarrel</title> <link> http://feeds.reuters.com/~r/reuters/entertainment/~3/sgu-7vwrr3s/us-lindsaylohan-idustre72t0aa20110330 </link> <pubDate>31 Mar 2011 00:24:34 +0000</pubDate> <category> <![CDATA[ entertainment ]]> </category> <description> <![CDATA[ prosecutors on tuesday decided against filing a battery charge against lindsay lohan that might have sent the troubled actress to jail over a confrontation at california's betty ford center rehab clinic. ]]> </description> </item> <item> <title>anti-abortion amendments added to proposed ohio budget bill</title> <link> http://feeds.reuters.com/~r/reuters/domesticnews/~3/_8d8eytxtuw/us-abortion-states-ohio-idustre7566tr20110607 </link> <pubDate>07 Jun 2011 23:38:49 +0000</pubDate> <category> <![CDATA[ us ]]> </category> <description> <![CDATA[ two amendments restricting abortions in public hospitals and clinics were added to the ohio senate's proposed budget bidon tuesday, a day before lawmakers are set to vote on it. ]]> </description> </item> <item> <title>the rail: morning line: another defection, and uncle maybe</title> <link> http://feeds1.nytimes.com/~r/nyt/rss/sports/~3/eoiitdy7ru0/ </link> <pubDate>04 May 2011 19:30:27 +0000</pubDate> <category> <![CDATA[ sport ]]> </category> <description> <![CDATA[ the morning line for wednesday, may 4 ]]> </description> </item> <item> <title>palestinian dies after protest in jerusalem</title> <link> http://feeds.reuters.com/~r/reuters/worldnews/~3/rcwp2xyfwmu/us-palestinians-israel-violence-idustre74d0gq20110514 </link> <pubDate>14 May 2011 13:19:29 +0000</pubDate> <category> <![CDATA[ world ]]> </category> <description> <![CDATA[ a palestinian teenager who was shot during protests in jerusalem died on saturday, hospital officials said, and israeli police, expecting further demonstrations, deployed heavily in the streets. ]]> </description> </item> <item> <title>japan stops radioactive leaks from nuclear plant</title> <link> http://feeds.nytimes.com/click.phdo?i=a45ccc60c797bdc038433031d4304657 </link> <pubDate>06 Apr 2011 03:47:00 +0000</pubDate> <category> <![CDATA[ world ]]> </category> <description> <![CDATA[ engineers stopped radioactive water leaking into the sea from the crippled plant, the facility's operator said. ]]> </description> </item> <item> <title>final four trip pays off for coaches</title> <link> http://feeds1.nytimes.com/~r/nyt/rss/sports/~3/1mc-2ndrjc8/ </link> <pubDate>31 Mar 2011 17:29:25 +0000</pubDate> <category> <![CDATA[ sport ]]> </category> <description> <![CDATA[ college coaches love reaching the final four for more than the obvious reasons -- it can also bring them more money in bonuses. ]]> </description> </item> <item> <title>endo to acquire american medical for $2.9 billion</title> <link> http://feeds.nytimes.com/click.phdo?i=916be81bb6dc7ea4a4ac828de3c3d65f </link> <pubDate>11 Apr 2011 16:57:14 +0000</pubDate> <category> <![CDATA[ business ]]> </category> <description> <![CDATA[ the deal is the third for endo pharmaceuticals in 12 months, and will add to the drug maker's treatments for urology and pain. ]]> </description> </item> <item> <title>u.s. to publish radiation data from airport screening</title> <link> http://feeds.reuters.com/~r/reuters/healthnews/~3/in4w8y8nevq/us-usa-airports-radiation-idustre72a57420110311 </link> <pubDate>11 Mar 2011 20:19:20 +0000</pubDate> <category> <![CDATA[ health ]]> </category> <description> <![CDATA[ the transportation security administration said on friday it will start publishing radiation test results from airport passenger and luggage screening equipment in a bid to allay lingering fears about potential health risks. ]]> </description> </item> <item> <title>several hundred keep up protest pressure in morocco</title> <link> http://feeds.reuters.com/~r/reuters/worldnews/~3/remcq9qv0ri/us-morocco-protest-idustre72k5ox20110321 </link> <pubDate>21 Mar 2011 19:25:35 +0000</pubDate> <category> <![CDATA[ world ]]> </category> <description> <![CDATA[ several hundred teachers marched through rabat on monday for better pay a day after one of morocco's largest anti-government protests in recent decades against corruption and demanding government change. ]]> </description> </item> <item> <title>dr. irwin d. mandel, expert on dental chemistry, dies at 89</title> <link> http://feeds.nytimes.com/click.phdo?i=66ee416a3c4d31481637c35ab681abfb </link> <pubDate>06 Jun 2011 17:04:45 +0000</pubDate> <category> <![CDATA[ health ]]> </category> <description> <![CDATA[ dr. mandel, a founder of the preventive dentistry movement, did research on the biochemistry of saliva that was important to many medical fields. ]]> </description> </item> <item> <title>bp faces angry oil spill protesters at agm</title> <link> http://feeds.reuters.com/~r/reuters/businessnews/~3/zdqpf5qs0q8/us-bp-agm-idustre73d5ps20110414 </link> <pubDate>14 Apr 2011 18:54:26 +0000</pubDate> <category> <![CDATA[ business ]]> </category> <description> <![CDATA[ bp's annual shareholder meeting was disrupted by campaigners protesting against the oil giant's role in the gulf of mexico spill, while investors registered their disapproval with big votes against directors. ]]> </description> </item> <item> <title>children are among casualties of syrian military raids after demonstrations</title> <link> http://feeds.nytimes.com/click.phdo?i=3a67788b87edd4a74d5b7c6cefbd17ea </link> <pubDate>02 Jun 2011 07:01:24 +0000</pubDate> <category> <![CDATA[ world ]]> </category> <description> <![CDATA[ human rights activists and residents in towns near homs said 42 people were killed as neighborhoods were besieged by tanks and troops. ]]> </description> </item> <item> <title>manchester city beats stoke 3-0 in premier league</title> <link> http://feeds1.nytimes.com/~r/nyt/rss/sports/~3/nclk3y3-iss/ap-soc-euro-rdp.html </link> <pubDate>18 May 2011 06:46:41 +0000</pubDate> <category> <![CDATA[ sport ]]> </category> <description> <![CDATA[ manchester city is on the verge of qualifying for the group phase of nest season's champions league after beating stoke 3-0 tuesday night, three days after defeating the same opponent in the fa cup final to end a 35-year title drought. ]]> </description> </item> <item> <title>40 civilians dead in tripoli strikes: vatican official</title> <link> http://feeds.reuters.com/~r/reuters/worldnews/~3/iqwzco8_aqa/us-libya-civilians-vatican-idustre72u47j20110331 </link> <pubDate>31 Mar 2011 16:55:05 +0000</pubDate> <category> <![CDATA[ world ]]> </category> <description> <![CDATA[ at least 40 civilians have been killed in air strikes by western forces on tripoli, the top vatican official in the libyan capital said thursday, citing what he called reliable sources in close contact with residents. ]]> </description> </item> <item> <title>nasa sending retired space shuttles to museums</title> <link> http://feeds.reuters.com/~r/reuters/domesticnews/~3/nimtzsazqye/us-space-shuttles-idustre73b5vi20110412 </link> <pubDate>12 Apr 2011 21:21:14 +0000</pubDate> <category> <![CDATA[ us ]]> </category> <description> <![CDATA[ the three retiring u.s. space shuttles will be going on display at museums in florida, california and virginia, the u.s. space agency nasa said on tuesday. ]]> </description> </item> <item> <title>google loses executive to groupon, preps rival service</title> <link> http://feeds.reuters.com/~r/reuters/technologynews/~3/4pgzgbjdbtq/us-groupon-idustre73k70g20110422 </link> <pubDate>22 Apr 2011 14:13:10 +0000</pubDate> <category> <![CDATA[ sci_tech ]]> </category> <description> <![CDATA[ online coupon service groupon has hired a google executive to be its new chief operating officer, as google began rolling out a new service aimed directly at groupon's thriving business. ]]> </description> </item> <item> <title>al qaeda "cadres" still help afghan taliban: u.s.</title> <link> http://feeds.reuters.com/~r/reuters/worldnews/~3/e2ts2q1xmoe/us-afghanistan-qaeda-usa-idustre74f4wn20110516 </link> <pubDate>16 May 2011 18:45:52 +0000</pubDate> <category> <![CDATA[ world ]]> </category> <description> <![CDATA[ fewer than 100 al qaeda members remain inside afghanistan, but they form a core group providing the afghan taliban with resources and technical battlefield skills, the second most senior u.s. commander in the country said monday. ]]> </description> </item> <item> <title>google loses exec to groupon, preps rival service</title> <link> http://feeds.reuters.com/~r/reuters/technologynews/~3/g3wijeo2r6k/us-groupon-idustre73k70g20110421 </link> <pubDate>22 Apr 2011 01:48:17 +0000</pubDate> <category> <![CDATA[ sci_tech ]]> </category> <description> <![CDATA[ online coupon service groupon has hired a google inc executive to be its new chief operating officer, as google began rolling out a new service aimed directly at groupon's thriving business. ]]> </description> </item> <item> <title>donald trump driving pace car at indianapolis 500</title> <link> http://feeds1.nytimes.com/~r/nyt/rss/sports/~3/ecz9yvyxd78/ap-car-indy-500-trump.html </link> <pubDate>06 Apr 2011 07:13:10 +0000</pubDate> <category> <![CDATA[ sport ]]> </category> <description> <![CDATA[ donald trump hasn't announced whether he'll run for president, but he will be involved in a race of a different kind next month. ]]> </description> </item> <item> <title>couture, grabner and skinner named calder trophy finalists</title> <link> http://feeds.reuters.com/~r/reuters/sportsnews/~3/sbjvyyyfif0/us-nhl-calder-finalists-idustre73i54220110419 </link> <pubDate>19 Apr 2011 19:14:21 +0000</pubDate> <category> <![CDATA[ sport ]]> </category> <description> <![CDATA[ san jose sharks center logan couture, new york islanders winger michael grabner and carolina hurricanes center jeff skinner have been named finalists for rookie of the year, the nhl said on tuesday. ]]> </description> </item> <item> <title>ozone layer faces record loss over arctic</title> <link> http://rssfeeds.usatoday.com/~r/usatodaycomworld-topstories/~3/nfkvu9nzz9y/2011-04-05-ozone-arctic_n.htm </link> <pubDate>05 Apr 2011 17:03:28 +0000</pubDate> <category> <![CDATA[ world ]]> </category> <description> <![CDATA[ the depletion of the ozone layer shielding earth from damaging ultraviolet rays has reached an unprecedented low over the arctic this spring ... ]]> </description> </item> <item> <title>a strongman found support in prominent u.s. conservatives</title> <link> http://feeds.nytimes.com/click.phdo?i=75b951ac805000a5d21a9cf8468ab765 </link> <pubDate>12 Apr 2011 07:37:03 +0000</pubDate> <category> <![CDATA[ us ]]> </category> <description> <![CDATA[ laurent gbagbo, who had refused to cede presidential power before being captured, had the backing of at least one american senator and the rev. pat robertson. ]]> </description> </item> <item> <title>yemen crisis deal collapses despite u.s. pressure</title> <link> http://feeds.reuters.com/~r/reuters/worldnews/~3/pw4vdywwhww/us-yemen-deal-idustre74h26n20110519 </link> <pubDate>19 May 2011 04:38:28 +0000</pubDate> <category> <![CDATA[ world ]]> </category> <description> <![CDATA[ last-minute diplomatic wrangling has derailed a deal on a transition of power in yemen despite growing u.s. pressure on president ali abdullah saleh to agree to the gulf-brokered plan and relinquish power. ]]> </description> </item> <item> <title>yemen transition deal falls through at last minute</title> <link> http://feeds.reuters.com/~r/reuters/worldnews/~3/r78byjwuxei/us-yemen-deal-idustre74h26n20110518 </link> <pubDate>18 May 2011 20:49:34 +0000</pubDate> <category> <![CDATA[ world ]]> </category> <description> <![CDATA[ a deal on a transition of power in yemen fell through at the last minute on wednesday, even as washington stepped up pressure on president ali abdullah saleh to sign a gulf-brokered agreement to ease him out of office. ]]> </description> </item> <item> <title>toys r us ipo likely in july: source</title> <link> http://feeds.reuters.com/~r/reuters/businessnews/~3/heuajfrwolm/us-toysrus-idustre73c7ij20110413 </link> <pubDate>13 Apr 2011 23:34:11 +0000</pubDate> <category> <![CDATA[ business ]]> </category> <description> <![CDATA[ toys r us is targeting an initial public offering in july, a source familiar with the matter told reuters on wednesday. ]]> </description> </item> <item> <title>nigerians turn out for presidential vote</title> <link> http://feeds.nytimes.com/click.phdo?i=f112bc6034ed1ba221331fc30dd49a9b </link> <pubDate>16 Apr 2011 17:30:29 +0000</pubDate> <category> <![CDATA[ world ]]> </category> <description> <![CDATA[ nigerians massed at polling stations saturday for what they hoped would be their first credible presidential election in decades. ]]> </description> </item> <item> <title>djokovic drops federer, will face nadal in indian wells final</title> <link> http://rssfeeds.usatoday.com/~r/usatodaycomsports-topstories/~3/x-hp6i4qxio/2011-03-19-bnp-paribas-open_n.htm </link> <pubDate>20 Mar 2011 02:16:19 +0000</pubDate> <category> <![CDATA[ sport ]]> </category> <description> <![CDATA[ australian open champion novak djokovic outlasted roger federer 6-3, 3-6, 6-2 to stay undefeated this season and reach the bnp paribas open final ... ]]> </description> </item> <item> <title>american ryan sweeting gains first atp final in houston</title> <link> http://rssfeeds.usatoday.com/~r/usatodaycomsports-topstories/~3/tebj8pkz11o/2011-04-09-us-clay-court-championships_n.htm </link> <pubDate>10 Apr 2011 01:54:22 +0000</pubDate> <category> <![CDATA[ sport ]]> </category> <description> <![CDATA[ wild card ryan sweeting of the united states has reached his first atp final, defeating ivo karlovic of croatia 7-6 (7-3) 6-3 at the u.s. men's ... ]]> </description> </item> <item> <title>berlusconi leaves hospital after attack</title> <link> http://feeds.nytimes.com/click.phdo?i=2ebba7c6836a23ef7e5cb4a82ed49304 </link> <pubDate>17 Dec 2009 16:20:34 +0000</pubDate> <category> <![CDATA[ world ]]> </category> <description> <![CDATA[ italian premier silvio berlusconi, his face bandaged, has left a milan hospital four days after being attacked at a political rally. ]]> </description> </item> <item> <title>brewers' gallardo takes no-hitter into 8th, beats cardinals</title> <link> http://rssfeeds.usatoday.com/~r/usatodaycomsports-topstories/~3/nhqdqbi77pa/2011-05-07-brewers-cardinals_n.htm </link> <pubDate>08 May 2011 07:29:04 +0000</pubDate> <category> <![CDATA[ sport ]]> </category> <description> <![CDATA[ yovani gallardo was the second straight pitcher to flirt with a no-hitter at busch stadium, allowing only a single to start the eighth inning ... ]]> </description> </item> <item> <title>avila, verlander help tigers hand orioles first loss</title> <link> http://rssfeeds.usatoday.com/~r/usatodaycomsports-topstories/~3/npqujvrdu7y/2011-04-06-tigers-orioles_n.htm </link> <pubDate>07 Apr 2011 06:11:02 +0000</pubDate> <category> <![CDATA[ sport ]]> </category> <description> <![CDATA[ alex avila homered and had a career-high five rbi to back an effective pitching performance by justin verlander as the detroit tigers ended the ... ]]> </description> </item> <item> <title>microsoft not too late for tablet party: citigroup</title> <link> http://feeds.reuters.com/~r/reuters/technologynews/~3/mpgkrsyl7_q/us-microsoft-research-citigroup-idustre74q3bs20110527 </link> <pubDate>27 May 2011 15:15:14 +0000</pubDate> <category> <![CDATA[ sci_tech ]]> </category> <description> <![CDATA[ microsoft is still not too late for the tablet party. and with its next operating system closer than most expect, the software maker could corner meaningful market share in 2013 and beyond, citigroup said. ]]> </description> </item> <item> <title>webber on the pace in first spanish practice</title> <link> http://feeds.reuters.com/~r/reuters/sportsnews/~3/ip4sigxah38/us-motor-racing-prix-practice-idustre74j26v20110520 </link> <pubDate>20 May 2011 12:31:06 +0000</pubDate> <category> <![CDATA[ sport ]]> </category> <description> <![CDATA[ australian mark webber lapped a second faster than world champion team mate sebastian vettel in a red bull one-two in friday's first free practice for the spanish grand prix. ]]> </description> </item> <item> <title>roundup: rose plans to keep firing away for the bulls</title> <link> http://feeds1.nytimes.com/~r/nyt/rss/sports/~3/65nlj2bc7ze/10nba.html </link> <pubDate>10 May 2011 08:10:04 +0000</pubDate> <category> <![CDATA[ sport ]]> </category> <description> <![CDATA[ the league m.v.p. said that he did not shoot too much in sunday's loss to atlanta, and that he just needed to stop missing so many. ]]> </description> </item> <item> <title>u.s. orders transcanada to shut pipeline</title> <link> http://feeds.nytimes.com/click.phdo?i=637f028c4376eb6dbc0fa4ed5c1f6095 </link> <pubDate>04 Jun 2011 04:53:09 +0000</pubDate> <category> <![CDATA[ sci_tech ]]> </category> <description> <![CDATA[ after spills, the department of transportation declares that the pipeline poses a decisive threat and that corrective action is needed. ]]> </description> </item> <item> <title>blast kills 9 at afghan base, including 5 from nato</title> <link> http://feeds.nytimes.com/click.phdo?i=690a3d3f505d436741cdfb9a4616bae4 </link> <pubDate>17 Apr 2011 07:01:25 +0000</pubDate> <category> <![CDATA[ world ]]> </category> <description> <![CDATA[ five nato service members and at least four afghan troops were killed by a suicide bomber in an afghan national security uniform as the taliban warned it would step up its infiltration of local forces. ]]> </description> </item> <item> <title>honoring freedom riders at an old bus station</title> <link> http://feeds.nytimes.com/click.phdo?i=9f53f6078660f4a1e38a0f657f6b0b89 </link> <pubDate>22 May 2011 03:27:07 +0000</pubDate> <category> <![CDATA[ us ]]> </category> <description> <![CDATA[ the site of a mob attack on freedom riders in 1961 has been turned into a museum, and some of the riders returned for its dedication. ]]> </description> </item> <item> <title>editorial: when states punish women</title> <link> http://feeds.nytimes.com/click.phdo?i=83372f745f0a8d28b4d14d7abb663d91 </link> <pubDate>03 Jun 2011 17:31:20 +0000</pubDate> <category> <![CDATA[ health ]]> </category> <description> <![CDATA[ federal officials are right to block the republican drive against planned parenthood. ]]> </description> </item> <item> <title>shia labeouf: megan fox had a 'hard time' with sex-driven role</title> <link> http://rssfeeds.usatoday.com/~r/usatoday-lifetopstories/~3/m-n5ytzienu/1 </link> <pubDate>03 Jun 2011 20:58:00 +0000</pubDate> <category> <![CDATA[ entertainment ]]> </category> <description> <![CDATA[ shia labeouf gives his take on why megan fox and 'transformers' director michael bay never really got along. (although she was pretty clear when ... ]]> </description> </item> <item> <title>"book of mormon", "anything goes" top drama desk awards</title> <link> http://feeds.reuters.com/~r/reuters/entertainment/~3/a4amzzafdws/us-stage-dramadesk-idustre74n0j920110524 </link> <pubDate>24 May 2011 06:11:11 +0000</pubDate> <category> <![CDATA[ entertainment ]]> </category> <description> <![CDATA[ the hit musicals "the book of mormon" and revival of "anything goes" each won five drama desk awards on monday, bolstering their front-runner status going into next month's tony awards, broadway's top honors. ]]> </description> </item> <item> <title>spain 4, u.s. 0 : with more important games to come, u.s. is taught low-cost lesson</title> <link> http://feeds1.nytimes.com/~r/nyt/rss/sports/~3/iursc72ijse/spain-teaches-united-states-a-low-cost-lesson.html </link> <pubDate>05 Jun 2011 10:00:39 +0000</pubDate> <category> <![CDATA[ sport ]]> </category> <description> <![CDATA[ spain, the world cup champion, scored three times in 13 minutes in the first half and generally had its way in a 4-0 victory at gillette stadium. ]]> </description> </item> <item> <title>ex-central banker warns on canada health spending</title> <link> http://feeds.reuters.com/~r/reuters/healthnews/~3/uh9hbultvqs/us-health-idustre7354z420110406 </link> <pubDate>06 Apr 2011 19:29:18 +0000</pubDate> <category> <![CDATA[ health ]]> </category> <description> <![CDATA[ canada can't keep spending on healthcare at its current rate, and must choose between a number of unpopular options for its state-funded medical system, a former central bank chief said on wednesday. ]]> </description> </item> <item> <title>in malaysia, shiites struggle to practice their faith</title> <link> http://feeds.nytimes.com/click.phdo?i=086c50149de5d2cdf7fd50f0e87267a9 </link> <pubDate>24 Mar 2011 06:55:42 +0000</pubDate> <category> <![CDATA[ world ]]> </category> <description> <![CDATA[ where sunni islam is the official religion, other forms of the faith, including shiite islam, are considered deviant and are not allowed to be spread. ]]> </description> </item> <item> <title>cisco to pay first-ever quarterly dividend</title> <link> http://feeds.reuters.com/~r/reuters/businessnews/~3/k7w3p_wwe_g/us-cisco-idustre72h3co20110318 </link> <pubDate>18 Mar 2011 18:26:35 +0000</pubDate> <category> <![CDATA[ business ]]> </category> <description> <![CDATA[ top network equipment maker cisco systems inc plans to pay a dividend for the first time, helping appease investors' concerns about slowing growth by returning more of its ample... ]]> </description> </item> <item> <title>accuser in duke lacrosse case indicted on murder charge</title> <link> http://rssfeeds.usatoday.com/~r/usatodaycomsports-topstories/~3/zq8wagghoxk/2011-04-18-duke-accuser-crystal-mangum-murder-charge_n.htm </link> <pubDate>19 Apr 2011 00:33:31 +0000</pubDate> <category> <![CDATA[ sport ]]> </category> <description> <![CDATA[ the woman who falsely accused duke lacrosse players of raping her is now charged with murder in her boyfriend's death. crystal mangum was charged ... ]]> </description> </item> <item> <title>lawrence taylor gives his side after sentencing</title> <link> http://feeds1.nytimes.com/~r/nyt/rss/sports/~3/z2vjxvtut3s/ </link> <pubDate>24 Mar 2011 11:52:31 +0000</pubDate> <category> <![CDATA[ sport ]]> </category> <description> <![CDATA[ the former giants great said of prostitution, "i'm not saying it's right but it's the oldest profession in the world." ]]> </description> </item> <item> <title>oil drilling off cuba raises specter of what-if</title> <link> http://feeds.nytimes.com/click.phdo?i=7f3ff3420104372df2d6b2d8e78a47a0 </link> <pubDate>06 Jun 2011 21:02:39 +0000</pubDate> <category> <![CDATA[ sci_tech ]]> </category> <description> <![CDATA[ the prospect of a blowout in cuban waters may give the obama administration an incentive to open the way for emergency assistance from the united states. ]]> </description> </item> <item> <title>tuscaloosa honors tornado victims, volunteers with vigil</title> <link> http://feeds.reuters.com/~r/reuters/domesticnews/~3/du9r6qyrqto/us-tornado-tuscaloosa-idustre7512sh20110602 </link> <pubDate>02 Jun 2011 14:21:22 +0000</pubDate> <category> <![CDATA[ us ]]> </category> <description> <![CDATA[ more than a thousand people lit candles on wednesday night and remembered the dozens who lost their lives after a tornado roared through tuscaloosa, alabama, in april. ]]> </description> </item> <item> <title>"shaq" wise-cracks his way into retirement</title> <link> http://feeds.reuters.com/~r/reuters/sportsnews/~3/tfkzui7iygg/us-nba-shaquille-idustre75264j20110604 </link> <pubDate>04 Jun 2011 02:30:06 +0000</pubDate> <category> <![CDATA[ sport ]]> </category> <description> <![CDATA[ shaquille o'neal formally announced his retirement on friday, ending a professional nba career that spanned nearly two decades. ]]> </description> </item> <item> <title>shaquille o'neal confirms retirement</title> <link> http://feeds.reuters.com/~r/reuters/sportsnews/~3/qsi8jwkljca/us-nba-shaquille-idustre75264j20110603 </link> <pubDate>03 Jun 2011 20:26:17 +0000</pubDate> <category> <![CDATA[ sport ]]> </category> <description> <![CDATA[ shaquille o'neal formally announced his retirement friday, ending a professional career in the national basketball association that spanned nearly two decades. ]]> </description> </item> <item> <title>does work interfere with breastfeeding?</title> <link> http://feeds.reuters.com/~r/reuters/healthnews/~3/j3l5j_-wp6o/us-work-breastfeeding-idustre74u61r20110531 </link> <pubDate>31 May 2011 21:59:41 +0000</pubDate> <category> <![CDATA[ health ]]> </category> <description> <![CDATA[ the sooner a new mother goes back to work after giving birth, the less likely she is to breastfeed her baby, researchers have found. ]]> </description> </item> <item> <title>al central preview: tigers look to dethrone twins</title> <link> http://rssfeeds.usatoday.com/~r/usatodaycomsports-topstories/~3/eybmcvziofm/2011-03-28-american-league-central-preview_n.htm </link> <pubDate>29 Mar 2011 10:23:08 +0000</pubDate> <category> <![CDATA[ sport ]]> </category> <description> <![CDATA[ teams are in order of predicted finish. "scouts' report" is based on scouts who have watched al central teams this spring and requested anonymity ... ]]> </description> </item> <item> <title>angels have decisions minus morales, braves hopeful on heyward</title> <link> http://rssfeeds.usatoday.com/~r/usatodaycomsports-topstories/~3/nqmmqx459jq/1 </link> <pubDate>12 May 2011 17:48:00 +0000</pubDate> <category> <![CDATA[ sport ]]> </category> <description> <![CDATA[ which team is hurting the most today? ]]> </description> </item> <item> <title>v.c.u. turned barbs into a dream trip to the round of 16</title> <link> http://feeds1.nytimes.com/~r/nyt/rss/sports/~3/ytlzxfsep9q/25vcu.html </link> <pubDate>26 Mar 2011 01:13:52 +0000</pubDate> <category> <![CDATA[ sport ]]> </category> <description> <![CDATA[ unheralded virginia commonwealth has won three n.c.a.a. tournament games by a combined 49 points, going from the first four to the round of 16. ]]> </description> </item> <item> <title>thai and cambodian troops exchange fire near ancient temple</title> <link> http://feeds.reuters.com/~r/reuters/worldnews/~3/ezzh9qj2nni/us-thailand-cambodia-idustre73p3rh20110426 </link> <pubDate>26 Apr 2011 16:40:26 +0000</pubDate> <category> <![CDATA[ world ]]> </category> <description> <![CDATA[ thai and cambodia troops fought with short-range rockets and guns near 900-year-old preah vihear temple tuesday, opening a second front in a five-day confrontation that has killed 13 people in southeast asia's bloodiest border dispute in years. ]]> </description> </item> <item> <title>cambodia pm welcomes talks after thai border clashes</title> <link> http://feeds.reuters.com/~r/reuters/worldnews/~3/8wjr3lfefaa/us-thailand-cambodia-idustre73p3rh20110427 </link> <pubDate>27 Apr 2011 18:50:17 +0000</pubDate> <category> <![CDATA[ world ]]> </category> <description> <![CDATA[ cambodian prime minister hun sen offered wednesday to meet one-on-one with his thai counterpart after six days of sporadic fighting that has killed at least 14 people, raising hopes of a ceasefire in southeast asia's bloodiest border dispute in years. ]]> </description> </item> <item> <title>analysis: on cloud 2: making fans of customers on social media</title> <link> http://feeds.reuters.com/~r/reuters/technologynews/~3/fzzbsikca3w/us-socialcrm-idustre73o4sj20110425 </link> <pubDate>25 Apr 2011 20:39:31 +0000</pubDate> <category> <![CDATA[ sci_tech ]]> </category> <description> <![CDATA[ in may 2008, a blog post caught computer maker dell inc by surprise: popular tech blog gizmodo had broken news about dell's inspiron 910 mini-notebook -- months ahead of its launch -- after seeing ceo michael dell toting the notebook at an industry conference. ]]> </description> </item> <item> <title>states move to make biking safer</title> <link> http://rssfeeds.usatoday.com/~r/usatodaycomnation-topstories/~3/uzql78u795k/2011-05-22-biking-safety-legislation-national-bike-month_n.htm </link> <pubDate>23 May 2011 18:57:25 +0000</pubDate> <category> <![CDATA[ us ]]> </category> <description> <![CDATA[ more states are trying to make it safer to bicycle, as more cyclists hit the road ]]> </description> </item> <item> <title>keeping score: which team has the right stuff to win the cup?</title> <link> http://feeds1.nytimes.com/~r/nyt/rss/sports/~3/d52hae7u7rq/ </link> <pubDate>31 May 2011 01:30:48 +0000</pubDate> <category> <![CDATA[ sport ]]> </category> <description> <![CDATA[ focusing on concepts of sports psychology like big-game experience, leadership on the ice and consistency can help determine who will win the stanley cup. ]]> </description> </item> <item> <title>new armed services chairman is ready to be heard</title> <link> http://feeds.nytimes.com/click.phdo?i=bf8f7c96d4447e7a631d74ae52884383 </link> <pubDate>17 Mar 2011 07:30:35 +0000</pubDate> <category> <![CDATA[ us ]]> </category> <description> <![CDATA[ representative howard p. mckeon, the new chairman of the house armed services committee, has not shied away from opposing the administration. ]]> </description> </item> <item> <title>aflac picks new duck voice to replace gottfried</title> <link> http://feeds.reuters.com/~r/reuters/domesticnews/~3/_qkyjk0wo28/us-aflac-idustre73p6ay20110426 </link> <pubDate>26 Apr 2011 21:41:13 +0000</pubDate> <category> <![CDATA[ us ]]> </category> <description> <![CDATA[ a clean-cut minnesota father of three is the new voice of insurer aflac, taking over the role of the acerbic quacking duck from the fired comedian gilbert gottfried. ]]> </description> </item> <item> <title>feds now target execs, not just companies, in health frauds</title> <link> http://rssfeeds.usatoday.com/~r/usatodaycommoney-topstories/~3/bv42ilnbr1o/2011-05-31-execs-health-care-fraud_n.htm </link> <pubDate>31 May 2011 21:57:04 +0000</pubDate> <category> <![CDATA[ business ]]> </category> <description> <![CDATA[ federal enforcers are targeting individual executives in health care fraud cases that used to be aimed at their corporations. ]]> </description> </item> <item> <title>zuckerberg says not opening facebook to under-13s</title> <link> http://feeds.reuters.com/~r/reuters/technologynews/~3/paj1z0s50ai/us-facebook-zuckerberg-idustre74o5l020110525 </link> <pubDate>25 May 2011 18:12:26 +0000</pubDate> <category> <![CDATA[ sci_tech ]]> </category> <description> <![CDATA[ facebook is not working on opening up the world's biggest social network to children under the age of 13 in the short term, founder and chief executive mark zuckerberg said wednesday, contradicting some media reports. ]]> </description> </item> <item> <title>top draft prospect: i want to shake commissioner's hand at draft</title> <link> http://rssfeeds.usatoday.com/~r/usatodaycomsports-topstories/~3/xprfhxrd4ls/1 </link> <pubDate>15 Mar 2011 16:53:00 +0000</pubDate> <category> <![CDATA[ sport ]]> </category> <description> <![CDATA[ patrick peterson -- a potential no. 1 overall pick in april's nfl draft -- wants to be in new york to hear his name called. ]]> </description> </item> <item> <title>the office: sedentary no more</title> <link> http://feeds.nytimes.com/click.phdo?i=a7d78bd8819a40bc95fdcc657e727695 </link> <pubDate>28 May 2011 21:28:45 +0000</pubDate> <category> <![CDATA[ business ]]> </category> <description> <![CDATA[ less physical activity at work may be a major but overlooked culprit in rising american obesity. this calls for a management solution. ]]> </description> </item> <item> <title>la lakers survive marathon test to eclipse phoenix suns</title> <link> http://feeds.reuters.com/~r/reuters/sportsnews/~3/2tuo0t0hqai/us-nba-lakers-idustre72m1fn20110323 </link> <pubDate>23 Mar 2011 08:23:51 +0000</pubDate> <category> <![CDATA[ sport ]]> </category> <description> <![CDATA[ kobe bryant delivered a sensational performance to lead the los angeles lakers to a roller-coaster 139-137 triple-overtime victory over the phoenix suns on tuesday. ]]> </description> </item> <item> <title>u.s. chases elusive currency-detection technology</title> <link> http://feeds.reuters.com/~r/reuters/technologynews/~3/vsjcpv8dcc4/us-financial-cash-idustre7436bx20110504 </link> <pubDate>04 May 2011 20:08:11 +0000</pubDate> <category> <![CDATA[ sci_tech ]]> </category> <description> <![CDATA[ to combat money laundering and contain the drug war raging along the u.s.-mexico border, u.s. authorities are seeking technology to detect the hoards of cash that smugglers try to spirit abroad. ]]> </description> </item> <item> <title>battle against lice may be aided by new genome study</title> <link> http://rssfeeds.usatoday.com/~r/usatodaycomscienceandspace-topstories/~3/4hjy5os3ite/2010-06-21-body-louse-genome_n.htm </link> <pubDate>21 Jun 2010 21:01:00 +0000</pubDate> <category> <![CDATA[ sci_tech ]]> </category> <description> <![CDATA[ sometimes scientific research can be a lousy job. ]]> </description> </item> <item> <title>odd behavior of neighbors makes sense after bin laden killing</title> <link> http://feeds.reuters.com/~r/reuters/worldnews/~3/nd-5ra-cahu/us-behaviour-neighbours-idustre7431yj20110504 </link> <pubDate>04 May 2011 13:23:50 +0000</pubDate> <category> <![CDATA[ world ]]> </category> <description> <![CDATA[ the children in the white mansion with closed circuit cameras in abbottabad never came out to play. ]]> </description> </item> <item> <title>novartis vaccine shields against meningitis cause</title> <link> http://feeds.reuters.com/~r/reuters/healthnews/~3/gnpfmdgdo5o/us-novartis-idustre7581fd20110609 </link> <pubDate>09 Jun 2011 10:19:22 +0000</pubDate> <category> <![CDATA[ health ]]> </category> <description> <![CDATA[ novartis ag's bexsero vaccine helps protect toddlers against the most common cause of meningitis when used as a booster, the swiss drugmaker said on thursday, giving its meningitis franchise another lift. ]]> </description> </item> <item> <title>u.s. nuclear investment to pause: analysts</title> <link> http://feeds.reuters.com/~r/reuters/businessnews/~3/zytx3lw7gqy/us-investing-nuclear-idustre7300dr20110401 </link> <pubDate>01 Apr 2011 04:10:45 +0000</pubDate> <category> <![CDATA[ business ]]> </category> <description> <![CDATA[ plans for nuclear power investment in the united states will be sidelined but not derailed by the problems japan is having with the fukushima nuclear plant, experts said in a panel discussion on thursday. ]]> </description> </item> <item> <title>u.s. markets calm as greece weighs on europe</title> <link> http://feeds.nytimes.com/click.phdo?i=201975f219cd9aca89ff538d246fc0e5 </link> <pubDate>09 May 2011 16:03:02 +0000</pubDate> <category> <![CDATA[ business ]]> </category> <description> <![CDATA[ stocks fell in europe, pressured by financials, as investors sold riskier assets after talks on a revised bailout package for greece. ]]> </description> </item> <item> <title>royals legend paul splittorff dies at 64</title> <link> http://rssfeeds.usatoday.com/~r/usatodaycomsports-topstories/~3/3z906no5ave/1 </link> <pubDate>25 May 2011 16:17:00 +0000</pubDate> <category> <![CDATA[ sport ]]> </category> <description> <![CDATA[ paul splittorff, who won a club-record 166 games while spending his entire 15-year career with the royals, died on wednesday at 64. ]]> </description> </item> <item> <title>'idol' covers elton john: the studio recordings</title> <link> http://rssfeeds.usatoday.com/~r/usatoday-lifetopstories/~3/fm1wmmujifa/1 </link> <pubDate>01 Apr 2011 18:48:00 +0000</pubDate> <category> <![CDATA[ entertainment ]]> </category> <description> <![CDATA[ this week's "american idol" performances were a remarkably consistent bunch. nobody did a bad job of covering elton john, at least not from the ... ]]> </description> </item> <item> <title>lohan gets jail sentence for probation violation</title> <link> http://rssfeeds.usatoday.com/~r/usatoday-lifetopstories/~3/dx_7_7tpwti/2011-04-22-lindsay-lohan-jail_n.htm </link> <pubDate>23 Apr 2011 03:43:25 +0000</pubDate> <category> <![CDATA[ entertainment ]]> </category> <description> <![CDATA[ a judge sentenced lindsay lohan to 120 days in jail on friday for a probation violation after hearing evidence against the actress in a theft ... ]]> </description> </item> <item> <title>opposition forces in ivory coast take towns on 2 fronts</title> <link> http://feeds.nytimes.com/click.phdo?i=7e6a7c4263c339b592b1bd2c0733ab69 </link> <pubDate>30 Mar 2011 07:20:32 +0000</pubDate> <category> <![CDATA[ world ]]> </category> <description> <![CDATA[ ivory coast tipped further toward civil war tuesday as soldiers loyal to alassane ouattara, the former prime minister and banker, continued their fight against the strongman laurent gbagbo. ]]> </description> </item> <item> <title>honda, mazda to resume some production</title> <link> http://feeds.reuters.com/~r/reuters/businessnews/~3/k5pls4xbs5u/us-honda-mazda-idustre72u7hi20110331 </link> <pubDate>31 Mar 2011 23:52:35 +0000</pubDate> <category> <![CDATA[ business ]]> </category> <description> <![CDATA[ honda motor co and mazda motor corp on thursday became the latest major automakers to say they would resume some production in japan after halting plant operations following the earthquake and tsunami of march 11. ]]> </description> </item> <item> <title>demand media rebuffs, redesigns</title> <link> http://rssfeeds.usatoday.com/~r/usatodaycommoney-topstories/~3/r0bmfk236ts/2011-03-16-demand-media-redesign.htm </link> <pubDate>16 Mar 2011 14:21:35 +0000</pubDate> <category> <![CDATA[ business ]]> </category> <description> <![CDATA[ demand media is trumpeting a new look: ehow has gotten a face lift. ]]> </description> </item> <item> <title>big east replay: march 10</title> <link> http://feeds1.nytimes.com/~r/nyt/rss/sports/~3/hhqtiycgqgi/sptsbigeast0310.html </link> <pubDate>11 Mar 2011 06:19:16 +0000</pubDate> <category> <![CDATA[ sport ]]> </category> <description> <![CDATA[ a look at the big east tournament quarterfinals at madison square garden includes a buzzer beater and a dunk that didn?t quite work. ]]> </description> </item> <item> <title>'gunsmoke' star james arness dies</title> <link> http://rssfeeds.usatoday.com/~r/usatoday-lifetopstories/~3/76omqx1ezyk/1 </link> <pubDate>03 Jun 2011 19:27:00 +0000</pubDate> <category> <![CDATA[ entertainment ]]> </category> <description> <![CDATA[ flowers will be placed on the hollywood walk of fame of james arness, who died today at age 88. ]]> </description> </item> <item> <title>former sony chairman sony credited with developing cds dies</title> <link> http://rssfeeds.usatoday.com/~r/usatodaycommoney-topstories/~3/hhr3vytzofi/2011-04-23-sony-chairman-compact-disc-dies.htm </link> <pubDate>23 Apr 2011 19:32:08 +0000</pubDate> <category> <![CDATA[ business ]]> </category> <description> <![CDATA[ former sony president and chairman norio ohga, credited with expanding the company from electronics hardware to software and entertainment and ... ]]> </description> </item> <item> <title>att follows its customers overseas</title> <link> http://feeds.nytimes.com/click.phdo?i=23c3b23fe1cf9f1f864a8e389d678d8c </link> <pubDate>19 Apr 2011 07:20:50 +0000</pubDate> <category> <![CDATA[ sci_tech ]]> </category> <description> <![CDATA[ the former u.s. telephone monopoly is pursuing a potentially lucrative strategy abroad, offering one-stop service to multinational companies. ]]> </description> </item> <item> <title>investing in transportation</title> <link> http://feeds.nytimes.com/click.phdo?i=e66ec27c4b9ff40dde18b1ddab219622 </link> <pubDate>03 Jun 2011 13:46:31 +0000</pubDate> <category> <![CDATA[ business ]]> </category> <description> <![CDATA[ spending more on transportation -- and spending it wisely -- would create jobs and improve the nation's competitiveness, an economist writes. ]]> </description> </item> <item> <title>creating plays, but holding on to the day job</title> <link> http://feeds.nytimes.com/click.phdo?i=5db0218a0c0dad8315aec38b6ae6b243 </link> <pubDate>26 Mar 2011 23:16:52 +0000</pubDate> <category> <![CDATA[ entertainment ]]> </category> <description> <![CDATA[ the playwright sharr white has embraced the practical way in which he lives his life in his creative endeavors, and the approach has helped make his play 'the other place' his first major new york production. ]]> </description> </item> <item> <title>u.s. moves wikileaks soldier bradley manning to kansas jail</title> <link> http://feeds.reuters.com/~r/reuters/domesticnews/~3/pdftbp0klhy/us-usa-wikileaks-manning-idustre73i79s20110419 </link> <pubDate>20 Apr 2011 00:56:08 +0000</pubDate> <category> <![CDATA[ us ]]> </category> <description> <![CDATA[ the obama administration, under criticism for its treatment of the u.s. soldier accused of leaking secret documents that appeared on the wikileaks website, is transferring the detainee to a kansas jail. ]]> </description> </item> <item> <title>long-term costs next challenge for f-35 jet program</title> <link> http://feeds.reuters.com/~r/reuters/domesticnews/~3/q3ycn_o2p8e/us-lockheed-fighter-idustre73k8fl20110421 </link> <pubDate>22 Apr 2011 01:14:07 +0000</pubDate> <category> <![CDATA[ us ]]> </category> <description> <![CDATA[ the pentagon's next challenge in the $382 billion lockheed martin corp f-35 fighter program will be cutting longer-term operating and maintenance costs and keeping unit production costs low. ]]> </description> </item> <item> <title>a minute with: kara dioguardi about her return to tv</title> <link> http://feeds.reuters.com/~r/reuters/entertainment/~3/exupscpbfzg/us-karadioguardi-idustre74o48w20110525 </link> <pubDate>25 May 2011 15:59:54 +0000</pubDate> <category> <![CDATA[ entertainment ]]> </category> <description> <![CDATA[ as a former "american idol" judge, singer, songwriter and producer, kara dioguardi, made her mark offering no-nonsense feedback to contestants hoping for stardom on the popular singing talent contest. ]]> </description> </item> <item> <title>bnp's bumper q1 sets high bar for rivals</title> <link> http://feeds.reuters.com/~r/reuters/businessnews/~3/1gi9jj39eh8/us-bnpparibas-idustre7430t120110504 </link> <pubDate>04 May 2011 11:50:03 +0000</pubDate> <category> <![CDATA[ business ]]> </category> <description> <![CDATA[ bnp paribas, france's biggest listed bank, beat first-quarter forecasts, driven by strong retail growth and resilient investment banking that bolstered investor confidence and set a high bar for rivals. ]]> </description> </item> <item> <title>moviegoers not eager to see mel gibson's "beaver"</title> <link> http://feeds.reuters.com/~r/reuters/entertainment/~3/iazwgeg-ada/us-boxoffice-gibson-idustre7472jj20110509 </link> <pubDate>09 May 2011 18:07:28 +0000</pubDate> <category> <![CDATA[ entertainment ]]> </category> <description> <![CDATA[ mel gibson's long-delayed first movie since he was embroiled in a messy domestic dispute with his ex-girlfriend flopped at the weekend box office in north america. ]]> </description> </item> <item> <title>moviegoers not eager to see mel gibson's "beaver"</title> <link> http://feeds.reuters.com/~r/reuters/entertainment/~3/f2hpahb_61c/us-boxoffice-gibson-idustre7472jj20110508 </link> <pubDate>08 May 2011 23:45:53 +0000</pubDate> <category> <![CDATA[ entertainment ]]> </category> <description> <![CDATA[ mel gibson's long-delayed first movie since he was embroiled in a messy domestic dispute with his ex-girlfriend flopped at the weekend box office in north america. ]]> </description> </item> <item> <title>saints coach must pay $1.15m in restitution for real estate scam</title> <link> http://rssfeeds.usatoday.com/~r/usatodaycomsports-topstories/~3/prznk3aoede/2011-03-11-travis-jones-real-estate-scam_n.htm </link> <pubDate>11 Mar 2011 19:20:35 +0000</pubDate> <category> <![CDATA[ sport ]]> </category> <description> <![CDATA[ saints assistant travis jones has been sentenced to three years probation, 100 hours of community service and ordered to pay $1.15 million in ... ]]> </description> </item> </rss>
{ "content_hash": "5edc853eaa42f7137d53cade1a74df2a", "timestamp": "", "source": "github", "line_count": 1502, "max_line_length": 262, "avg_line_length": 33.82956058588549, "alnum_prop": 0.7088679839408014, "repo_name": "Kianoosh76/fop-project", "id": "421cdab9476eb3c69cc732798952128248683435", "size": "50812", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "static/news/221.xml", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "10080" }, { "name": "JavaScript", "bytes": "4894" }, { "name": "Python", "bytes": "26308" } ], "symlink_target": "" }
package org.apache.accumulo.tserver.log; import static org.apache.accumulo.tserver.logger.LogEvents.COMPACTION_FINISH; import static org.apache.accumulo.tserver.logger.LogEvents.COMPACTION_START; import static org.apache.accumulo.tserver.logger.LogEvents.DEFINE_TABLET; import static org.apache.accumulo.tserver.logger.LogEvents.MUTATION; import static org.apache.accumulo.tserver.logger.LogEvents.OPEN; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.reset; import static org.easymock.EasyMock.verify; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Set; import java.util.TreeMap; import org.apache.accumulo.core.conf.ConfigurationCopy; import org.apache.accumulo.core.conf.DefaultConfiguration; import org.apache.accumulo.core.conf.Property; import org.apache.accumulo.core.crypto.CryptoServiceFactory; import org.apache.accumulo.core.data.Mutation; import org.apache.accumulo.core.data.TableId; import org.apache.accumulo.core.data.Value; import org.apache.accumulo.core.dataImpl.KeyExtent; import org.apache.accumulo.core.file.rfile.bcfile.Compression; import org.apache.accumulo.core.file.rfile.bcfile.Utils; import org.apache.accumulo.core.file.streams.SeekableDataInputStream; import org.apache.accumulo.core.util.Pair; import org.apache.accumulo.server.ServerContext; import org.apache.accumulo.server.data.ServerMutation; import org.apache.accumulo.server.fs.VolumeManagerImpl; import org.apache.accumulo.server.log.SortedLogState; import org.apache.accumulo.tserver.logger.LogEvents; import org.apache.accumulo.tserver.logger.LogFileKey; import org.apache.accumulo.tserver.logger.LogFileValue; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.Text; import org.easymock.EasyMock; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; @SuppressFBWarnings(value = "PATH_TRAVERSAL_IN", justification = "paths not set by user input") public class SortedLogRecoveryTest { static final int bufferSize = 5; static final KeyExtent extent = new KeyExtent(TableId.of("table"), null, null); static final Text cf = new Text("cf"); static final Text cq = new Text("cq"); static final Value value = new Value("value"); static ServerContext context; static LogSorter logSorter; @Rule public TemporaryFolder tempFolder = new TemporaryFolder(new File(System.getProperty("user.dir") + "/target")); @Before public void setup() { context = EasyMock.createMock(ServerContext.class); logSorter = new LogSorter(context, DefaultConfiguration.getInstance()); } static class KeyValue implements Comparable<KeyValue> { public final LogFileKey key; public final LogFileValue value; KeyValue() { key = new LogFileKey(); value = new LogFileValue(); } @Override public int hashCode() { return Objects.hashCode(key) + Objects.hashCode(value); } @Override public boolean equals(Object obj) { return this == obj || (obj != null && obj instanceof KeyValue && 0 == compareTo((KeyValue) obj)); } @Override public int compareTo(KeyValue o) { return key.compareTo(o.key); } } private static KeyValue createKeyValue(LogEvents type, long seq, int tid, Object fileExtentMutation) { KeyValue result = new KeyValue(); result.key.event = type; result.key.seq = seq; result.key.tabletId = tid; switch (type) { case OPEN: result.key.tserverSession = (String) fileExtentMutation; break; case COMPACTION_FINISH: break; case COMPACTION_START: result.key.filename = (String) fileExtentMutation; break; case DEFINE_TABLET: result.key.tablet = (KeyExtent) fileExtentMutation; break; case MUTATION: result.value.mutations = Arrays.asList((Mutation) fileExtentMutation); break; case MANY_MUTATIONS: result.value.mutations = Arrays.asList((Mutation[]) fileExtentMutation); } return result; } private static class CaptureMutations implements MutationReceiver { public ArrayList<Mutation> result = new ArrayList<>(); @Override public void receive(Mutation m) { // make a copy of Mutation: result.add(m); } } private List<Mutation> recover(Map<String,KeyValue[]> logs, KeyExtent extent) throws IOException { return recover(logs, new HashSet<>(), extent, bufferSize); } private List<Mutation> recover(Map<String,KeyValue[]> logs, Set<String> files, KeyExtent extent, int bufferSize) throws IOException { final String workdir = tempFolder.newFolder().getAbsolutePath(); try (var fs = VolumeManagerImpl.getLocalForTesting(workdir)) { expect(context.getVolumeManager()).andReturn(fs).anyTimes(); expect(context.getCryptoService()).andReturn(CryptoServiceFactory.newDefaultInstance()) .anyTimes(); expect(context.getConfiguration()).andReturn(DefaultConfiguration.getInstance()).anyTimes(); replay(context); final Path workdirPath = new Path("file://" + workdir); fs.deleteRecursively(workdirPath); ArrayList<Path> dirs = new ArrayList<>(); for (Entry<String,KeyValue[]> entry : logs.entrySet()) { String destPath = workdir + "/" + entry.getKey(); FileSystem ns = fs.getFileSystemByPath(new Path(destPath)); // convert test object to Pairs for LogSorter, flushing based on bufferSize List<Pair<LogFileKey,LogFileValue>> buffer = new ArrayList<>(); int parts = 0; for (KeyValue pair : entry.getValue()) { buffer.add(new Pair<>(pair.key, pair.value)); if (buffer.size() >= bufferSize) { logSorter.writeBuffer(destPath, buffer, parts++); buffer.clear(); } } logSorter.writeBuffer(destPath, buffer, parts); ns.create(SortedLogState.getFinishedMarkerPath(destPath)).close(); dirs.add(new Path(destPath)); } // Recover SortedLogRecovery recovery = new SortedLogRecovery(context); CaptureMutations capture = new CaptureMutations(); recovery.recover(extent, dirs, files, capture); verify(context); return capture.result; } } @Test public void testCompactionCrossesLogs() throws IOException { Mutation ignored = new ServerMutation(new Text("ignored")); ignored.put(cf, cq, value); Mutation m = new ServerMutation(new Text("row1")); m.put(cf, cq, value); Mutation m2 = new ServerMutation(new Text("row2")); m2.put(cf, cq, value); KeyValue[] entries = {createKeyValue(OPEN, 0, 1, "2"), createKeyValue(DEFINE_TABLET, 1, 1, extent), createKeyValue(COMPACTION_START, 3, 1, "/t1/f1"), createKeyValue(MUTATION, 2, 1, ignored), createKeyValue(MUTATION, 4, 1, ignored),}; KeyValue[] entries2 = {createKeyValue(OPEN, 0, 1, "2"), createKeyValue(DEFINE_TABLET, 1, 1, extent), createKeyValue(COMPACTION_START, 4, 1, "/t1/f1"), createKeyValue(MUTATION, 7, 1, m),}; KeyValue[] entries3 = {createKeyValue(OPEN, 0, 2, "23"), createKeyValue(DEFINE_TABLET, 1, 1, extent), createKeyValue(COMPACTION_START, 5, 1, "/t1/f2"), createKeyValue(COMPACTION_FINISH, 6, 1, null), createKeyValue(MUTATION, 3, 1, ignored), createKeyValue(MUTATION, 4, 1, ignored),}; KeyValue[] entries4 = {createKeyValue(OPEN, 0, 3, "69"), createKeyValue(DEFINE_TABLET, 1, 1, extent), createKeyValue(MUTATION, 2, 1, ignored), createKeyValue(MUTATION, 3, 1, ignored), createKeyValue(MUTATION, 4, 1, ignored),}; KeyValue[] entries5 = {createKeyValue(OPEN, 0, 4, "70"), createKeyValue(DEFINE_TABLET, 1, 1, extent), createKeyValue(COMPACTION_START, 3, 1, "/t1/f3"), createKeyValue(MUTATION, 2, 1, ignored), createKeyValue(MUTATION, 6, 1, m2),}; Map<String,KeyValue[]> logs = new TreeMap<>(); logs.put("entries", entries); logs.put("entries2", entries2); logs.put("entries3", entries3); logs.put("entries4", entries4); logs.put("entries5", entries5); // Recover List<Mutation> mutations = recover(logs, extent); // Verify recovered data assertEquals(2, mutations.size()); assertTrue(mutations.contains(m)); assertTrue(mutations.contains(m2)); } @Test public void testCompactionCrossesLogs5() throws IOException { // Create a test log Mutation ignored = new ServerMutation(new Text("ignored")); ignored.put(cf, cq, value); Mutation m = new ServerMutation(new Text("row1")); m.put(cf, cq, value); Mutation m2 = new ServerMutation(new Text("row2")); m2.put(cf, cq, value); Mutation m3 = new ServerMutation(new Text("row3")); m3.put(cf, cq, value); Mutation m4 = new ServerMutation(new Text("row4")); m4.put(cf, cq, value); KeyValue[] entries = {createKeyValue(OPEN, 0, -1, "1"), createKeyValue(DEFINE_TABLET, 1, 1, extent), createKeyValue(COMPACTION_START, 3, 1, "/t1/f1"), createKeyValue(MUTATION, 2, 1, ignored), createKeyValue(MUTATION, 4, 1, ignored),}; KeyValue[] entries2 = {createKeyValue(OPEN, 5, -1, "2"), createKeyValue(DEFINE_TABLET, 6, 1, extent), createKeyValue(MUTATION, 7, 1, ignored),}; // createKeyValue(COMPACTION_FINISH, 14, 1, null), KeyValue[] entries3 = {createKeyValue(OPEN, 8, -1, "3"), createKeyValue(DEFINE_TABLET, 9, 1, extent), createKeyValue(COMPACTION_FINISH, 10, 1, "/t1/f1"), createKeyValue(COMPACTION_START, 12, 1, "/t1/f2"), createKeyValue(COMPACTION_FINISH, 13, 1, "/t1/f2"), // createKeyValue(COMPACTION_FINISH, 14, 1, null), createKeyValue(MUTATION, 11, 1, ignored), createKeyValue(MUTATION, 15, 1, m), createKeyValue(MUTATION, 16, 1, m2),}; KeyValue[] entries4 = {createKeyValue(OPEN, 17, -1, "4"), createKeyValue(DEFINE_TABLET, 18, 1, extent), createKeyValue(COMPACTION_START, 20, 1, "/t1/f3"), createKeyValue(MUTATION, 19, 1, m3), createKeyValue(MUTATION, 21, 1, m4),}; Map<String,KeyValue[]> logs = new TreeMap<>(); logs.put("entries", entries); logs.put("entries2", entries2); logs.put("entries3", entries3); logs.put("entries4", entries4); // Recover List<Mutation> mutations = recover(logs, extent); // Verify recovered data assertEquals(4, mutations.size()); assertEquals(m, mutations.get(0)); assertEquals(m2, mutations.get(1)); assertEquals(m3, mutations.get(2)); assertEquals(m4, mutations.get(3)); } @Test public void testCompactionCrossesLogs6() throws IOException { // Create a test log Mutation ignored = new ServerMutation(new Text("ignored")); ignored.put(cf, cq, value); Mutation m = new ServerMutation(new Text("row1")); m.put(cf, cq, value); Mutation m2 = new ServerMutation(new Text("row2")); m2.put(cf, cq, value); Mutation m3 = new ServerMutation(new Text("row3")); m3.put(cf, cq, value); Mutation m4 = new ServerMutation(new Text("row4")); m4.put(cf, cq, value); Mutation m5 = new ServerMutation(new Text("row5")); m5.put(cf, cq, value); KeyValue[] entries = {createKeyValue(OPEN, 0, 1, "2"), createKeyValue(DEFINE_TABLET, 1, 1, extent), createKeyValue(MUTATION, 1, 1, ignored), createKeyValue(MUTATION, 3, 1, m),}; KeyValue[] entries2 = {createKeyValue(OPEN, 0, 1, "2"), createKeyValue(DEFINE_TABLET, 1, 1, extent), createKeyValue(COMPACTION_START, 2, 1, "/t1/f1"), createKeyValue(COMPACTION_FINISH, 3, 1, "/t1/f1"), createKeyValue(MUTATION, 3, 1, m2),}; Map<String,KeyValue[]> logs = new TreeMap<>(); logs.put("entries", entries); logs.put("entries2", entries2); // Recover List<Mutation> mutations = recover(logs, extent); // Verify recovered data assertEquals(2, mutations.size()); assertEquals(m, mutations.get(0)); assertEquals(m2, mutations.get(1)); } @Test public void testEmpty() throws IOException { // Create a test log KeyValue[] entries = {createKeyValue(OPEN, 0, -1, "1"), createKeyValue(DEFINE_TABLET, 1, 1, extent),}; Map<String,KeyValue[]> logs = new TreeMap<>(); logs.put("testlog", entries); // Recover List<Mutation> mutations = recover(logs, extent); // Verify recovered data assertEquals(0, mutations.size()); } @Test public void testMissingDefinition() { // Create a test log KeyValue[] entries = {createKeyValue(OPEN, 0, -1, "1"),}; Map<String,KeyValue[]> logs = new TreeMap<>(); logs.put("testlog", entries); // Recover try { recover(logs, extent); fail("tablet should not have been found"); } catch (Throwable t) {} } @Test public void testSimple() throws IOException { // Create a test log Mutation m = new ServerMutation(new Text("row1")); m.put(cf, cq, value); KeyValue[] entries = {createKeyValue(OPEN, 0, -1, "1"), createKeyValue(DEFINE_TABLET, 1, 1, extent), createKeyValue(MUTATION, 2, 1, m),}; Map<String,KeyValue[]> logs = new TreeMap<>(); logs.put("testlog", entries); // Recover List<Mutation> mutations = recover(logs, extent); // Verify recovered data assertEquals(1, mutations.size()); assertEquals(m, mutations.get(0)); } @Test public void testSkipSuccessfulCompaction() throws IOException { // Create a test log Mutation ignored = new ServerMutation(new Text("ignored")); ignored.put(cf, cq, value); Mutation m = new ServerMutation(new Text("row1")); m.put(cf, cq, value); KeyValue[] entries = {createKeyValue(OPEN, 0, -1, "1"), createKeyValue(DEFINE_TABLET, 1, 1, extent), createKeyValue(COMPACTION_START, 3, 1, "/t1/f1"), createKeyValue(COMPACTION_FINISH, 4, 1, null), createKeyValue(MUTATION, 2, 1, ignored), createKeyValue(MUTATION, 5, 1, m),}; Map<String,KeyValue[]> logs = new TreeMap<>(); logs.put("testlog", entries); // Recover List<Mutation> mutations = recover(logs, extent); // Verify recovered data assertEquals(1, mutations.size()); assertEquals(m, mutations.get(0)); } @Test public void testSkipSuccessfulCompactionAcrossFiles() throws IOException { // Create a test log Mutation ignored = new ServerMutation(new Text("ignored")); ignored.put(cf, cq, value); Mutation m = new ServerMutation(new Text("row1")); m.put(cf, cq, value); KeyValue[] entries = {createKeyValue(OPEN, 0, -1, "1"), createKeyValue(DEFINE_TABLET, 1, 1, extent), createKeyValue(COMPACTION_START, 3, 1, "/t1/f1"), createKeyValue(MUTATION, 2, 1, ignored),}; KeyValue[] entries2 = {createKeyValue(OPEN, 4, -1, "1"), createKeyValue(DEFINE_TABLET, 5, 1, extent), createKeyValue(COMPACTION_FINISH, 6, 1, null), createKeyValue(MUTATION, 7, 1, m),}; Map<String,KeyValue[]> logs = new TreeMap<>(); logs.put("entries", entries); logs.put("entries2", entries2); // Recover List<Mutation> mutations = recover(logs, extent); // Verify recovered data assertEquals(1, mutations.size()); assertEquals(m, mutations.get(0)); } @Test public void testGetMutationsAfterCompactionStart() throws IOException { // Create a test log Mutation ignored = new ServerMutation(new Text("ignored")); ignored.put(cf, cq, value); Mutation m = new ServerMutation(new Text("row1")); m.put(cf, cq, value); Mutation m2 = new ServerMutation(new Text("row2")); m2.put(cf, cq, new Value("123")); KeyValue[] entries = {createKeyValue(OPEN, 0, -1, "1"), createKeyValue(DEFINE_TABLET, 1, 1, extent), createKeyValue(COMPACTION_START, 3, 1, "/t1/f1"), createKeyValue(MUTATION, 2, 1, ignored), createKeyValue(MUTATION, 4, 1, m),}; KeyValue[] entries2 = {createKeyValue(OPEN, 5, -1, "1"), createKeyValue(DEFINE_TABLET, 4, 1, extent), createKeyValue(COMPACTION_FINISH, 4, 1, null), createKeyValue(MUTATION, 8, 1, m2),}; Map<String,KeyValue[]> logs = new TreeMap<>(); logs.put("entries", entries); logs.put("entries2", entries2); // Recover List<Mutation> mutations = recover(logs, extent); // Verify recovered data assertEquals(2, mutations.size()); assertEquals(m, mutations.get(0)); assertEquals(m2, mutations.get(1)); } @Test public void testDoubleFinish() throws IOException { // Create a test log Mutation ignored = new ServerMutation(new Text("ignored")); ignored.put(cf, cq, value); Mutation m = new ServerMutation(new Text("row1")); m.put(cf, cq, value); Mutation m2 = new ServerMutation(new Text("row2")); m2.put(cf, cq, new Value("123")); KeyValue[] entries = {createKeyValue(OPEN, 0, -1, "1"), createKeyValue(DEFINE_TABLET, 1, 1, extent), createKeyValue(COMPACTION_FINISH, 2, 1, null), createKeyValue(COMPACTION_START, 4, 1, "/t1/f1"), createKeyValue(COMPACTION_FINISH, 5, 1, null), createKeyValue(MUTATION, 3, 1, ignored), createKeyValue(MUTATION, 5, 1, m), createKeyValue(MUTATION, 5, 1, m2),}; Map<String,KeyValue[]> logs = new TreeMap<>(); logs.put("entries", entries); // Recover List<Mutation> mutations = recover(logs, extent); // Verify recovered data assertEquals(2, mutations.size()); assertEquals(m, mutations.get(0)); assertEquals(m2, mutations.get(1)); } @Test public void testCompactionCrossesLogs2() throws IOException { // Create a test log Mutation ignored = new ServerMutation(new Text("ignored")); ignored.put(cf, cq, value); Mutation m = new ServerMutation(new Text("row1")); m.put(cf, cq, value); Mutation m2 = new ServerMutation(new Text("row2")); m2.put(cf, cq, value); Mutation m3 = new ServerMutation(new Text("row3")); m3.put(cf, cq, value); KeyValue[] entries = {createKeyValue(OPEN, 0, -1, "1"), createKeyValue(DEFINE_TABLET, 1, 1, extent), createKeyValue(COMPACTION_START, 3, 1, "/t1/f1"), createKeyValue(MUTATION, 2, 1, ignored), createKeyValue(MUTATION, 4, 1, m),}; KeyValue[] entries2 = {createKeyValue(OPEN, 5, -1, "1"), createKeyValue(DEFINE_TABLET, 4, 1, extent), createKeyValue(MUTATION, 4, 1, m2),}; KeyValue[] entries3 = {createKeyValue(OPEN, 8, -1, "1"), createKeyValue(DEFINE_TABLET, 4, 1, extent), createKeyValue(COMPACTION_FINISH, 4, 1, null), createKeyValue(MUTATION, 4, 1, m3),}; Map<String,KeyValue[]> logs = new TreeMap<>(); logs.put("entries", entries); logs.put("entries2", entries2); logs.put("entries3", entries3); // Recover List<Mutation> mutations = recover(logs, extent); // Verify recovered data assertEquals(3, mutations.size()); assertTrue(mutations.contains(m)); assertTrue(mutations.contains(m2)); assertTrue(mutations.contains(m3)); } @Test public void testBug1() throws IOException { // this unit test reproduces a bug that occurred, nothing should recover Mutation m1 = new ServerMutation(new Text("row1")); m1.put(cf, cq, value); Mutation m2 = new ServerMutation(new Text("row2")); m2.put(cf, cq, value); KeyValue[] entries = {createKeyValue(OPEN, 0, -1, "1"), createKeyValue(DEFINE_TABLET, 1, 1, extent), createKeyValue(COMPACTION_START, 30, 1, "/t1/f1"), createKeyValue(COMPACTION_FINISH, 32, 1, "/t1/f1"), createKeyValue(MUTATION, 29, 1, m1), createKeyValue(MUTATION, 30, 1, m2),}; Map<String,KeyValue[]> logs = new TreeMap<>(); logs.put("testlog", entries); // Recover List<Mutation> mutations = recover(logs, extent); // Verify recovered data assertEquals(0, mutations.size()); } @Test public void testBug2() throws IOException { // Create a test log Mutation ignored = new ServerMutation(new Text("ignored")); ignored.put(cf, cq, value); Mutation m = new ServerMutation(new Text("row1")); m.put(cf, cq, value); Mutation m2 = new ServerMutation(new Text("row2")); m2.put(cf, cq, value); Mutation m3 = new ServerMutation(new Text("row3")); m3.put(cf, cq, value); KeyValue[] entries = {createKeyValue(OPEN, 0, -1, "1"), createKeyValue(DEFINE_TABLET, 1, 1, extent), createKeyValue(COMPACTION_START, 3, 1, "/t1/f1"), createKeyValue(COMPACTION_FINISH, 4, 1, null), createKeyValue(MUTATION, 4, 1, m),}; KeyValue[] entries2 = {createKeyValue(OPEN, 5, -1, "1"), createKeyValue(DEFINE_TABLET, 6, 1, extent), createKeyValue(COMPACTION_START, 8, 1, "/t1/f1"), createKeyValue(MUTATION, 7, 1, m2), createKeyValue(MUTATION, 9, 1, m3),}; Map<String,KeyValue[]> logs = new TreeMap<>(); logs.put("entries", entries); logs.put("entries2", entries2); // Recover List<Mutation> mutations = recover(logs, extent); // Verify recovered data assertEquals(3, mutations.size()); assertEquals(m, mutations.get(0)); assertEquals(m2, mutations.get(1)); assertEquals(m3, mutations.get(2)); } @Test public void testCompactionCrossesLogs4() throws IOException { // Create a test log Mutation ignored = new ServerMutation(new Text("ignored")); ignored.put(cf, cq, value); Mutation m = new ServerMutation(new Text("row1")); m.put(cf, cq, value); Mutation m2 = new ServerMutation(new Text("row2")); m2.put(cf, cq, value); Mutation m3 = new ServerMutation(new Text("row3")); m3.put(cf, cq, value); Mutation m4 = new ServerMutation(new Text("row4")); m4.put(cf, cq, value); Mutation m5 = new ServerMutation(new Text("row5")); m5.put(cf, cq, value); Mutation m6 = new ServerMutation(new Text("row6")); m6.put(cf, cq, value); // createKeyValue(COMPACTION_FINISH, 5, 1, null), KeyValue[] entries = {createKeyValue(OPEN, 0, -1, "1"), createKeyValue(DEFINE_TABLET, 1, 1, extent), createKeyValue(COMPACTION_START, 4, 1, "/t1/f1"), // createKeyValue(COMPACTION_FINISH, 5, 1, null), createKeyValue(MUTATION, 2, 1, m), createKeyValue(MUTATION, 3, 1, m2),}; KeyValue[] entries2 = {createKeyValue(OPEN, 5, -1, "2"), createKeyValue(DEFINE_TABLET, 6, 1, extent), createKeyValue(MUTATION, 7, 1, m3), createKeyValue(MUTATION, 8, 1, m4),}; // createKeyValue(COMPACTION_FINISH, 11, 1, null), // createKeyValue(COMPACTION_FINISH, 14, 1, null), // createKeyValue(COMPACTION_START, 15, 1, "somefile"), // createKeyValue(COMPACTION_FINISH, 17, 1, null), // createKeyValue(COMPACTION_START, 18, 1, "somefile"), // createKeyValue(COMPACTION_FINISH, 19, 1, null), KeyValue[] entries3 = {createKeyValue(OPEN, 9, -1, "3"), createKeyValue(DEFINE_TABLET, 10, 1, extent), // createKeyValue(COMPACTION_FINISH, 11, 1, null), createKeyValue(COMPACTION_START, 12, 1, "/t1/f1"), // createKeyValue(COMPACTION_FINISH, 14, 1, null), // createKeyValue(COMPACTION_START, 15, 1, "somefile"), // createKeyValue(COMPACTION_FINISH, 17, 1, null), // createKeyValue(COMPACTION_START, 18, 1, "somefile"), // createKeyValue(COMPACTION_FINISH, 19, 1, null), createKeyValue(MUTATION, 9, 1, m5), createKeyValue(MUTATION, 20, 1, m6),}; Map<String,KeyValue[]> logs = new TreeMap<>(); logs.put("entries", entries); logs.put("entries2", entries2); logs.put("entries3", entries3); // Recover List<Mutation> mutations = recover(logs, extent); // Verify recovered data assertEquals(6, mutations.size()); assertEquals(m, mutations.get(0)); assertEquals(m2, mutations.get(1)); assertEquals(m3, mutations.get(2)); assertEquals(m4, mutations.get(3)); assertEquals(m5, mutations.get(4)); assertEquals(m6, mutations.get(5)); } @Test public void testLookingForBug3() throws IOException { Mutation ignored = new ServerMutation(new Text("ignored")); ignored.put(cf, cq, value); Mutation m = new ServerMutation(new Text("row1")); m.put(cf, cq, value); Mutation m2 = new ServerMutation(new Text("row2")); m2.put(cf, cq, value); Mutation m3 = new ServerMutation(new Text("row3")); m3.put(cf, cq, value); Mutation m4 = new ServerMutation(new Text("row4")); m4.put(cf, cq, value); Mutation m5 = new ServerMutation(new Text("row5")); m5.put(cf, cq, value); KeyValue[] entries = {createKeyValue(OPEN, 0, -1, "1"), createKeyValue(DEFINE_TABLET, 1, 1, extent), createKeyValue(COMPACTION_START, 2, 1, "/t1/f1"), createKeyValue(COMPACTION_FINISH, 3, 1, null), createKeyValue(MUTATION, 1, 1, ignored), createKeyValue(MUTATION, 3, 1, m), createKeyValue(MUTATION, 3, 1, m2), createKeyValue(MUTATION, 3, 1, m3),}; KeyValue[] entries2 = {createKeyValue(OPEN, 0, -1, "2"), createKeyValue(DEFINE_TABLET, 1, 1, extent), createKeyValue(COMPACTION_START, 2, 1, "/t1/f12"), createKeyValue(MUTATION, 3, 1, m4), createKeyValue(MUTATION, 3, 1, m5),}; Map<String,KeyValue[]> logs = new TreeMap<>(); logs.put("entries", entries); logs.put("entries2", entries2); // Recover List<Mutation> mutations = recover(logs, extent); // Verify recovered data assertEquals(5, mutations.size()); assertTrue(mutations.contains(m)); assertTrue(mutations.contains(m2)); assertTrue(mutations.contains(m3)); assertTrue(mutations.contains(m4)); assertTrue(mutations.contains(m5)); } @Test public void testMultipleTabletDefinition() throws Exception { // test for a tablet defined multiple times in a log file // there was a bug where the oldest tablet id was used instead // of the newest Mutation ignored = new ServerMutation(new Text("row1")); ignored.put("foo", "bar", "v1"); Mutation m = new ServerMutation(new Text("row1")); m.put("foo", "bar", "v1"); KeyValue[] entries = {createKeyValue(OPEN, 0, -1, "1"), createKeyValue(DEFINE_TABLET, 1, 1, extent), createKeyValue(DEFINE_TABLET, 1, 2, extent), createKeyValue(MUTATION, 2, 2, ignored), createKeyValue(COMPACTION_START, 5, 2, "/t1/f1"), createKeyValue(MUTATION, 6, 2, m), createKeyValue(COMPACTION_FINISH, 6, 2, null),}; Arrays.sort(entries); Map<String,KeyValue[]> logs = new TreeMap<>(); logs.put("entries", entries); List<Mutation> mutations = recover(logs, extent); assertEquals(1, mutations.size()); assertEquals(m, mutations.get(0)); } @Test public void testNoFinish0() throws Exception { // its possible that a minor compaction finishes successfully, but the process dies before // writing the compaction event Mutation ignored = new ServerMutation(new Text("row1")); ignored.put("foo", "bar", "v1"); KeyValue[] entries = {createKeyValue(OPEN, 0, -1, "1"), createKeyValue(DEFINE_TABLET, 1, 2, extent), createKeyValue(MUTATION, 2, 2, ignored), createKeyValue(COMPACTION_START, 3, 2, "/t/f1")}; Arrays.sort(entries); Map<String,KeyValue[]> logs = new TreeMap<>(); logs.put("entries", entries); List<Mutation> mutations = recover(logs, Collections.singleton("/t/f1"), extent, bufferSize); assertEquals(0, mutations.size()); } @Test public void testNoFinish1() throws Exception { // its possible that a minor compaction finishes successfully, but the process dies before // writing the compaction event Mutation ignored = new ServerMutation(new Text("row1")); ignored.put("foo", "bar", "v1"); Mutation m = new ServerMutation(new Text("row1")); m.put("foo", "bar", "v2"); KeyValue[] entries = {createKeyValue(OPEN, 0, -1, "1"), createKeyValue(DEFINE_TABLET, 1, 2, extent), createKeyValue(MUTATION, 2, 2, ignored), createKeyValue(COMPACTION_START, 3, 2, "/t/f1"), createKeyValue(MUTATION, 4, 2, m),}; Arrays.sort(entries); Map<String,KeyValue[]> logs = new TreeMap<>(); logs.put("entries", entries); List<Mutation> mutations = recover(logs, Collections.singleton("/t/f1"), extent, bufferSize); assertEquals(1, mutations.size()); assertEquals(m, mutations.get(0)); } @Test public void testLeaveAndComeBack() throws IOException { /** * This test recreates the situation in bug #449 (Github issues). */ Mutation m1 = new ServerMutation(new Text("r1")); m1.put("f1", "q1", "v1"); Mutation m2 = new ServerMutation(new Text("r2")); m2.put("f1", "q1", "v2"); KeyValue[] entries1 = {createKeyValue(OPEN, 0, -1, "1"), createKeyValue(DEFINE_TABLET, 100, 10, extent), createKeyValue(MUTATION, 100, 10, m1), createKeyValue(COMPACTION_START, 101, 10, "/t/f1"), createKeyValue(COMPACTION_FINISH, 102, 10, null)}; KeyValue[] entries2 = {createKeyValue(OPEN, 0, -1, "1"), createKeyValue(DEFINE_TABLET, 1, 20, extent), createKeyValue(MUTATION, 1, 20, m2)}; Arrays.sort(entries1); Arrays.sort(entries2); Map<String,KeyValue[]> logs = new TreeMap<>(); logs.put("entries1", entries1); logs.put("entries2", entries2); List<Mutation> mutations = recover(logs, extent); assertEquals(1, mutations.size()); assertEquals(m2, mutations.get(0)); } @Test public void testMultipleTablets() throws IOException { KeyExtent e1 = new KeyExtent(TableId.of("1"), new Text("m"), null); KeyExtent e2 = new KeyExtent(TableId.of("1"), null, new Text("m")); Mutation m1 = new ServerMutation(new Text("b")); m1.put("f1", "q1", "v1"); Mutation m2 = new ServerMutation(new Text("b")); m2.put("f1", "q2", "v2"); Mutation m3 = new ServerMutation(new Text("s")); m3.put("f1", "q1", "v3"); Mutation m4 = new ServerMutation(new Text("s")); m4.put("f1", "q2", "v4"); KeyValue[] entries1 = {createKeyValue(OPEN, 0, -1, "1"), createKeyValue(DEFINE_TABLET, 7, 10, e1), createKeyValue(DEFINE_TABLET, 5, 11, e2), createKeyValue(MUTATION, 8, 10, m1), createKeyValue(COMPACTION_START, 9, 10, "/t/f1"), createKeyValue(MUTATION, 10, 10, m2), createKeyValue(COMPACTION_FINISH, 10, 10, null), createKeyValue(MUTATION, 6, 11, m3), createKeyValue(COMPACTION_START, 7, 11, "/t/f2"), createKeyValue(MUTATION, 8, 11, m4)}; Arrays.sort(entries1); Map<String,KeyValue[]> logs = new TreeMap<>(); logs.put("entries1", entries1); List<Mutation> mutations1 = recover(logs, e1); assertEquals(1, mutations1.size()); assertEquals(m2, mutations1.get(0)); reset(context); List<Mutation> mutations2 = recover(logs, e2); assertEquals(2, mutations2.size()); assertEquals(m3, mutations2.get(0)); assertEquals(m4, mutations2.get(1)); KeyValue[] entries2 = {createKeyValue(OPEN, 0, -1, "1"), createKeyValue(DEFINE_TABLET, 9, 11, e2), createKeyValue(COMPACTION_FINISH, 8, 11, null)}; Arrays.sort(entries2); logs.put("entries2", entries2); reset(context); mutations2 = recover(logs, e2); assertEquals(1, mutations2.size()); assertEquals(m4, mutations2.get(0)); } private void runPathTest(boolean startMatches, String compactionStartFile, String... tabletFiles) throws IOException { Mutation m1 = new ServerMutation(new Text("row1")); m1.put("foo", "bar", "v1"); Mutation m2 = new ServerMutation(new Text("row1")); m2.put("foo", "bar", "v2"); KeyValue[] entries = {createKeyValue(OPEN, 0, -1, "1"), createKeyValue(DEFINE_TABLET, 1, 2, extent), createKeyValue(MUTATION, 2, 2, m1), createKeyValue(COMPACTION_START, 3, 2, compactionStartFile), createKeyValue(MUTATION, 4, 2, m2),}; Arrays.sort(entries); Map<String,KeyValue[]> logs = new TreeMap<>(); logs.put("entries", entries); HashSet<String> filesSet = new HashSet<>(); filesSet.addAll(Arrays.asList(tabletFiles)); List<Mutation> mutations = recover(logs, filesSet, extent, bufferSize); if (startMatches) { assertEquals(1, mutations.size()); assertEquals(m2, mutations.get(0)); } else { assertEquals(2, mutations.size()); assertEquals(m1, mutations.get(0)); assertEquals(m2, mutations.get(1)); } } @Test public void testPaths() throws IOException { // test having different paths for the same file. This can happen as a result of upgrade or user // changing configuration runPathTest(false, "/t1/f1", "/t1/f0"); reset(context); runPathTest(true, "/t1/f1", "/t1/f0", "/t1/f1"); String[] aliases = {"/t1/f1", "hdfs://nn1/accumulo/tables/8/t1/f1", "hdfs://1.2.3.4/accumulo/tables/8/t1/f1", "hdfs://1.2.3.4//accumulo//tables//8//t1//f1"}; String[] others = {"/t1/f0", "hdfs://nn1/accumulo/tables/8/t1/f2", "hdfs://1.2.3.4//accumulo//tables//8//t1//f3", "hdfs://nn1/accumulo/tables/8/t1/t1", "hdfs://nn1/accumulo/tables/8/f1/f1"}; for (String alias1 : aliases) { for (String alias2 : aliases) { reset(context); runPathTest(true, alias1, alias2); for (String other : others) { reset(context); runPathTest(true, alias1, other, alias2); reset(context); runPathTest(true, alias1, alias2, other); } } } for (String alias1 : aliases) { for (String other : others) { reset(context); runPathTest(false, alias1, other); } } } @Test public void testOnlyCompactionFinishEvent() throws IOException { Mutation m1 = new ServerMutation(new Text("r1")); m1.put("f1", "q1", "v1"); // The presence of only a compaction finish event indicates the write ahead logs are incomplete // in some way. This should cause an exception. KeyValue[] entries1 = {createKeyValue(OPEN, 0, -1, "1"), createKeyValue(DEFINE_TABLET, 100, 10, extent), createKeyValue(COMPACTION_FINISH, 102, 10, null), createKeyValue(MUTATION, 102, 10, m1)}; Arrays.sort(entries1); Map<String,KeyValue[]> logs = new TreeMap<>(); logs.put("entries1", entries1); List<Mutation> mutations = recover(logs, extent); assertEquals(1, mutations.size()); assertEquals(m1, mutations.get(0)); } @Test public void testConsecutiveCompactionFinishEvents() throws IOException { Mutation m1 = new ServerMutation(new Text("r1")); m1.put("f1", "q1", "v1"); Mutation m2 = new ServerMutation(new Text("r2")); m2.put("f1", "q1", "v2"); // Consecutive compaction finish events indicate the write ahead logs are incomplete in some // way. This should cause an exception. KeyValue[] entries1 = {createKeyValue(OPEN, 0, -1, "1"), createKeyValue(DEFINE_TABLET, 100, 10, extent), createKeyValue(MUTATION, 100, 10, m1), createKeyValue(COMPACTION_START, 102, 10, "/t/f1"), createKeyValue(COMPACTION_FINISH, 103, 10, null), createKeyValue(COMPACTION_FINISH, 109, 10, null), createKeyValue(MUTATION, 105, 10, m2)}; Arrays.sort(entries1); Map<String,KeyValue[]> logs = new TreeMap<>(); logs.put("entries1", entries1); var e = assertThrows(IllegalStateException.class, () -> recover(logs, extent)); assertTrue(e.getMessage().contains("consecutive " + LogEvents.COMPACTION_FINISH.name())); } @Test public void testDuplicateCompactionFinishEvents() throws IOException { Mutation m1 = new ServerMutation(new Text("r1")); m1.put("f1", "q1", "v1"); Mutation m2 = new ServerMutation(new Text("r2")); m2.put("f1", "q1", "v2"); // Duplicate consecutive compaction finish events should not cause an exception. KeyValue[] entries1 = {createKeyValue(OPEN, 0, -1, "1"), createKeyValue(DEFINE_TABLET, 100, 10, extent), createKeyValue(MUTATION, 100, 10, m1), createKeyValue(COMPACTION_START, 102, 10, "/t/f1"), createKeyValue(COMPACTION_FINISH, 103, 10, null), createKeyValue(COMPACTION_FINISH, 103, 10, null), createKeyValue(MUTATION, 103, 10, m2)}; Arrays.sort(entries1); Map<String,KeyValue[]> logs = new TreeMap<>(); logs.put("entries1", entries1); List<Mutation> mutations1 = recover(logs, extent); assertEquals(1, mutations1.size()); assertEquals(m2, mutations1.get(0)); } @Test public void testMultipleCompactionStartEvents() throws IOException { Mutation m1 = new ServerMutation(new Text("r1")); m1.put("f1", "q1", "v1"); Mutation m2 = new ServerMutation(new Text("r2")); m2.put("f1", "q1", "v2"); // The code that writes compaction start events retries on failures, this could lead to multiple // compaction start events in the log. This should not cause any problems. KeyValue[] entries1 = {createKeyValue(OPEN, 0, -1, "1"), createKeyValue(DEFINE_TABLET, 100, 10, extent), createKeyValue(MUTATION, 100, 10, m1), createKeyValue(COMPACTION_START, 102, 10, "/t/f1"), createKeyValue(COMPACTION_START, 102, 10, "/t/f1"), createKeyValue(COMPACTION_START, 102, 10, "/t/f1"), createKeyValue(COMPACTION_FINISH, 103, 10, null), createKeyValue(MUTATION, 103, 10, m2)}; Arrays.sort(entries1); Map<String,KeyValue[]> logs = new TreeMap<>(); logs.put("entries1", entries1); List<Mutation> mutations1 = recover(logs, extent); assertEquals(1, mutations1.size()); assertEquals(m2, mutations1.get(0)); } @Test public void testEmptyLogFiles() throws IOException { Mutation m1 = new ServerMutation(new Text("r1")); m1.put("f1", "q1", "v1"); Mutation m2 = new ServerMutation(new Text("r2")); m2.put("f1", "q1", "v2"); KeyValue[] entries1 = {createKeyValue(OPEN, 0, -1, "1"), createKeyValue(DEFINE_TABLET, 100, 10, extent), createKeyValue(MUTATION, 100, 10, m1)}; KeyValue[] entries2 = {createKeyValue(OPEN, 0, -1, "1")}; KeyValue[] entries3 = {createKeyValue(OPEN, 0, -1, "1"), createKeyValue(DEFINE_TABLET, 105, 10, extent), createKeyValue(COMPACTION_START, 107, 10, "/t/f1")}; KeyValue[] entries4 = {}; KeyValue[] entries5 = {createKeyValue(OPEN, 0, -1, "1"), createKeyValue(DEFINE_TABLET, 107, 10, extent), createKeyValue(COMPACTION_FINISH, 111, 10, null)}; KeyValue[] entries6 = {createKeyValue(OPEN, 0, -1, "1"), createKeyValue(DEFINE_TABLET, 122, 10, extent), createKeyValue(MUTATION, 123, 10, m2)}; Arrays.sort(entries1); Arrays.sort(entries2); Arrays.sort(entries3); Arrays.sort(entries4); Arrays.sort(entries5); Arrays.sort(entries6); Map<String,KeyValue[]> logs = new TreeMap<>(); logs.put("entries1", entries1); List<Mutation> mutations = recover(logs, extent); assertEquals(1, mutations.size()); assertEquals(m1, mutations.get(0)); logs.put("entries2", entries2); reset(context); mutations = recover(logs, extent); assertEquals(1, mutations.size()); assertEquals(m1, mutations.get(0)); logs.put("entries3", entries3); reset(context); mutations = recover(logs, extent); assertEquals(1, mutations.size()); assertEquals(m1, mutations.get(0)); logs.put("entries4", entries4); reset(context); mutations = recover(logs, extent); assertEquals(1, mutations.size()); assertEquals(m1, mutations.get(0)); logs.put("entries5", entries5); reset(context); mutations = recover(logs, extent); assertEquals(0, mutations.size()); logs.put("entries6", entries6); reset(context); mutations = recover(logs, extent); assertEquals(1, mutations.size()); assertEquals(m2, mutations.get(0)); } @Test public void testFileWithoutOpen() throws IOException { Mutation m1 = new ServerMutation(new Text("r1")); m1.put("f1", "q1", "v1"); Mutation m2 = new ServerMutation(new Text("r2")); m2.put("f1", "q1", "v2"); // Its expected that every log file should have an open event as the first event. Should throw // an error if not present. KeyValue[] entries1 = {createKeyValue(DEFINE_TABLET, 100, 10, extent), createKeyValue(MUTATION, 100, 10, m1), createKeyValue(COMPACTION_FINISH, 102, 10, null), createKeyValue(MUTATION, 105, 10, m2)}; Arrays.sort(entries1); Map<String,KeyValue[]> logs = new TreeMap<>(); logs.put("entries1", entries1); var e = assertThrows(IllegalStateException.class, () -> recover(logs, extent)); assertTrue(e.getMessage().contains("not " + LogEvents.OPEN)); } @Test public void testInvalidLogSortedProperties() { ConfigurationCopy testConfig = new ConfigurationCopy(DefaultConfiguration.getInstance()); // test all the possible properties for tserver.sort.file. prefix String prop = Property.TSERV_WAL_SORT_FILE_PREFIX + "invalid"; testConfig.set(prop, "snappy"); try { new LogSorter(context, testConfig); fail("Did not throw IllegalArgumentException for " + prop); } catch (IllegalArgumentException e) { // valid for test } } @Test public void testLogSortedProperties() throws Exception { Mutation ignored = new ServerMutation(new Text("ignored")); ignored.put(cf, cq, value); Mutation m = new ServerMutation(new Text("row1")); m.put(cf, cq, value); ConfigurationCopy testConfig = new ConfigurationCopy(DefaultConfiguration.getInstance()); String sortFileCompression = "none"; // test all the possible properties for tserver.sort.file. prefix String prefix = Property.TSERV_WAL_SORT_FILE_PREFIX.toString(); testConfig.set(prefix + "compress.type", sortFileCompression); testConfig.set(prefix + "compress.blocksize", "50K"); testConfig.set(prefix + "compress.blocksize.index", "56K"); testConfig.set(prefix + "blocksize", "256B"); testConfig.set(prefix + "replication", "3"); LogSorter sorter = new LogSorter(context, testConfig); final String workdir = tempFolder.newFolder().getAbsolutePath(); try (var vm = VolumeManagerImpl.getLocalForTesting(workdir)) { expect(context.getVolumeManager()).andReturn(vm).anyTimes(); expect(context.getCryptoService()).andReturn(CryptoServiceFactory.newDefaultInstance()) .anyTimes(); expect(context.getConfiguration()).andReturn(DefaultConfiguration.getInstance()).anyTimes(); replay(context); final Path workdirPath = new Path("file://" + workdir); vm.deleteRecursively(workdirPath); KeyValue[] events = {createKeyValue(OPEN, 0, -1, "1"), createKeyValue(DEFINE_TABLET, 1, 1, extent), createKeyValue(COMPACTION_FINISH, 2, 1, null), createKeyValue(COMPACTION_START, 4, 1, "/t1/f1"), createKeyValue(COMPACTION_FINISH, 5, 1, null), createKeyValue(MUTATION, 3, 1, ignored), createKeyValue(MUTATION, 5, 1, m)}; String dest = workdir + "/testLogSortedProperties"; List<Pair<LogFileKey,LogFileValue>> buffer = new ArrayList<>(); int parts = 0; for (KeyValue pair : events) { buffer.add(new Pair<>(pair.key, pair.value)); if (buffer.size() >= bufferSize) { sorter.writeBuffer(dest, buffer, parts++); buffer.clear(); } } sorter.writeBuffer(dest, buffer, parts); FileSystem fs = vm.getFileSystemByPath(workdirPath); // check contents of directory for (var file : fs.listStatus(new Path(dest))) { assertTrue(file.isFile()); try (var fileStream = fs.open(file.getPath())) { var algo = getCompressionFromRFile(fileStream, file.getLen()); assertEquals(sortFileCompression, algo.getName()); } } } } /** * Pulled from BCFile.Reader() */ private final Utils.Version API_VERSION_3 = new Utils.Version((short) 3, (short) 0); private final String defaultPrefix = "data:"; private Compression.Algorithm getCompressionFromRFile(FSDataInputStream fsin, long fileLength) throws IOException { try (var in = new SeekableDataInputStream(fsin)) { int magicNumberSize = 16; // BCFile.Magic.size(); // Move the cursor to grab the version and the magic first in.seek(fileLength - magicNumberSize - Utils.Version.size()); var version = new Utils.Version(in); assertEquals(API_VERSION_3, version); in.readFully(new byte[16]); // BCFile.Magic.readAndVerify(in); // 16 bytes in.seek(fileLength - magicNumberSize - Utils.Version.size() - 16); // 2 * Long.BYTES = 16 long offsetIndexMeta = in.readLong(); long offsetCryptoParameters = in.readLong(); assertTrue(offsetCryptoParameters > 0); // read meta index in.seek(offsetIndexMeta); int count = Utils.readVInt(in); assertTrue(count > 0); String fullMetaName = Utils.readString(in); if (fullMetaName != null && !fullMetaName.startsWith(defaultPrefix)) { throw new IOException("Corrupted Meta region Index"); } return Compression.getCompressionAlgorithmByName(Utils.readString(in)); } } }
{ "content_hash": "cd14e67e5a64fc32a8ffd8dc2063436a", "timestamp": "", "source": "github", "line_count": 1162, "max_line_length": 100, "avg_line_length": 39.43803786574871, "alnum_prop": 0.6542649529753203, "repo_name": "phrocker/accumulo-1", "id": "0a2720b44d7aa6fefa48cbeab76bee64e9d5f75c", "size": "46634", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "server/tserver/src/test/java/org/apache/accumulo/tserver/log/SortedLogRecoveryTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "2465" }, { "name": "C++", "bytes": "37312" }, { "name": "CSS", "bytes": "6443" }, { "name": "FreeMarker", "bytes": "57422" }, { "name": "HTML", "bytes": "5454" }, { "name": "Java", "bytes": "18447889" }, { "name": "JavaScript", "bytes": "71755" }, { "name": "Makefile", "bytes": "2872" }, { "name": "Python", "bytes": "7344" }, { "name": "Shell", "bytes": "61899" }, { "name": "Thrift", "bytes": "40724" } ], "symlink_target": "" }
import math, random # Primality test functions. Assume that "n" is odd and greater than 3. # Tests if 'n' is prime by trial division, by checking if it has a factor # k (1 < k <= sqrt(n)) def trial_division(n): return not(any(n % x == 0 for x in range(3, math.floor(math.sqrt(n))+1))) # Tests if 'n' is a strong pseudoprime using the Miller-Rabin probabilistic algorithm. # # If 'n' is prime, then the following properties hold. If one of them fails, # then we know 'n' is composite. # # Randomly picks 'rounds' bases. # For each base 'a', start with Fermat's little theorem (a^(n-1) = 1 (mod n)). # Take the square root of 1 (in a finite field Z/nZ, assuming n is prime) # and verify that every root is either 1 or -1. # so, (suppose n-1 = 2^s * d (d odd) and n prime), we have EITHER: # - a^d = 1 (mod n) (no need to continue, will give 1 for the 's' time that we'll square it) # - a^(2^r * d) = -1 (mod n), for a certain r in [0,s-1] (all subsequent squarings will # then give 1, so we can stop there). # The contrapositive: # n is composite if we have BOTH: # - a^d != 1 (mod n) # - a^(2^r * d) != -1 (mod n), for all r in [0,s-1] # # Has a probability of 4^(-'rounds') to return a composite number as a strong pseudoprime. def miller_rabin(n, rounds = 40): # get the form n - 1 = 2^s * d s = 0 d = n-1 while is_even(d): d //= 2 s += 1 for i in range(rounds): a = random.randrange(2,n) x = pow(a, d, n) if x == 1: # pseudoprime continue skip = False for r in range(s): if x == n-1: # pseudoprime skip = True break x = pow(x, 2, n) if not skip: return False # composite return True # Tests if 'n' is probably prime using the Solovay-Strassen probabilistic algorithm. # # If 'n' is prime, the Euler's criterion holds for any 'a' (if it fails, 'n' is composite): # a ^ ( (n-1)/2 ) = Legendre(a, n) # Where Legendre stands for Legendre's symbol. # Since we don't know if n is prime, we'll use Jacobi's symbol (a generalization # of Legendre's symbol). # # Randomly pick 'rounds' bases. # For each base 'a', see if the criterion holds. If not, 'n' is composite. # If the criterion holds for all bases, 'n' is considered probably prime. def solovay_strassen(n, rounds = 80): for i in range(rounds): a = random.randrange(2,n) x = pow(a, (n-1)//2, n) jacobi = jacobi_symbol(a, n) if jacobi < 0: jacobi += n # we want n-1 instead of -1 (mod n) if x != jacobi: return False return True def is_even(n): return n & 1 == 0 # Calculates the Jacobi symbol of 'a' and 'n'. # # Note: the comments of the form '(i)' indicate what property # was used from this: https://en.wikipedia.org/wiki/Jacobi_symbol#Properties def jacobi_symbol(a, n): j = 1 while a > 0: while is_even(a): # extract (2/n) using (4) a //= 2 # evaluate (2/n) using (8) if n % 8 == 3 or n % 8 == 5: j = -j # swap, by the law of quadratic reciprocity (6) if n % 4 == 3 and a % 4 == 3: j = -j a, n = n, a a = a % n # can reduce using (2) # n != 1 means that gcd(a,n) != 1 => jacobi = 0 return j if n == 1 else 0
{ "content_hash": "6d4ff592915901f3e5adb0bf87c22474", "timestamp": "", "source": "github", "line_count": 101, "max_line_length": 93, "avg_line_length": 33.13861386138614, "alnum_prop": 0.5760382432028682, "repo_name": "JesseEmond/benchmarkus-prime", "id": "7bebaf00c549693467be45d587f5818abd6a2a7b", "size": "3347", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "primes.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "6183" } ], "symlink_target": "" }
/** * 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 org.brixcms.plugin.site; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.jcr.Item; import javax.jcr.Node; import javax.jcr.RepositoryException; import javax.jcr.Session; import org.apache.wicket.Component; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.IModel; import org.apache.wicket.model.ResourceModel; import org.apache.wicket.util.string.Strings; import org.brixcms.Brix; import org.brixcms.Path; import org.brixcms.SessionAwarePlugin; import org.brixcms.auth.Action; import org.brixcms.auth.Action.Context; import org.brixcms.config.BrixConfig; import org.brixcms.jcr.api.JcrNode; import org.brixcms.jcr.api.JcrNodeIterator; import org.brixcms.jcr.api.JcrSession; import org.brixcms.jcr.api.wrapper.NodeWrapper; import org.brixcms.jcr.base.BrixSession; import org.brixcms.jcr.base.action.AbstractActionHandler; import org.brixcms.jcr.base.event.AddNodeEvent; import org.brixcms.jcr.base.event.Event; import org.brixcms.jcr.base.event.EventsListener; import org.brixcms.jcr.wrapper.BrixNode; import org.brixcms.jcr.wrapper.ResourceNode; import org.brixcms.markup.MarkupCache; import org.brixcms.plugin.site.admin.NodeManagerContainerPanel; import org.brixcms.plugin.site.admin.NodeTreeContainer; import org.brixcms.plugin.site.admin.convert.ConvertNodeTabFactory; import org.brixcms.plugin.site.admin.nodetree.AudioNodeTreeRenderer; import org.brixcms.plugin.site.admin.nodetree.CssNodeTreeRenderer; import org.brixcms.plugin.site.admin.nodetree.ImageNodeTreeRenderer; import org.brixcms.plugin.site.admin.nodetree.OfficeDocumentNodeTreeRenderer; import org.brixcms.plugin.site.admin.nodetree.OfficePresentationNodeTreeRenderer; import org.brixcms.plugin.site.admin.nodetree.OfficeSpreadsheetNodeTreeRenderer; import org.brixcms.plugin.site.admin.nodetree.PageNodeTreeRenderer; import org.brixcms.plugin.site.admin.nodetree.TemplateNodeTreeRenderer; import org.brixcms.plugin.site.admin.nodetree.VideoNodeTreeRenderer; import org.brixcms.plugin.site.auth.AccessSitePluginAction; import org.brixcms.plugin.site.auth.SiteNodeAction; import org.brixcms.plugin.site.auth.SiteNodeAction.Type; import org.brixcms.plugin.site.fallback.FallbackNodePlugin; import org.brixcms.plugin.site.folder.FolderNodePlugin; import org.brixcms.plugin.site.page.AbstractContainer; import org.brixcms.plugin.site.page.PageNode; import org.brixcms.plugin.site.page.PageSiteNodePlugin; import org.brixcms.plugin.site.page.TemplateNode; import org.brixcms.plugin.site.page.TemplateSiteNodePlugin; import org.brixcms.plugin.site.page.admin.MarkupEditorFactory; import org.brixcms.plugin.site.page.admin.SimpleMarkupEditorFactory; import org.brixcms.plugin.site.page.global.GlobalContainerNode; import org.brixcms.plugin.site.page.global.GlobalTilesPanel; import org.brixcms.plugin.site.page.global.GlobalVariablesPanel; import org.brixcms.plugin.site.page.tile.TileContainerFacet; import org.brixcms.plugin.site.resource.ResourceNodePlugin; import org.brixcms.plugin.site.webdav.Rule; import org.brixcms.plugin.site.webdav.RulesNode; import org.brixcms.plugin.site.webdav.RulesPanel; import org.brixcms.registry.ExtensionPointRegistry; import org.brixcms.web.tab.AbstractWorkspaceTab; import org.brixcms.web.tab.IBrixTab; import org.brixcms.workspace.JcrException; import org.brixcms.workspace.Workspace; public class SitePlugin implements SessionAwarePlugin { public static final String PREFIX = "site"; public static final String WORKSPACE_ATTRIBUTE_STATE = "brix:site-state"; private static final String ID = SitePlugin.class.getName(); private static final String WORKSPACE_TYPE = "brix:site"; private static final String WORKSPACE_ATTRIBUTE_NAME = "brix:site-name"; private static final String WEB_NODE_NAME = Brix.NS_PREFIX + "web"; private static final String SITE_NODE_NAME = Brix.NS_PREFIX + "site"; private static final String GLOBAL_CONTAINER_NODE_NAME = Brix.NS_PREFIX + "globalContainer"; private static final String WEBDAV_RULES_NODE_NAME = Brix.NS_PREFIX + "webDavRules"; public static final String BRIX_INDEX_PAGE = "index.brix"; private final Brix brix; private FallbackNodePlugin fallbackNodePlugin = new FallbackNodePlugin(); private Comparator<String> stateComparator = null; private MarkupCache markupCache = new MarkupCache(); private WebDavEventListener webDavEventListener = new WebDavEventListener(); public static SitePlugin get() { return get(Brix.get()); } public static SitePlugin get(Brix brix) { return (SitePlugin) brix.getPlugin(ID); } public SitePlugin(Brix brix) { this.brix = brix; registerNodePlugin(new FolderNodePlugin(this)); registerNodePlugin(new ResourceNodePlugin(this)); registerNodePlugin(new TemplateSiteNodePlugin(this)); registerNodePlugin(new PageSiteNodePlugin(this)); registerManageNodeTabFactory(new ConvertNodeTabFactory()); // register default editor ExtensionPointRegistry registry = brix.getConfig().getRegistry(); registry.register(MarkupEditorFactory.POINT, new SimpleMarkupEditorFactory()); // register node types for tree renderer registry.register(NodeTreeRenderer.POINT, new PageNodeTreeRenderer()); registry.register(NodeTreeRenderer.POINT, new TemplateNodeTreeRenderer()); registry.register(NodeTreeRenderer.POINT, new CssNodeTreeRenderer()); registry.register(NodeTreeRenderer.POINT, new AudioNodeTreeRenderer()); registry.register(NodeTreeRenderer.POINT, new ImageNodeTreeRenderer()); registry.register(NodeTreeRenderer.POINT, new VideoNodeTreeRenderer()); registry.register(NodeTreeRenderer.POINT, new OfficeDocumentNodeTreeRenderer()); registry.register(NodeTreeRenderer.POINT, new OfficeSpreadsheetNodeTreeRenderer()); registry.register(NodeTreeRenderer.POINT, new OfficePresentationNodeTreeRenderer()); } public void registerNodePlugin(SiteNodePlugin plugin) { if (plugin == null) { throw new IllegalArgumentException("Argument 'plugin' cannot be null"); } brix.getConfig().getRegistry().register(SiteNodePlugin.POINT, plugin); } public void registerManageNodeTabFactory(ManageNodeTabFactory factory) { if (factory == null) { throw new IllegalArgumentException("Argument 'factory' cannot be null"); } brix.getConfig().getRegistry().register(ManageNodeTabFactory.POINT, factory); } public final Brix getBrix() { return brix; } public MarkupCache getMarkupCache() { return markupCache; } public void setStateComparator(Comparator<String> stateComparator) { this.stateComparator = stateComparator; } public String getId() { return ID; } public List<IBrixTab> newTabs(final IModel<Workspace> workspaceModel) { IBrixTab tabs[] = new IBrixTab[]{new SiteTab(new ResourceModel("site", "Site"), workspaceModel), new GlobalTilesTab(new ResourceModel("tiles", "Tiles"), workspaceModel), new GlobalVariablesTab(new ResourceModel("variables", "Variables"), workspaceModel), new WebDAVRulesTab(new ResourceModel("webdav.rules", "WebDAV Rules"), workspaceModel)}; return Arrays.asList(tabs); } public void initWorkspace(Workspace workspace, JcrSession workspaceSession) { JcrNode root = (JcrNode) workspaceSession.getItem(brix.getRootPath()); JcrNode web = null; if (root.hasNode(WEB_NODE_NAME)) { web = root.getNode(WEB_NODE_NAME); } else if (isSiteWorkspace(workspace)) { web = root.addNode(WEB_NODE_NAME, "nt:folder"); } if (web != null) { if (!web.isNodeType(BrixNode.JCR_TYPE_BRIX_NODE)) { web.addMixin(BrixNode.JCR_TYPE_BRIX_NODE); } checkForSiteRoot(web); if (!web.hasNode(GLOBAL_CONTAINER_NODE_NAME)) { GlobalContainerNode.initialize(web.addNode(GLOBAL_CONTAINER_NODE_NAME, "nt:file")); } if (!web.hasNode(WEBDAV_RULES_NODE_NAME)) { RulesNode.initialize((BrixNode) web.addNode(WEBDAV_RULES_NODE_NAME, "nt:unstructured")); } } } public List<Workspace> getWorkspaces(Workspace currentWorkspace, boolean isFrontend) { Map<String, String> attributes = new HashMap<String, String>(); attributes.put(Brix.WORKSPACE_ATTRIBUTE_TYPE, WORKSPACE_TYPE); List<Workspace> workspaces = new ArrayList<Workspace>(brix.getWorkspaceManager() .getWorkspacesFiltered(attributes)); Collections.sort(workspaces, new Comparator<Workspace>() { public int compare(Workspace o1, Workspace o2) { String n1 = getWorkspaceName(o1); String n2 = getWorkspaceName(o2); int r = n1.compareTo(n2); if (r == 0) { String s1 = getWorkspaceState(o1); String s2 = getWorkspaceState(o2); if (s1 != null && s2 != null) { if (stateComparator != null) { return stateComparator.compare(s1, s2); } else { return s1.compareTo(s2); } } else { return 0; } } else { return r; } } }); return workspaces; } public boolean isPluginWorkspace(Workspace workspace) { return isSiteWorkspace(workspace); } public String getUserVisibleName(Workspace workspace, boolean isFrontend) { String name = "Site - " + getWorkspaceName(workspace); String state = getWorkspaceState(workspace); if (!Strings.isEmpty(state)) { name = name + " - " + state; } return name; } public void onWebDavSession(final BrixSession session) { session.addEventsListener(webDavEventListener); session.addActionHandler(new WebDavActionHandler(session)); } public boolean canAddNodeChild(BrixNode node, Context context) { if (!isNodeEditable(node)) { return false; } Action action = new SiteNodeAction(context, Type.NODE_ADD_CHILD, node); return brix.getAuthorizationStrategy().isActionAuthorized(action); } public boolean canDeleteNode(BrixNode node, Context context) { if (!isNodeEditable(node)) { return false; } Action action = new SiteNodeAction(context, Type.NODE_DELETE, node); return brix.getAuthorizationStrategy().isActionAuthorized(action); } public boolean canEditNode(BrixNode node, Context context) { if (!isNodeEditable(node)) { return false; } Action action = new SiteNodeAction(context, Type.NODE_EDIT, node); return brix.getAuthorizationStrategy().isActionAuthorized(action); } private boolean isNodeEditable(BrixNode node) { if (node.isNodeType("mix:versionable") && !node.isCheckedOut()) { return false; } if (node.isLocked() && node.getLock().getLockToken() == null) { return false; } return true; } public boolean canRenameNode(BrixNode node, Context context) { if (!isNodeEditable(node)) { return false; } Action action = new SiteNodeAction(context, Type.NODE_DELETE, node); return brix.getAuthorizationStrategy().isActionAuthorized(action); } public boolean canViewNode(BrixNode node, Context context) { Action action = new SiteNodeAction(context, Type.NODE_VIEW, node); return brix.getAuthorizationStrategy().isActionAuthorized(action); } public boolean canViewNodeChildren(BrixNode node, Context context) { Action action = new SiteNodeAction(context, Type.NODE_VIEW_CHILDREN, node); return brix.getAuthorizationStrategy().isActionAuthorized(action); } private void checkForSiteRoot(JcrNode webNode) { if (!webNode.hasNode(SITE_NODE_NAME)) { JcrNode site = webNode.addNode(SITE_NODE_NAME, "nt:folder"); site.addMixin(BrixNode.JCR_TYPE_BRIX_NODE); JcrNodeIterator nodes = webNode.getNodes(); while (nodes.hasNext()) { BrixNode node = (BrixNode) nodes.nextNode(); if (node.isSame(site) == false && node instanceof GlobalContainerNode == false) { JcrSession session = webNode.getSession(); session.move(node.getPath(), site.getPath() + "/" + node.getName()); } } } else { // make reference for brix:site to brix:web to prevent creating prototypes // without selecting brix:web JcrNode site = webNode.getNode(SITE_NODE_NAME); if (!site.hasProperty(Brix.NS_PREFIX + "web")) { site.setProperty(Brix.NS_PREFIX + "web", webNode); } } } public Workspace createSite(String name, String state) { Workspace workspace = brix.getWorkspaceManager().createWorkspace(); workspace.setAttribute(Brix.WORKSPACE_ATTRIBUTE_TYPE, WORKSPACE_TYPE); setWorkspaceName(workspace, name); setWorkspaceState(workspace, state); return workspace; } public void setWorkspaceName(Workspace workspace, String name) { workspace.setAttribute(WORKSPACE_ATTRIBUTE_NAME, name); } public void setWorkspaceState(Workspace workspace, String state) { workspace.setAttribute(WORKSPACE_ATTRIBUTE_STATE, state); } public Collection<String> getGlobalTileIDs(JcrSession session) { AbstractContainer globalContainer = getGlobalContainer(session); Set<String> result; if (globalContainer != null) { result = new HashSet<String>(); for (BrixNode n : globalContainer.tiles().getTileNodes()) { String id = TileContainerFacet.getTileId(n); if (!Strings.isEmpty(id)) { result.add(id); } } } else { result = Collections.emptySet(); } return result; } public Collection<String> getGlobalVariableKeys(JcrSession session) { AbstractContainer globalContainer = getGlobalContainer(session); Collection<String> result; if (globalContainer != null) { result = globalContainer.getSavedVariableKeys(); } else { result = Collections.emptyList(); } return result; } public AbstractContainer getGlobalContainer(JcrSession session) { if (session.itemExists(getGlobalContainerPath())) { return (AbstractContainer) session.getItem(getGlobalContainerPath()); } else { return null; } } private String getGlobalContainerPath() { return getWebRootPath() + "/" + GLOBAL_CONTAINER_NODE_NAME; } public String getWebRootPath() { return brix.getRootPath() + "/" + WEB_NODE_NAME; } public String getGlobalVariableValue(JcrSession session, String variableKey) { AbstractContainer globalContainer = getGlobalContainer(session); if (globalContainer != null) { return globalContainer.getVariableValue(variableKey, false); } else { return null; } } public SiteNodePlugin getNodePluginForNode(JcrNode node) { return getNodePluginForType(((BrixNode) node).getNodeType()); } public SiteNodePlugin getNodePluginForType(String type) { for (SiteNodePlugin plugin : getNodePlugins()) { if (plugin.getNodeType().equals(type)) { return plugin; } } return fallbackNodePlugin; } public Collection<SiteNodePlugin> getNodePlugins() { return brix.getConfig().getRegistry().lookupCollection(SiteNodePlugin.POINT); } public BrixNode getSiteRootNode(String workspaceId) { JcrSession workspaceSession = brix.getCurrentSession(workspaceId); BrixNode root = (BrixNode) workspaceSession.getItem(getSiteRootPath()); return root; } public String getSiteRootPath() { return getWebRootPath() + "/" + SITE_NODE_NAME; } public RulesNode getWebDavRules(JcrSession session) { if (session.itemExists(getWebDavRulesPath())) { return (RulesNode) session.getItem(getWebDavRulesPath()); } else { return null; } } private String getWebDavRulesPath() { return getWebRootPath() + "/" + WEBDAV_RULES_NODE_NAME; } public String getWorkspaceName(Workspace workspace) { return workspace.getAttribute(WORKSPACE_ATTRIBUTE_NAME); } public String getWorkspaceState(Workspace workspace) { return workspace.getAttribute(WORKSPACE_ATTRIBUTE_STATE); } private void handleNewNode(String path, BrixNode node, JcrSession session, boolean save) { if (path.startsWith(getSiteRootPath()) == false) { return; } String relativePath = path.substring(getSiteRootPath().length()); List<Rule> rules = getWebDavRules(session).getRules(true); for (Rule rule : rules) { if (rule.matches(relativePath)) { if (node == null) { node = (BrixNode) session.getItem(path); } if (node instanceof ResourceNode == false) { return; } AbstractContainer container = null; if (rule.getType() == Rule.Type.TEMPLATE) { container = TemplateNode.initialize(node); } else if (rule.getType() == Rule.Type.PAGE) { container = PageNode.initialize(node); } if (container != null) { if (rule.getTemplateModel().getObject() != null) { container.setTemplate(rule.getTemplateModel().getObject()); } if (save) { container.save(); } } return; } } } public boolean isSiteWorkspace(Workspace workspace) { return WORKSPACE_TYPE.equals(workspace.getAttribute(Brix.WORKSPACE_ATTRIBUTE_TYPE)); } public JcrNode nodeForPath(BrixNode baseNode, Path path) { return nodeForPath(baseNode, path.toString()); } public JcrNode nodeForPath(BrixNode baseNode, String path) { Path realPath = new Path(SitePlugin.get().toRealWebNodePath(path)); if (realPath.isAbsolute() == false) { Path base = new Path(baseNode.getPath()); if (!baseNode.isFolder()) { base = base.parent(); } realPath = base.append(realPath); } String strPath = realPath.toString(); if (baseNode.getSession().itemExists(strPath) == false) { return null; } else { return ((JcrNode) baseNode.getSession().getItem(strPath)); } } /** * Creates a uri path for the specified <code>node</code> By default this * method uses {@link BrixConfig#getMapper()} to map node path to a uri * path. * * @param node * node to create uri path for * @return uri path that represents the node */ public Path getUriPathForNode(final BrixNode node) { // allow site plugin to translate jcr path into node path final String jcrPath = SitePlugin.get().fromRealWebNodePath(node.getPath()); final Path nodePath = new Path(jcrPath); // use urimapper to create the uri return brix.getConfig().getMapper().getUriPathForNode(nodePath, brix); } public String toRealWebNodePath(String nodePath) { Path prefix = new Path(getSiteRootPath()); Path path = new Path(nodePath); if (path.isRoot()) { path = new Path("."); } else if (path.isAbsolute()) { path = path.toRelative(new Path("/")); } return prefix.append(path).toString(); } public String pathForNode(JcrNode node) { return SitePlugin.get().fromRealWebNodePath(node.getPath()); } public String fromRealWebNodePath(String nodePath) { Path prefix = new Path(getSiteRootPath()); Path path = new Path(nodePath); if (path.equals(prefix)) { path = new Path("/"); } else if (path.isDescendantOf(prefix)) { path = path.toRelative(prefix); } if (!path.isAbsolute()) { path = new Path("/").append(path); } return path.toString(); } public void refreshNavigationTree(Component component) { NodeTreeContainer panel = findContainer(component); if (panel != null) { panel.updateTree(); } else { throw new IllegalStateException( "Can't call refreshNaviagtionTree with component outside of the hierarchy."); } } public void selectNode(Component component, BrixNode node) { selectNode(component, node, false); } public void selectNode(Component component, BrixNode node, boolean refreshTree) { NodeTreeContainer panel = findContainer(component); if (panel != null) { panel.selectNode(node); panel.updateTree(); } else { throw new IllegalStateException( "Can't call selectNode with component outside of the hierarchy."); } } private NodeTreeContainer findContainer(Component component) { if (component instanceof NodeTreeContainer) { return (NodeTreeContainer) component; } else { return component.findParent(NodeTreeContainer.class); } } public boolean siteExists(String name, String state) { return getSiteWorkspace(name, state) != null; } public Workspace getSiteWorkspace(String name, String state) { Map<String, String> attributes = new HashMap<String, String>(); attributes.put(Brix.WORKSPACE_ATTRIBUTE_TYPE, WORKSPACE_TYPE); attributes.put(WORKSPACE_ATTRIBUTE_NAME, name); if (state != null) { attributes.put(WORKSPACE_ATTRIBUTE_STATE, state); } List<Workspace> res = brix.getWorkspaceManager().getWorkspacesFiltered(attributes); return res.isEmpty() ? null : res.get(0); } private BrixNode wrapNode(Node node) { JcrSession session; try { session = brix.wrapSession(node.getSession()); return (BrixNode) NodeWrapper.wrap(node, session); } catch (RepositoryException e) { throw new JcrException(e); } } static class SiteTab extends AbstractWorkspaceTab { public SiteTab(IModel<String> title, IModel<Workspace> workspaceModel) { super(title, workspaceModel, 1000); } @Override public Panel newPanel(String panelId, IModel<Workspace> workspaceModel) { return new NodeManagerContainerPanel(panelId, workspaceModel); } @Override public boolean isVisible() { final Action action = new AccessSitePluginAction(getWorkspaceModel().getObject()); return Brix.get().getAuthorizationStrategy().isActionAuthorized(action); } } static class GlobalTilesTab extends AbstractWorkspaceTab { public GlobalTilesTab(IModel<String> title, IModel<Workspace> workspaceModel) { super(title, workspaceModel, 999); } @Override public Panel newPanel(String panelId, IModel<Workspace> workspaceModel) { return new GlobalTilesPanel(panelId, workspaceModel); } @Override public boolean isVisible() { final Action action = new AccessSitePluginAction(getWorkspaceModel().getObject()); final boolean granted = Brix.get().getAuthorizationStrategy().isActionAuthorized(action); if (granted) { JcrSession session = Brix.get().getCurrentSession(getWorkspaceModel().getObject().getId()); SitePlugin sp = SitePlugin.get(); return sp.canEditNode(sp.getGlobalContainer(session), Context.ADMINISTRATION); } return false; } } static abstract class AuthorizedWorkspaceTab extends AbstractWorkspaceTab { public AuthorizedWorkspaceTab(IModel<String> title, IModel<Workspace> workspaceModel) { super(title, workspaceModel); } public AuthorizedWorkspaceTab(IModel<String> title, IModel<Workspace> workspaceModel, int priority) { super(title, workspaceModel, priority); } @Override public boolean isVisible() { final Action action = new AccessSitePluginAction(getWorkspaceModel().getObject()); final boolean granted = Brix.get().getAuthorizationStrategy().isActionAuthorized(action); if (granted) { JcrSession session = Brix.get().getCurrentSession(getWorkspaceModel().getObject().getId()); SitePlugin sp = SitePlugin.get(); return sp.canEditNode(sp.getGlobalContainer(session), Context.ADMINISTRATION); } return false; } } static class GlobalVariablesTab extends AuthorizedWorkspaceTab { public GlobalVariablesTab(IModel<String> title, IModel<Workspace> workspaceModel) { super(title, workspaceModel, 998); } @Override public Panel newPanel(String panelId, IModel<Workspace> workspaceModel) { return new GlobalVariablesPanel(panelId, workspaceModel); } } static class WebDAVRulesTab extends AuthorizedWorkspaceTab { public WebDAVRulesTab(IModel<String> title, IModel<Workspace> workspaceModel) { super(title, workspaceModel, 0); } @Override public Panel newPanel(String panelId, IModel<Workspace> workspaceModel) { return new RulesPanel(panelId, workspaceModel); } } private class WebDavEventListener implements EventsListener { public void handleEventsBeforeSave(Session session, Item item, List<Event> events) throws RepositoryException { for (Event e : events) { if (e instanceof AddNodeEvent) { AddNodeEvent event = (AddNodeEvent) e; BrixNode node = wrapNode(event.getNewNode()); if (node instanceof ResourceNode) { handleNewNode(node.getPath(), node, brix.wrapSession(session), false); } } } } public void handleEventsAfterSave(Session session, Item item, List<Event> events) throws RepositoryException { } } private final class WebDavActionHandler extends AbstractActionHandler { private final BrixSession session; private WebDavActionHandler(BrixSession session) { this.session = session; } @Override public void afterWorkspaceMove(String srcAbsPath, String destAbsPath) throws RepositoryException { String n1 = new Path(srcAbsPath).getName().toLowerCase(); // check if the item had extension before renaming. This is used to handle special case // when coda creates // "Untitled file" node that is later renamed to real file name if (n1.lastIndexOf('.') > n1.lastIndexOf('/')) { // it had, this is probably not a new file return; } handleNewNode(destAbsPath, null, brix.wrapSession(session), true); } } }
{ "content_hash": "51585e0896ba84a9d6df1e59bc64b0c6", "timestamp": "", "source": "github", "line_count": 772, "max_line_length": 107, "avg_line_length": 37.71632124352332, "alnum_prop": 0.6461173884672184, "repo_name": "kbachl/brix-cms", "id": "7fe1ff656fea175402c23d4994c7ac47406f60ec", "size": "29117", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "brix-core/src/main/java/org/brixcms/plugin/site/SitePlugin.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "35221" }, { "name": "HTML", "bytes": "55419" }, { "name": "Java", "bytes": "1455192" }, { "name": "JavaScript", "bytes": "65729" } ], "symlink_target": "" }
[![Build Status](https://travis-ci.org/wangchongjie/multi-task.svg?branch=master)](https://travis-ci.org/wangchongjie/multi-task) [![Coverage Status](https://coveralls.io/repos/github/wangchongjie/multi-task/badge.svg?branch=master)](https://coveralls.io/github/wangchongjie/multi-task?branch=master) [![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.baidu.unbiz/multi-task/badge.svg)](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22com.baidu.unbiz%22%20AND%20a%3A%22multi-task%22) Multi-task is a Java framework for parallel processing which is based annotation. That is high performance, not intrusive and loose coupled. ## 1. Quick Start This chapter will show you how to get started with Multi-Task. [中文使用说明](https://github.com/wangchongjie/multi-engine/wiki) ### 1.1 Prerequisite In order to use Multi-Task within a Maven project, simply add the following dependency to your pom.xml. ``` <dependency> <groupId>com.baidu.unbiz</groupId> <artifactId>multi-task</artifactId> <version>1.0.0</version> </dependency> ``` ### 1.2 Create a normal service with annotation Create a normal service class whose methods will be called parallely on later. For example, a DevicePlanStatServiceImpl class is created as below. ``` @TaskService public class DevicePlanStatServiceImpl implements DevicePlanStatService { @TaskBean("deviceStatFetcher") public List<DeviceStatViewItem> queryPlanDeviceData(DeviceStatRequest req) { this.checkParam(req); return this.mockList1(); } @TaskBean("deviceUvFetcher") public List<DeviceUvViewItem> queryPlanDeviceUvData(DeviceUvRequest req) { this.checkParam(req); return this.mockList2(); } } ``` The class is marked by `@TaskService`, which could be scanned by Multi-Task framework. The `@TaskBean(task name)` is attached on the method. Then, the method could be regarded as parallel task. ### 1.3 Applying parallely processing with defined task ``` @Resource(name = "simpleParallelExePool") private ParallelExePool parallelExePool; public void testParallelFetch() { DeviceStatRequest req1 = new DeviceStatRequest(); DeviceUvRequest req2 = new DeviceUvRequest(); MultiResult ctx = parallelExePool.submit( new TaskPair("deviceStatFetcher", req1), new TaskPair("deviceUvFetcher", req2)); List<DeviceStatViewItem> stat = ctx.getResult("deviceStatFetcher"); List<DeviceUvViewItem> uv = ctx.getResult("deviceUvFetcher"); Assert.notEmpty(stat); Assert.notEmpty(uv); } ``` The task deviceStatFetcher and deviceUvFetcher will be parallely processing and atomic return. Actually, the method queryPlanDeviceData and queryPlanDeviceUvData of class DevicePlanStatServiceImpl will be implicitly executed. ### 1.4 Some other type' TaskBean Besides single param method, we could also define multi-param or void param' method for task by using `@TaskBean`. ``` @TaskService public class OtherStatServiceImpl implements OtherStatService { @TaskBean("multiParamFetcher") public List<DeviceViewItem> queryPlanDeviceDataByMultiParam(String p1, int p2, int p3) { return this.mockList1(); } @TaskBean("voidParamFetcher") public List<DeviceViewItem> queryPlanDeviceDataByVoidParam() { return this.mockList2(); } @TaskBean("doSthFailWithExceptionFetcher") public List<DeviceViewItem> queryPlanDeviceDataWithBusinessException(DeviceRequest req) { throw new BusinessException("Some business com.baidu.unbiz.multitask.vo.exception, just for test!"); } @TaskBean("doSthVerySlowFetcher") public List<DeviceViewItem> queryPlanDeviceDataWithBadNetwork(DeviceRequest req) { try { Thread.sleep(900000L); } catch (InterruptedException e) { // do nothing, just for test } return this.mockList1(); } } ``` ## 2. Advanced features ### 2.1 Explicit define task You can also define Task by implement `Taskable<T>` interface. But, not recommended. ``` @Service public class ExplicitDefTask implements Taskable<List<DeviceViewItem>> { public <E> List<DeviceViewItem> work(E request) { if (request instanceof DeviceRequest) { // do sth; return result; } return null; } } ``` ### 2.2 Explicit config thread pool Multi-Task will specify the thread pool configuration automatically considering hardware resources. It is possible to set pool parameters explicitly as well. Examples are as follows. ``` <bean name="xmlThreadPoolConfig" class="com.baidu.unbiz.multitask.constants.XmlThreadPoolConfig"> <property name="coreTaskNum" value="12"/> <property name="maxTaskNum" value="22"/> <property name="maxCacheTaskNum" value="4"/> <property name="queueFullSleepTime" value="10"/> <property name="taskTimeoutMillSeconds" value="5000"/> </bean> <bean name="simpleParallelExePool" class="com.baidu.unbiz.multitask.task.SimpleParallelExePool"> <constructor-arg ref="xmlThreadPoolConfig"/> </bean> ``` ### 2.3 Fork Join Multi-task could handle homogenous computing more friendly by fork-join mode. ForkJoin strategy should be provided to framework. ``` public void testParallelForkJoinFetch() { TaskPair taskPair = new TaskPair("deviceStatFetcher", new DeviceRequest())); ForkJoin<DeviceRequest, List<DeviceViewItem>> forkJoin = new ForkJoin<DeviceRequest, List<DeviceViewItem>>() { public List<DeviceRequest> fork(DeviceRequest deviceRequest) { List<DeviceRequest> reqs = new ArrayList<DeviceRequest>(); reqs.add(deviceRequest); reqs.add(deviceRequest); reqs.add(deviceRequest); return reqs; } public List<DeviceViewItem> join(List<List<DeviceViewItem>> lists) { List<DeviceViewItem> result = new ArrayList<DeviceViewItem>(); if (CollectionUtils.isEmpty(lists)) { return result; } for (List<DeviceViewItem> res : lists) { result.addAll(res); } return result; } }; List<DeviceViewItem> result = parallelExePool.submit(taskPair, forkJoin); Assert.notEmpty(result); } ``` ### 2.4 ThreadLocal Support Multi-task will ingore ThreadLocal of Java by default. If you want to let the ThreadLocal take effect in running task, you should do the following configuration once: ``` TaskContext.attachThreadLocal(MyThreadLocal.instance()); ``` ## 3. Examples All test cases or samples can be found from the below links: [Samples - How to define task](https://github.com/wangchongjie/multi-task/tree/master/src/test/java/com/baidu/unbiz/multitask/service) [Test cases - How to use task](https://github.com/wangchongjie/multi-task/tree/master/src/test/java/com/baidu/unbiz/multitask/demo/test) [Resources - Optional, not necessary](https://github.com/wangchongjie/multi-task/tree/master/src/test/resources) This project is licensed under [Apache v2 license](http://www.apache.org/licenses/LICENSE-2.0.txt).
{ "content_hash": "2019b6bec8026b4f310a25d8fe56bdd4", "timestamp": "", "source": "github", "line_count": 178, "max_line_length": 225, "avg_line_length": 40.93258426966292, "alnum_prop": 0.7005215481745813, "repo_name": "wangchongjie/multi-task", "id": "a9bc578633123c8d2b3f35418631c92c2e363d39", "size": "7311", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "111299" } ], "symlink_target": "" }
package elasta.orm.query.expression.builder; import elasta.criteria.Func; import java.util.List; /** * Created by Jango on 17/02/09. */ public interface SelectBuilder { SelectBuilder add(Func selection); SelectBuilder add(List<Func> selections); List<Func> build(); }
{ "content_hash": "98f0bdf78845f27be384189484274e6c", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 45, "avg_line_length": 16.941176470588236, "alnum_prop": 0.7152777777777778, "repo_name": "codefacts/elasta", "id": "b0a4f4748ab04ca090d25b2f20f2d4b58590af40", "size": "288", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "elasta-orm/src/main/java/elasta/orm/query/expression/builder/SelectBuilder.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "1192155" } ], "symlink_target": "" }
$packagesDir = "$PSScriptRoot\packages" $nuget_exe = "$PSScriptRoot\NuGet.exe" function Get-LatestPackageFolder ([string]$package) { Get-ChildItem "$packagesDir\$package.*" | Select-Object -Last 1 } # Find or download nuget.exe if (-not (Test-Path $nuget_exe)) { Write-Host "Downloading Nuget.exe" (new-object System.Net.WebClient).DownloadFile( "http://www.nuget.org/nuget.exe", $nuget_exe) } Write-Host "Restoring packages" # Download all nuget packages needed. They are downloaded to src\packages dir $env:EnableNuGetPackageRestore="true" try { & $nuget_exe install "$PSScriptRoot\packages.config" -OutputDirectory "$packagesDir" } catch [Exception]{ Write-Host "Unable to install nuget packages $($_.Exception.Message)" exit 1 } if ($lastexitcode -ne 0) { Write-Host "`nNuget install failed" exit 1 }
{ "content_hash": "12e601c40d73a0a3cf377065f214a36f", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 97, "avg_line_length": 30.703703703703702, "alnum_prop": 0.7273823884197829, "repo_name": "andlju/hyperspec", "id": "0578f3102ec1d2241a171967aca591abf06288b7", "size": "830", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "scripts/BuildBootstrap.psm1", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "100202" }, { "name": "CSS", "bytes": "52" }, { "name": "HTML", "bytes": "9717" }, { "name": "JavaScript", "bytes": "56668" }, { "name": "PowerShell", "bytes": "19587" } ], "symlink_target": "" }
<!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"/> <meta name="generator" content="Doxygen 1.8.9.1"/> <title>Able Polecat: AblePolecat_AccessControl_ResourceInterface Interface 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="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtreedata.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); $(window).load(resizeHeight); </script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </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">Able Polecat &#160;<span id="projectnumber">0.7.0</span> </div> <div id="projectbrief">Able Polecat Core Class Library</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.9.1 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <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 class="current"><a href="annotated.html"><span>Data&#160;Structures</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Data&#160;Structures</span></a></li> <li><a href="classes.html"><span>Data&#160;Structure&#160;Index</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Data&#160;Fields</span></a></li> </ul> </div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> $(document).ready(function(){initNavTree('interface_able_polecat___access_control___resource_interface.html','');}); </script> <div id="doc-content"> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="header"> <div class="summary"> <a href="#pub-methods">Public Member Functions</a> </div> <div class="headertitle"> <div class="title">AblePolecat_AccessControl_ResourceInterface Interface Reference</div> </div> </div><!--header--> <div class="contents"> <div class="dynheader"> Inheritance diagram for AblePolecat_AccessControl_ResourceInterface:</div> <div class="dyncontent"> <div class="center"> <img src="interface_able_polecat___access_control___resource_interface.png" usemap="#AblePolecat_AccessControl_ResourceInterface_map" alt=""/> <map id="AblePolecat_AccessControl_ResourceInterface_map" name="AblePolecat_AccessControl_ResourceInterface_map"> <area href="interface_able_polecat___access_control___article___dynamic_interface.html" alt="AblePolecat_AccessControl_Article_DynamicInterface" shape="rect" coords="990,56,1310,80"/> <area href="interface_able_polecat___access_control___article_interface.html" alt="AblePolecat_AccessControl_ArticleInterface" shape="rect" coords="990,0,1310,24"/> <area href="interface_able_polecat___database_interface.html" alt="AblePolecat_DatabaseInterface" shape="rect" coords="0,168,320,192"/> <area href="interface_able_polecat___resource_interface.html" alt="AblePolecat_ResourceInterface" shape="rect" coords="660,168,980,192"/> <area href="interface_able_polecat___service___initiator_interface.html" alt="AblePolecat_Service_InitiatorInterface" shape="rect" coords="1320,168,1640,192"/> <area href="interface_able_polecat___service___listener_interface.html" alt="AblePolecat_Service_ListenerInterface" shape="rect" coords="1980,168,2300,192"/> <area href="interface_able_polecat___database___pdo_interface.html" alt="AblePolecat_Database_PdoInterface" shape="rect" coords="330,224,650,248"/> <area href="class_able_polecat___database_abstract.html" alt="AblePolecat_DatabaseAbstract" shape="rect" coords="330,280,650,304"/> <area href="interface_able_polecat___resource___core_interface.html" alt="AblePolecat_Resource_CoreInterface" shape="rect" coords="990,224,1310,248"/> <area href="interface_able_polecat___resource___list_interface.html" alt="AblePolecat_Resource_ListInterface" shape="rect" coords="990,280,1310,304"/> <area href="interface_able_polecat___resource___restricted_interface.html" alt="AblePolecat_Resource_RestrictedInterface" shape="rect" coords="990,336,1310,360"/> <area href="class_able_polecat___resource_abstract.html" alt="AblePolecat_ResourceAbstract" shape="rect" coords="990,392,1310,416"/> <area href="interface_able_polecat___service___client_interface.html" alt="AblePolecat_Service_ClientInterface" shape="rect" coords="1650,224,1970,248"/> <area href="class_able_polecat___service___initiator_abstract.html" alt="AblePolecat_Service_InitiatorAbstract" shape="rect" coords="1650,280,1970,304"/> <area href="interface_able_polecat___service___interface.html" alt="AblePolecat_Service_Interface" shape="rect" coords="1650,336,1970,360"/> <area href="class_able_polecat___service___listener_abstract.html" alt="AblePolecat_Service_ListenerAbstract" shape="rect" coords="1980,224,2300,248"/> </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:aaba20e74dced7f11f018a5a86ead176e"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="interface_able_polecat___access_control___resource_interface.html#aaba20e74dced7f11f018a5a86ead176e">open</a> (<a class="el" href="interface_able_polecat___access_control___agent_interface.html">AblePolecat_AccessControl_AgentInterface</a> $Agent, <a class="el" href="interface_able_polecat___access_control___resource___locater_interface.html">AblePolecat_AccessControl_Resource_LocaterInterface</a> $Url=NULL)</td></tr> <tr class="separator:aaba20e74dced7f11f018a5a86ead176e"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="inherit_header pub_methods_interface_able_polecat___access_control___article___dynamic_interface"><td colspan="2" onclick="javascript:toggleInherit('pub_methods_interface_able_polecat___access_control___article___dynamic_interface')"><img src="closed.png" alt="-"/>&#160;Public Member Functions inherited from <a class="el" href="interface_able_polecat___access_control___article___dynamic_interface.html">AblePolecat_AccessControl_Article_DynamicInterface</a></td></tr> <tr class="memitem:a12251d0c022e9e21c137a105ff683f13 inherit pub_methods_interface_able_polecat___access_control___article___dynamic_interface"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="interface_able_polecat___access_control___article___dynamic_interface.html#a12251d0c022e9e21c137a105ff683f13">getId</a> ()</td></tr> <tr class="separator:a12251d0c022e9e21c137a105ff683f13 inherit pub_methods_interface_able_polecat___access_control___article___dynamic_interface"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a3d0963e68bb313b163a73f2803c64600 inherit pub_methods_interface_able_polecat___access_control___article___dynamic_interface"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="interface_able_polecat___access_control___article___dynamic_interface.html#a3d0963e68bb313b163a73f2803c64600">getName</a> ()</td></tr> <tr class="separator:a3d0963e68bb313b163a73f2803c64600 inherit pub_methods_interface_able_polecat___access_control___article___dynamic_interface"><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_static_methods_interface_able_polecat___access_control___article_interface"><td colspan="2" onclick="javascript:toggleInherit('pub_static_methods_interface_able_polecat___access_control___article_interface')"><img src="closed.png" alt="-"/>&#160;Static Public Member Functions inherited from <a class="el" href="interface_able_polecat___access_control___article_interface.html">AblePolecat_AccessControl_ArticleInterface</a></td></tr> <tr class="memitem:ad9ade868bd136d32967059d1cccb3e92 inherit pub_static_methods_interface_able_polecat___access_control___article_interface"><td class="memItemLeft" align="right" valign="top">static&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="interface_able_polecat___access_control___article_interface.html#ad9ade868bd136d32967059d1cccb3e92">getScope</a> ()</td></tr> <tr class="separator:ad9ade868bd136d32967059d1cccb3e92 inherit pub_static_methods_interface_able_polecat___access_control___article_interface"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> <h2 class="groupheader">Member Function Documentation</h2> <a class="anchor" id="aaba20e74dced7f11f018a5a86ead176e"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">open </td> <td>(</td> <td class="paramtype"><a class="el" href="interface_able_polecat___access_control___agent_interface.html">AblePolecat_AccessControl_AgentInterface</a>&#160;</td> <td class="paramname"><em>$Agent</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype"><a class="el" href="interface_able_polecat___access_control___resource___locater_interface.html">AblePolecat_AccessControl_Resource_LocaterInterface</a>&#160;</td> <td class="paramname"><em>$Url</em> = <code>NULL</code>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td> </tr> </table> </div><div class="memdoc"> <p>Opens an existing resource or makes an empty one accessible depending on permissions.</p> <dl class="params"><dt>Parameters</dt><dd> <table class="params"> <tr><td class="paramtype"><a class="el" href="interface_able_polecat___access_control___agent_interface.html">AblePolecat_AccessControl_AgentInterface</a></td><td class="paramname">$agent</td><td>Agent seeking access. </td></tr> <tr><td class="paramtype"><a class="el" href="interface_able_polecat___access_control___resource___locater_interface.html">AblePolecat_AccessControl_Resource_LocaterInterface</a></td><td class="paramname">$Url</td><td>Existing or new resource. </td></tr> <tr><td class="paramtype">string</td><td class="paramname">$name</td><td>Optional common name for new resources.</td></tr> </table> </dd> </dl> <dl class="section return"><dt>Returns</dt><dd>bool TRUE if access to resource is granted, otherwise FALSE. </dd></dl> <p>Implemented in <a class="el" href="class_able_polecat___resource_abstract.html#aaba20e74dced7f11f018a5a86ead176e">AblePolecat_ResourceAbstract</a>, and <a class="el" href="class_able_polecat___database___pdo.html#a4ce5c2e3d8229d890939c780db9c8ba8">AblePolecat_Database_Pdo</a>.</p> </div> </div> <hr/>The documentation for this interface was generated from the following file:<ul> <li>C:/wamp/www/polecat/public/core/AccessControl/Resource.php</li> </ul> </div><!-- contents --> </div><!-- doc-content --> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> <li class="navelem"><a class="el" href="interface_able_polecat___access_control___resource_interface.html">AblePolecat_AccessControl_ResourceInterface</a></li> <li class="footer">Generated on Fri Apr 10 2015 11:24:45 for Able Polecat by <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.9.1 </li> </ul> </div> </body> </html>
{ "content_hash": "aaea74f2aeb977a7507b2fbe8d956243", "timestamp": "", "source": "github", "line_count": 211, "max_line_length": 598, "avg_line_length": 67.76303317535545, "alnum_prop": 0.7085606378514477, "repo_name": "kkuhrman/AblePolecat", "id": "bde0969e4d4f1ed7d491125b7c2c6da45e382243", "size": "14298", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "usr/share/documentation/html/interface_able_polecat___access_control___resource_interface.html", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "PHP", "bytes": "1010057" } ], "symlink_target": "" }
package models type Geolocation struct { IPAddress string `json:"ipaddress"` City string `json:"city"` Country string `json:"country"` Latitude float64 `json:"latitude"` Longitude float64 `json:"longitude"` }
{ "content_hash": "9dadf536ba7a6bf1c942764fd7f6576c", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 37, "avg_line_length": 25.11111111111111, "alnum_prop": 0.7079646017699115, "repo_name": "zulhilmizainuddin/geoip-webservice", "id": "340cfeee9b102169c51121ec88f368e0bca5a8fd", "size": "226", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "models/geolocation.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "3776" } ], "symlink_target": "" }
<!-- This file is generated automatically. Do not change its content. --> The BarChart control enables you to render a bar chart from one or more series of values.
{ "content_hash": "f3577d3bdb63b4f37f40a3008a463091", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 91, "avg_line_length": 82.5, "alnum_prop": 0.7575757575757576, "repo_name": "DevExpress/AjaxControlToolkit", "id": "a0be7229f838378993b5d94fbf915121dd6d432c", "size": "165", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "AjaxControlToolkit.SampleSite/App_Data/ControlReference/BarChart.Description.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ASP", "bytes": "500398" }, { "name": "C#", "bytes": "1575499" }, { "name": "CSS", "bytes": "122964" }, { "name": "HTML", "bytes": "100900" }, { "name": "JavaScript", "bytes": "2995611" }, { "name": "PowerShell", "bytes": "3240" } ], "symlink_target": "" }
from __future__ import unicode_literals import sys from PySide import QtGui from PySide import QtCore class Ejemplo11(QtGui.QWidget): def __init__(self): super(Ejemplo11, self).__init__() self.WidgetsParte2_4() def WidgetsParte2_4(self): self.boton = QtGui.QPushButton('Abrir imagen') self.boton.clicked.connect(self.abrir_imagen) self.imagen_etiqueta = QtGui.QLabel() self.imagen_etiqueta.setBackgroundRole(QtGui.QPalette.Base) self.imagen_etiqueta.setSizePolicy(QtGui.QSizePolicy.Ignored, QtGui.QSizePolicy.Ignored) self.vbox = QtGui.QVBoxLayout() self.vbox.addWidget(self.imagen_etiqueta) self.vbox.addWidget(self.boton) self.setLayout(self.vbox) self.setGeometry(300, 50, 500, 650) self.setWindowTitle('Ejemplo de widget N°4') self.show() def abrir_imagen(self): imagen_abierta = QtGui.QFileDialog.getOpenFileName(self, 'Abrir imagen', QtCore.QDir.currentPath(), 'Archivos de imagen (*.jpg *.png *gif)') if imagen_abierta: imagen = QtGui.QImage(imagen_abierta[0]) if imagen.isNull(): print imagen.isNull() self.imagen_etiqueta.setPixmap( QtGui.QPixmap.fromImage(imagen)) self.imagen_etiqueta.setScaledContents(True) if __name__ == '__main__': app = QtGui.QApplication(sys.argv) ej11 = Ejemplo11() sys.exit(app.exec_())
{ "content_hash": "b353953d9eeeea6e5614535c228344f8", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 69, "avg_line_length": 31.93617021276596, "alnum_prop": 0.6295802798134577, "repo_name": "DoctorMalboro/CharlaPySidePyDayLujan2014", "id": "798059fad1cc20011719935fe431a61385f1ceae", "size": "1526", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ejemplos/ejemplo-11.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "123520" }, { "name": "JavaScript", "bytes": "132187" }, { "name": "Python", "bytes": "18931" } ], "symlink_target": "" }
#include "config.h" #include "WebKitCSSArrayFunctionValue.h" #if ENABLE(CSS_SHADERS) namespace WebCore { WebKitCSSArrayFunctionValue::WebKitCSSArrayFunctionValue() : CSSValueList(WebKitCSSArrayFunctionValueClass, CommaSeparator) { } WebKitCSSArrayFunctionValue::WebKitCSSArrayFunctionValue(const WebKitCSSArrayFunctionValue& cloneFrom) : CSSValueList(cloneFrom) { } String WebKitCSSArrayFunctionValue::customCSSText() const { return "array(" + CSSValueList::customCSSText() + ')'; } PassRefPtr<WebKitCSSArrayFunctionValue> WebKitCSSArrayFunctionValue::cloneForCSSOM() const { return adoptRef(new WebKitCSSArrayFunctionValue(*this)); } bool WebKitCSSArrayFunctionValue::equals(const WebKitCSSArrayFunctionValue& other) const { return CSSValueList::equals(other); } } // namespace WebCore #endif // ENABLE(CSS_SHADERS)
{ "content_hash": "1638c2440facf0ba94e5111d6e67098d", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 102, "avg_line_length": 22.91891891891892, "alnum_prop": 0.7936320754716981, "repo_name": "klim-iv/phantomjs-qt5", "id": "813016913de8120df3c1bf995c7c81d55de0b69f", "size": "2218", "binary": false, "copies": "1", "ref": "refs/heads/qt5", "path": "src/webkit/Source/WebCore/css/WebKitCSSArrayFunctionValue.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "291913" }, { "name": "Awk", "bytes": "3965" }, { "name": "C", "bytes": "42431954" }, { "name": "C++", "bytes": "128347641" }, { "name": "CSS", "bytes": "778535" }, { "name": "CoffeeScript", "bytes": "46367" }, { "name": "D", "bytes": "1931" }, { "name": "Emacs Lisp", "bytes": "8191" }, { "name": "IDL", "bytes": "191984" }, { "name": "Java", "bytes": "232840" }, { "name": "JavaScript", "bytes": "16127527" }, { "name": "Objective-C", "bytes": "10465655" }, { "name": "PHP", "bytes": "1223" }, { "name": "Perl", "bytes": "1296504" }, { "name": "Python", "bytes": "5916339" }, { "name": "Ruby", "bytes": "381483" }, { "name": "Shell", "bytes": "1005210" }, { "name": "Smalltalk", "bytes": "1308" }, { "name": "VimL", "bytes": "3731" }, { "name": "XSLT", "bytes": "50637" } ], "symlink_target": "" }
local class = require('opus.class') local UI = require('opus.ui') local Util = require('opus.util') UI.Text = class(UI.Window) UI.Text.defaults = { UIElement = 'Text', value = '', height = 1, } function UI.Text:layout() if not self.width and not self.ex then self.width = #tostring(self.value) end UI.Window.layout(self) end function UI.Text:draw() self:write(1, 1, Util.widthify(self.value, self.width, self.align)) end
{ "content_hash": "a792d3eb8d2791186fb200e47a8a9b5e", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 68, "avg_line_length": 21.8, "alnum_prop": 0.6857798165137615, "repo_name": "kepler155c/opus", "id": "5bf379921d8c4b8a2eae8adb868a55cefc1477cc", "size": "436", "binary": false, "copies": "1", "ref": "refs/heads/develop-1.8", "path": "sys/modules/opus/ui/components/Text.lua", "mode": "33188", "license": "mit", "language": [ { "name": "Lua", "bytes": "543174" } ], "symlink_target": "" }
package org.duracloud.common.annotation; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import org.apache.commons.beanutils.BeanUtils; /** * @author "Daniel Bernstein (dbernstein@durspace.org)" */ public class FieldMatchValidator implements ConstraintValidator<FieldMatch, Object> { private FieldMatch constraintAnnotation; @Override public void initialize(final FieldMatch constraintAnnotation) { this.constraintAnnotation = constraintAnnotation; } @Override public boolean isValid( final Object value, final ConstraintValidatorContext context) { try { final Object firstObj = BeanUtils.getProperty(value, this.constraintAnnotation.first()); final Object secondObj = BeanUtils.getProperty(value, this.constraintAnnotation.second()); boolean doesNotMatch = firstObj == null && secondObj == null || firstObj != null && firstObj.equals(secondObj); if (!doesNotMatch) { context.disableDefaultConstraintViolation(); context.buildConstraintViolationWithTemplate(this.constraintAnnotation.message()) .addNode(this.constraintAnnotation.second()).addConstraintViolation(); } return doesNotMatch; } catch (final Exception ignore) { // ignore } return true; } }
{ "content_hash": "e2da5838919342c54c3dc4ded12275a4", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 102, "avg_line_length": 33.27272727272727, "alnum_prop": 0.6700819672131147, "repo_name": "duracloud/management-console", "id": "6b5175a69836fb258211af43b30ea2f26333a15d", "size": "1682", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "account-management-app/src/main/java/org/duracloud/common/annotation/FieldMatchValidator.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "41522" }, { "name": "Java", "bytes": "639876" }, { "name": "JavaScript", "bytes": "29991" }, { "name": "Shell", "bytes": "2559" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_05) on Thu Nov 12 23:45:52 CET 2015 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>Uses of Interface org.osmdroid.views.overlay.ItemizedOverlayControlView.ItemizedOverlayControlViewListener (OSMdroid Android 5.0.1 API)</title> <meta name="date" content="2015-11-12"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Interface org.osmdroid.views.overlay.ItemizedOverlayControlView.ItemizedOverlayControlViewListener (OSMdroid Android 5.0.1 API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../org/osmdroid/views/overlay/ItemizedOverlayControlView.ItemizedOverlayControlViewListener.html" title="interface in org.osmdroid.views.overlay">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/osmdroid/views/overlay/class-use/ItemizedOverlayControlView.ItemizedOverlayControlViewListener.html" target="_top">Frames</a></li> <li><a href="ItemizedOverlayControlView.ItemizedOverlayControlViewListener.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Interface org.osmdroid.views.overlay.ItemizedOverlayControlView.ItemizedOverlayControlViewListener" class="title">Uses of Interface<br>org.osmdroid.views.overlay.ItemizedOverlayControlView.ItemizedOverlayControlViewListener</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../org/osmdroid/views/overlay/ItemizedOverlayControlView.ItemizedOverlayControlViewListener.html" title="interface in org.osmdroid.views.overlay">ItemizedOverlayControlView.ItemizedOverlayControlViewListener</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#org.osmdroid.views.overlay">org.osmdroid.views.overlay</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.osmdroid.views.overlay"> <!-- --> </a> <h3>Uses of <a href="../../../../../org/osmdroid/views/overlay/ItemizedOverlayControlView.ItemizedOverlayControlViewListener.html" title="interface in org.osmdroid.views.overlay">ItemizedOverlayControlView.ItemizedOverlayControlViewListener</a> in <a href="../../../../../org/osmdroid/views/overlay/package-summary.html">org.osmdroid.views.overlay</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing fields, and an explanation"> <caption><span>Fields in <a href="../../../../../org/osmdroid/views/overlay/package-summary.html">org.osmdroid.views.overlay</a> declared as <a href="../../../../../org/osmdroid/views/overlay/ItemizedOverlayControlView.ItemizedOverlayControlViewListener.html" title="interface in org.osmdroid.views.overlay">ItemizedOverlayControlView.ItemizedOverlayControlViewListener</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>protected <a href="../../../../../org/osmdroid/views/overlay/ItemizedOverlayControlView.ItemizedOverlayControlViewListener.html" title="interface in org.osmdroid.views.overlay">ItemizedOverlayControlView.ItemizedOverlayControlViewListener</a></code></td> <td class="colLast"><span class="strong">ItemizedOverlayControlView.</span><code><strong><a href="../../../../../org/osmdroid/views/overlay/ItemizedOverlayControlView.html#mLis">mLis</a></strong></code>&nbsp;</td> </tr> </tbody> </table> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../org/osmdroid/views/overlay/package-summary.html">org.osmdroid.views.overlay</a> with parameters of type <a href="../../../../../org/osmdroid/views/overlay/ItemizedOverlayControlView.ItemizedOverlayControlViewListener.html" title="interface in org.osmdroid.views.overlay">ItemizedOverlayControlView.ItemizedOverlayControlViewListener</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><span class="strong">ItemizedOverlayControlView.</span><code><strong><a href="../../../../../org/osmdroid/views/overlay/ItemizedOverlayControlView.html#setItemizedOverlayControlViewListener(org.osmdroid.views.overlay.ItemizedOverlayControlView.ItemizedOverlayControlViewListener)">setItemizedOverlayControlViewListener</a></strong>(<a href="../../../../../org/osmdroid/views/overlay/ItemizedOverlayControlView.ItemizedOverlayControlViewListener.html" title="interface in org.osmdroid.views.overlay">ItemizedOverlayControlView.ItemizedOverlayControlViewListener</a>&nbsp;lis)</code>&nbsp;</td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../org/osmdroid/views/overlay/ItemizedOverlayControlView.ItemizedOverlayControlViewListener.html" title="interface in org.osmdroid.views.overlay">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/osmdroid/views/overlay/class-use/ItemizedOverlayControlView.ItemizedOverlayControlViewListener.html" target="_top">Frames</a></li> <li><a href="ItemizedOverlayControlView.ItemizedOverlayControlViewListener.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2015. All Rights Reserved.</small></p> </body> </html>
{ "content_hash": "26d7a614a7686e46cef8a08290c74a15", "timestamp": "", "source": "github", "line_count": 170, "max_line_length": 612, "avg_line_length": 51.11176470588235, "alnum_prop": 0.6960524801473127, "repo_name": "osmdroid/OsmdroidXamarin", "id": "4319293792e449d73f61fc587a880dc12a7a1667", "size": "8689", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "OsmdroidAndroidBinding/JavaDocs/osmdroid-android-5.0.1-javadoc/org/osmdroid/views/overlay/class-use/ItemizedOverlayControlView.ItemizedOverlayControlViewListener.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "668" }, { "name": "C#", "bytes": "33087" }, { "name": "CSS", "bytes": "22278" }, { "name": "HTML", "bytes": "6366072" } ], "symlink_target": "" }
<?php namespace app\modules\shop\models; use Yii; use yii\behaviors\TimestampBehavior; /** * This is the model class for table "{{%inventory_storage_rel}}". * * @property integer $id * @property integer $storage_id * @property integer $goods_id * @property integer $sku_id * @property integer $total * @property string $note * @property integer $created_at */ class InventoryStorageRel extends \app\core\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return '{{%inventory_storage_rel}}'; } /** * @inheritdoc */ public function rules() { return [ [['storage_id', 'goods_id', 'sku_id'], 'required'], [['storage_id', 'goods_id', 'sku_id', 'total', 'created_at', 'status'], 'integer'], [['note'], 'string'], ]; } public function behaviors() { return [ [ 'class' => TimestampBehavior::className(), 'attributes' => [ InventorySupplier::EVENT_BEFORE_INSERT => ['created_at'], ], ], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'storage_id' => '仓库', 'goods_id' => '商品', 'sku_id' => 'Sku', 'total' => '总数量', 'note' => '备注', 'created_at' => '添加时间', ]; } /** * @name 添加库存,如果没有记录,则添加记录 */ public static function add() { } public function getGoods() { return $this->hasOne(Goods::className(), ['id'=>'goods_id']); } public function getSku() { return $this->hasOne(Sku::className(), ['id'=>'sku_id']); } public function getStorage() { return $this->hasOne(InventoryStorage::className(), ['id'=>'storage_id']); } }
{ "content_hash": "98de2c6b8ba5784c1e632b1ae8a2f86d", "timestamp": "", "source": "github", "line_count": 88, "max_line_length": 95, "avg_line_length": 21.90909090909091, "alnum_prop": 0.4927385892116183, "repo_name": "cboy868/lion", "id": "6a4ea7b347569f572bc001de7f23e03e5252b3e7", "size": "1988", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/shop/models/InventoryStorageRel.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ActionScript", "bytes": "20283" }, { "name": "ApacheConf", "bytes": "514" }, { "name": "Batchfile", "bytes": "515" }, { "name": "CSS", "bytes": "1596076" }, { "name": "HTML", "bytes": "388819" }, { "name": "JavaScript", "bytes": "8084067" }, { "name": "PHP", "bytes": "10347057" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_75) on Wed Mar 18 19:43:01 PDT 2015 --> <title>PollServiceGrpc.PollServiceFutureStub (grpc-examples 0.1.0-SNAPSHOT API)</title> <meta name="date" content="2015-03-18"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="PollServiceGrpc.PollServiceFutureStub (grpc-examples 0.1.0-SNAPSHOT API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../edu/sjsu/cmpe273/lab2/PollServiceGrpc.PollServiceFutureClient.html" title="interface in edu.sjsu.cmpe273.lab2"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../edu/sjsu/cmpe273/lab2/PollServiceGrpc.PollServiceServiceDescriptor.html" title="class in edu.sjsu.cmpe273.lab2"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?edu/sjsu/cmpe273/lab2/PollServiceGrpc.PollServiceFutureStub.html" target="_top">Frames</a></li> <li><a href="PollServiceGrpc.PollServiceFutureStub.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li><a href="#nested_classes_inherited_from_class_io.grpc.stub.AbstractStub">Nested</a>&nbsp;|&nbsp;</li> <li><a href="#fields_inherited_from_class_io.grpc.stub.AbstractStub">Field</a>&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">edu.sjsu.cmpe273.lab2</div> <h2 title="Class PollServiceGrpc.PollServiceFutureStub" class="title">Class PollServiceGrpc.PollServiceFutureStub</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>io.grpc.stub.AbstractStub&lt;<a href="../../../../edu/sjsu/cmpe273/lab2/PollServiceGrpc.PollServiceFutureStub.html" title="class in edu.sjsu.cmpe273.lab2">PollServiceGrpc.PollServiceFutureStub</a>,<a href="../../../../edu/sjsu/cmpe273/lab2/PollServiceGrpc.PollServiceServiceDescriptor.html" title="class in edu.sjsu.cmpe273.lab2">PollServiceGrpc.PollServiceServiceDescriptor</a>&gt;</li> <li> <ul class="inheritance"> <li>edu.sjsu.cmpe273.lab2.PollServiceGrpc.PollServiceFutureStub</li> </ul> </li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Implemented Interfaces:</dt> <dd><a href="../../../../edu/sjsu/cmpe273/lab2/PollServiceGrpc.PollServiceFutureClient.html" title="interface in edu.sjsu.cmpe273.lab2">PollServiceGrpc.PollServiceFutureClient</a></dd> </dl> <dl> <dt>Enclosing class:</dt> <dd><a href="../../../../edu/sjsu/cmpe273/lab2/PollServiceGrpc.html" title="class in edu.sjsu.cmpe273.lab2">PollServiceGrpc</a></dd> </dl> <hr> <br> <pre>public static class <span class="strong">PollServiceGrpc.PollServiceFutureStub</span> extends io.grpc.stub.AbstractStub&lt;<a href="../../../../edu/sjsu/cmpe273/lab2/PollServiceGrpc.PollServiceFutureStub.html" title="class in edu.sjsu.cmpe273.lab2">PollServiceGrpc.PollServiceFutureStub</a>,<a href="../../../../edu/sjsu/cmpe273/lab2/PollServiceGrpc.PollServiceServiceDescriptor.html" title="class in edu.sjsu.cmpe273.lab2">PollServiceGrpc.PollServiceServiceDescriptor</a>&gt; implements <a href="../../../../edu/sjsu/cmpe273/lab2/PollServiceGrpc.PollServiceFutureClient.html" title="interface in edu.sjsu.cmpe273.lab2">PollServiceGrpc.PollServiceFutureClient</a></pre> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== NESTED CLASS SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="nested_class_summary"> <!-- --> </a> <h3>Nested Class Summary</h3> <ul class="blockList"> <li class="blockList"><a name="nested_classes_inherited_from_class_io.grpc.stub.AbstractStub"> <!-- --> </a> <h3>Nested classes/interfaces inherited from class&nbsp;io.grpc.stub.AbstractStub</h3> <code>io.grpc.stub.AbstractStub.StubConfigBuilder</code></li> </ul> </li> </ul> <!-- =========== FIELD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="field_summary"> <!-- --> </a> <h3>Field Summary</h3> <ul class="blockList"> <li class="blockList"><a name="fields_inherited_from_class_io.grpc.stub.AbstractStub"> <!-- --> </a> <h3>Fields inherited from class&nbsp;io.grpc.stub.AbstractStub</h3> <code>channel, config</code></li> </ul> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>protected <a href="../../../../edu/sjsu/cmpe273/lab2/PollServiceGrpc.PollServiceFutureStub.html" title="class in edu.sjsu.cmpe273.lab2">PollServiceGrpc.PollServiceFutureStub</a></code></td> <td class="colLast"><code><strong><a href="../../../../edu/sjsu/cmpe273/lab2/PollServiceGrpc.PollServiceFutureStub.html#build(io.grpc.Channel,%20edu.sjsu.cmpe273.lab2.PollServiceGrpc.PollServiceServiceDescriptor)">build</a></strong>(io.grpc.Channel&nbsp;channel, <a href="../../../../edu/sjsu/cmpe273/lab2/PollServiceGrpc.PollServiceServiceDescriptor.html" title="class in edu.sjsu.cmpe273.lab2">PollServiceGrpc.PollServiceServiceDescriptor</a>&nbsp;config)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>com.google.common.util.concurrent.ListenableFuture&lt;<a href="../../../../edu/sjsu/cmpe273/lab2/PollResponse.html" title="class in edu.sjsu.cmpe273.lab2">PollResponse</a>&gt;</code></td> <td class="colLast"><code><strong><a href="../../../../edu/sjsu/cmpe273/lab2/PollServiceGrpc.PollServiceFutureStub.html#createPoll(edu.sjsu.cmpe273.lab2.PollRequest)">createPoll</a></strong>(<a href="../../../../edu/sjsu/cmpe273/lab2/PollRequest.html" title="class in edu.sjsu.cmpe273.lab2">PollRequest</a>&nbsp;request)</code>&nbsp;</td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_io.grpc.stub.AbstractStub"> <!-- --> </a> <h3>Methods inherited from class&nbsp;io.grpc.stub.AbstractStub</h3> <code>configureNewStub, getChannel, getServiceDescriptor</code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="build(io.grpc.Channel, edu.sjsu.cmpe273.lab2.PollServiceGrpc.PollServiceServiceDescriptor)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>build</h4> <pre>protected&nbsp;<a href="../../../../edu/sjsu/cmpe273/lab2/PollServiceGrpc.PollServiceFutureStub.html" title="class in edu.sjsu.cmpe273.lab2">PollServiceGrpc.PollServiceFutureStub</a>&nbsp;build(io.grpc.Channel&nbsp;channel, <a href="../../../../edu/sjsu/cmpe273/lab2/PollServiceGrpc.PollServiceServiceDescriptor.html" title="class in edu.sjsu.cmpe273.lab2">PollServiceGrpc.PollServiceServiceDescriptor</a>&nbsp;config)</pre> <dl> <dt><strong>Specified by:</strong></dt> <dd><code>build</code>&nbsp;in class&nbsp;<code>io.grpc.stub.AbstractStub&lt;<a href="../../../../edu/sjsu/cmpe273/lab2/PollServiceGrpc.PollServiceFutureStub.html" title="class in edu.sjsu.cmpe273.lab2">PollServiceGrpc.PollServiceFutureStub</a>,<a href="../../../../edu/sjsu/cmpe273/lab2/PollServiceGrpc.PollServiceServiceDescriptor.html" title="class in edu.sjsu.cmpe273.lab2">PollServiceGrpc.PollServiceServiceDescriptor</a>&gt;</code></dd> </dl> </li> </ul> <a name="createPoll(edu.sjsu.cmpe273.lab2.PollRequest)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>createPoll</h4> <pre>public&nbsp;com.google.common.util.concurrent.ListenableFuture&lt;<a href="../../../../edu/sjsu/cmpe273/lab2/PollResponse.html" title="class in edu.sjsu.cmpe273.lab2">PollResponse</a>&gt;&nbsp;createPoll(<a href="../../../../edu/sjsu/cmpe273/lab2/PollRequest.html" title="class in edu.sjsu.cmpe273.lab2">PollRequest</a>&nbsp;request)</pre> <dl> <dt><strong>Specified by:</strong></dt> <dd><code><a href="../../../../edu/sjsu/cmpe273/lab2/PollServiceGrpc.PollServiceFutureClient.html#createPoll(edu.sjsu.cmpe273.lab2.PollRequest)">createPoll</a></code>&nbsp;in interface&nbsp;<code><a href="../../../../edu/sjsu/cmpe273/lab2/PollServiceGrpc.PollServiceFutureClient.html" title="interface in edu.sjsu.cmpe273.lab2">PollServiceGrpc.PollServiceFutureClient</a></code></dd> </dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../edu/sjsu/cmpe273/lab2/PollServiceGrpc.PollServiceFutureClient.html" title="interface in edu.sjsu.cmpe273.lab2"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../edu/sjsu/cmpe273/lab2/PollServiceGrpc.PollServiceServiceDescriptor.html" title="class in edu.sjsu.cmpe273.lab2"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?edu/sjsu/cmpe273/lab2/PollServiceGrpc.PollServiceFutureStub.html" target="_top">Frames</a></li> <li><a href="PollServiceGrpc.PollServiceFutureStub.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li><a href="#nested_classes_inherited_from_class_io.grpc.stub.AbstractStub">Nested</a>&nbsp;|&nbsp;</li> <li><a href="#fields_inherited_from_class_io.grpc.stub.AbstractStub">Field</a>&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
{ "content_hash": "c7eda6db95835b52c4374b8def883cbf", "timestamp": "", "source": "github", "line_count": 294, "max_line_length": 442, "avg_line_length": 44.8469387755102, "alnum_prop": 0.6784224497535077, "repo_name": "nivedhithaVenkatachalam/grpc-java", "id": "a86edb59f04227629bd6dc1643b97b5b0e3c24eb", "size": "13185", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "examples/build/docs/javadoc/edu/sjsu/cmpe273/lab2/PollServiceGrpc.PollServiceFutureStub.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C++", "bytes": "27373" }, { "name": "Java", "bytes": "951496" }, { "name": "Protocol Buffer", "bytes": "21910" }, { "name": "Shell", "bytes": "1396" } ], "symlink_target": "" }
 using System; using System.Collections.Generic; using XenAdmin.Core; using XenAdmin.Dialogs; using XenAPI; using XenAdmin.Controls; using XenAdmin.Actions; using XenAdmin.SettingsPanels; using System.Drawing; namespace XenAdmin.Wizards.NewVMWizard { public partial class Page_CloudConfigParameters : XenTabPage, IEditPage { private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private VM vmOrTemplate; private string existingConfig; public Host Affinity { get; set; } public Page_CloudConfigParameters() { InitializeComponent(); } void ConfigDriveTemplateTextBox_TextChanged(object sender, EventArgs e) { OnPageUpdated(); } public override string Text { get { return Messages.NEWVMWIZARD_CLOUD_CONFIG_PARAMETERS_PAGE; } } public string SubText { get { return IncludeConfigDriveCheckBox.Checked ? Messages.VM_CLOUD_CONFIG_DRIVE_INCLUDED : Messages.VM_CLOUD_CONFIG_DRIVE_NOT_INCLUDED; } } public Image Image { get { return Properties.Resources.coreos_16; } } public override string PageTitle { get { return Messages.NEWVMWIZARD_CLOUD_CONFIG_PARAMETERS_PAGE_TITLE; } } public override string HelpID { get { return "CloudConfigParameters"; } } public override bool EnableNext() { return true; } public override void PageLoaded(PageLoadedDirection direction) { base.PageLoaded(direction); if (SelectedTemplate == vmOrTemplate) return; vmOrTemplate = SelectedTemplate; GetCloudConfigParameters(); ShowHideButtonsAndWarnings(true); } public VM SelectedTemplate { private get; set; } public string ConfigDriveTemplateText { get { return IncludeConfigDriveCheckBox.Checked ? ConfigDriveTemplateTextBox.Text.Trim() : string.Empty; } } public override List<KeyValuePair<string, string>> PageSummary { get { List<KeyValuePair<string, string>> sum = new List<KeyValuePair<string, string>>(); sum.Add(new KeyValuePair<string, string>(Messages.NEWVMWIZARD_CLOUD_CONFIG_PARAMETERS_PAGE, SubText)); return sum; } } private void IncludeConfigDriveCheckBox_CheckedChanged(object sender, EventArgs e) { ConfigDriveTemplateTextBox.Enabled = IncludeConfigDriveCheckBox.Checked; } private void GetCloudConfigParameters() { var configDrive = vmOrTemplate.CloudConfigDrive; GetCloudConfigParameters(configDrive); } private bool errorRetrievingConfigParameters; private void GetCloudConfigParameters(VDI configDrive) { var defaultConfig = configDrive == null; var parameters = new Dictionary<string, string>(); if (defaultConfig) parameters.Add("templateuuid", vmOrTemplate.uuid); else parameters.Add("vdiuuid", configDrive.uuid); var action = new ExecutePluginAction(Connection, Affinity ?? Helpers.GetMaster(Connection), "xscontainer",//plugin defaultConfig ? "get_config_drive_default" : "get_config_drive_configuration",//function parameters, true); //hidefromlogs try { action.RunExternal(Connection.Session); var result = action.Result.Replace("\n", Environment.NewLine); ConfigDriveTemplateTextBox.Text = result; existingConfig = result; errorRetrievingConfigParameters = false; } catch (Exception) { log.Warn("Could not get the config drive parameters"); errorRetrievingConfigParameters = true; } } private void GetDefaultParameters() { GetCloudConfigParameters(null); } public void ShowHideButtonsAndWarnings(bool inNewVmWizard) { // IncludeConfigDriveCheckBox and reloadDefaults only visible in the New VM Wizard IncludeConfigDriveCheckBox.Visible = reloadDefaults.Visible = inNewVmWizard; // for existing VMs, the cloud config cannot be edited on non-halted VMs or when we failed to retrive the existing cloud config parameters bool canEdit = inNewVmWizard || !errorRetrievingConfigParameters && (vmOrTemplate.is_a_template || vmOrTemplate.power_state == vm_power_state.Halted); ConfigDriveTemplateTextBox.ReadOnly = !canEdit; warningsTable.Visible = errorRetrievingConfigParameters || !canEdit; labelWarning.Text = errorRetrievingConfigParameters ? Messages.VM_CLOUD_CONFIG_DRIVE_UNAVAILABLE : Messages.VM_CLOUD_CONFIG_DRIVE_READONLY; } private void reloadDefaults_Click(object sender, EventArgs e) { GetDefaultParameters(); if (errorRetrievingConfigParameters) new ThreeButtonDialog(new ThreeButtonDialog.Details(SystemIcons.Error, Messages.VM_CLOUD_CONFIG_DRIVE_CANNOT_RETRIEVE_DEFAULT)).ShowDialog(this); } #region Implementation of IEditPage public AsyncAction SaveSettings() { var configDrive = vmOrTemplate.CloudConfigDrive; if (configDrive == null || string.IsNullOrEmpty(ConfigDriveTemplateText)) return null; SR sr = vmOrTemplate.Connection.Resolve(configDrive.SR); if (sr == null) return null; var parameters = new Dictionary<string, string>(); parameters.Add("vmuuid", vmOrTemplate.uuid); parameters.Add("sruuid", sr.uuid); parameters.Add("configuration", ConfigDriveTemplateText.Replace("\r\n", "\n")); return new ExecutePluginAction(Connection, vmOrTemplate.Home() ?? Helpers.GetMaster(Connection), "xscontainer", //plugin "create_config_drive", //function parameters, true); //hidefromlogs } public void SetXenObjects(IXenObject orig, IXenObject clone) { vmOrTemplate = (VM)clone; if (Connection == null) // on the PropertiesDialog Connection = vmOrTemplate.Connection; GetCloudConfigParameters(); ShowHideButtonsAndWarnings(false); } public bool ValidToSave { get { return true; } } public void ShowLocalValidationMessages() { } public void Cleanup() { } public bool HasChanged { get { return existingConfig != ConfigDriveTemplateText; } } #endregion } }
{ "content_hash": "064d3614bba463d15d2591da7e8a6a33", "timestamp": "", "source": "github", "line_count": 223, "max_line_length": 161, "avg_line_length": 33.300448430493276, "alnum_prop": 0.5892809049286292, "repo_name": "robhoes/xenadmin", "id": "948f8b1e0a08c48b3f6c4861b0919c2d9779814d", "size": "8856", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "XenAdmin/Wizards/NewVMWizard/Page_CloudConfigParameters.cs", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Batchfile", "bytes": "608" }, { "name": "C", "bytes": "1955" }, { "name": "C#", "bytes": "15933813" }, { "name": "C++", "bytes": "21642" }, { "name": "CSS", "bytes": "11145" }, { "name": "HTML", "bytes": "4430" }, { "name": "JavaScript", "bytes": "829" }, { "name": "PowerShell", "bytes": "40" }, { "name": "Shell", "bytes": "85218" }, { "name": "Visual Basic", "bytes": "11647" } ], "symlink_target": "" }
package io.awacs.component.org.jetbrains.java.decompiler.code.optinstructions; import io.awacs.component.org.jetbrains.java.decompiler.code.JumpInstruction; import java.io.DataOutputStream; import java.io.IOException; public class GOTO_W extends JumpInstruction { public void writeToStream(DataOutputStream out, int offset) throws IOException { out.writeByte(opc_goto_w); out.writeInt(getOperand(0)); } public int length() { return 5; } }
{ "content_hash": "52ccc7c698c1112ff57861a164332113", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 82, "avg_line_length": 24.473684210526315, "alnum_prop": 0.7655913978494624, "repo_name": "ArcherFeel/AWACS", "id": "345a10d523891007346ebdf679882b5bfdd73d59", "size": "1065", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "awacs-component/awacs-fernflower-component/src/main/java/io/awacs/component/org/jetbrains/java/decompiler/code/optinstructions/GOTO_W.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "194069" }, { "name": "Shell", "bytes": "2436" } ], "symlink_target": "" }
package org.apache.geode.internal.logging; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; /** * Defines the common date format for GemFire and provides DateFormat instances. * */ public class DateFormatter { /** * The format string used to format the timestamp of GemFire log messages */ public static final String FORMAT_STRING = "yyyy/MM/dd HH:mm:ss.SSS z"; private static final DateFormat timeFormatter = createDateFormat(); /** * Creates a SimpleDateFormat using {@link #FORMAT_STRING}. * * Thread Safety Issue: (From SimpleDateFormat) Date formats are not synchronized. It is * recommended to create separate format instances for each thread. If multiple threads access a * format concurrently, it must be synchronized externally. */ public static DateFormat createDateFormat() { return new SimpleDateFormat(DateFormatter.FORMAT_STRING); } /** * Creates a SimpleDateFormat using specified formatString. */ public static DateFormat createDateFormat(final String formatString) { return new SimpleDateFormat(formatString); } /** * Gets a String representation of the current time. * * @return a String representation of the current time. */ public static String getTimeStamp() { return formatDate(new Date()); } /** * Convert a Date to a timestamp String. * * @param d a Date to format as a timestamp String. * @return a String representation of the current time. */ public static String formatDate(Date d) { try { synchronized (timeFormatter) { // Need sync: see bug 21858 return timeFormatter.format(d); } } catch (Exception e1) { // Fix bug 21857 try { return d.toString(); } catch (Exception e2) { try { return Long.toString(d.getTime()); } catch (Exception e3) { return "timestampFormatFailed"; } } } } /** * Do not instantiate this class. */ private DateFormatter() {} }
{ "content_hash": "6dce31c24079f9932eb496e8c7591661", "timestamp": "", "source": "github", "line_count": 78, "max_line_length": 98, "avg_line_length": 26.371794871794872, "alnum_prop": 0.6689353427321342, "repo_name": "deepakddixit/incubator-geode", "id": "6df52faf301f92f4c8d2cffe51441da3d8bee3e9", "size": "2846", "binary": false, "copies": "3", "ref": "refs/heads/develop", "path": "geode-core/src/main/java/org/apache/geode/internal/logging/DateFormatter.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "106708" }, { "name": "Dockerfile", "bytes": "16397" }, { "name": "Go", "bytes": "1205" }, { "name": "Groovy", "bytes": "5654" }, { "name": "HTML", "bytes": "3818849" }, { "name": "Java", "bytes": "29001614" }, { "name": "JavaScript", "bytes": "1781602" }, { "name": "Python", "bytes": "23749" }, { "name": "Ruby", "bytes": "6665" }, { "name": "Shell", "bytes": "118930" } ], "symlink_target": "" }
#include "clientmodel.h" #include "guiconstants.h" #include "optionsmodel.h" #include "addresstablemodel.h" #include "transactiontablemodel.h" #include "main.h" #include "init.h" // for pwalletMain #include "ui_interface.h" #include <QDateTime> #include <QTimer> static const int64 nClientStartupTime = GetTime(); ClientModel::ClientModel(OptionsModel *optionsModel, QObject *parent) : QObject(parent), optionsModel(optionsModel), cachedNumBlocks(0), cachedNumBlocksOfPeers(0), cachedHashrate(0), pollTimer(0) { numBlocksAtStartup = -1; pollTimer = new QTimer(this); // Read our specific settings from the wallet db /* CWalletDB walletdb(optionsModel->getWallet()->strWalletFile); walletdb.ReadSetting("miningDebug", miningDebug); walletdb.ReadSetting("miningScanTime", miningScanTime); std::string str; walletdb.ReadSetting("miningServer", str); miningServer = QString::fromStdString(str); walletdb.ReadSetting("miningPort", str); miningPort = QString::fromStdString(str); walletdb.ReadSetting("miningUsername", str); miningUsername = QString::fromStdString(str); walletdb.ReadSetting("miningPassword", str); miningPassword = QString::fromStdString(str); */ // if (fGenerateBitcoins) // { miningType = SoloMining; miningStarted = true; // } // else // { // miningType = PoolMining; // walletdb.ReadSetting("miningStarted", miningStarted); // } // miningThreads = nLimitProcessors; pollTimer->setInterval(MODEL_UPDATE_DELAY); pollTimer->start(); connect(pollTimer, SIGNAL(timeout()), this, SLOT(updateTimer())); subscribeToCoreSignals(); } ClientModel::~ClientModel() { unsubscribeFromCoreSignals(); } int ClientModel::getNumConnections() const { return vNodes.size(); } int ClientModel::getNumBlocks() const { return nBestHeight; } int ClientModel::getNumBlocksAtStartup() { if (numBlocksAtStartup == -1) numBlocksAtStartup = getNumBlocks(); return numBlocksAtStartup; } ClientModel::MiningType ClientModel::getMiningType() const { return miningType; } int ClientModel::getMiningThreads() const { return miningThreads; } bool ClientModel::getMiningStarted() const { return miningStarted; } bool ClientModel::getMiningDebug() const { return miningDebug; } void ClientModel::setMiningDebug(bool debug) { miningDebug = debug; // WriteSetting("miningDebug", miningDebug); } int ClientModel::getMiningScanTime() const { return miningScanTime; } void ClientModel::setMiningScanTime(int scantime) { miningScanTime = scantime; // WriteSetting("miningScanTime", miningScanTime); } QString ClientModel::getMiningServer() const { return miningServer; } void ClientModel::setMiningServer(QString server) { miningServer = server; // WriteSetting("miningServer", miningServer.toStdString()); } QString ClientModel::getMiningPort() const { return miningPort; } void ClientModel::setMiningPort(QString port) { miningPort = port; // WriteSetting("miningPort", miningPort.toStdString()); } QString ClientModel::getMiningUsername() const { return miningUsername; } void ClientModel::setMiningUsername(QString username) { miningUsername = username; // WriteSetting("miningUsername", miningUsername.toStdString()); } QString ClientModel::getMiningPassword() const { return miningPassword; } void ClientModel::setMiningPassword(QString password) { miningPassword = password; // WriteSetting("miningPassword", miningPassword.toStdString()); } int ClientModel::getHashrate() const { if (GetTimeMillis() - nHPSTimerStart > 8000) return (boost::int64_t)0; return (boost::int64_t)dHashesPerSec; } // AphroditeCoin: copied from bitcoinrpc.cpp. double ClientModel::GetDifficulty() const { // Floating point number that is a multiple of the minimum difficulty, // minimum difficulty = 1.0. if (pindexBest == NULL) return 1.0; int nShift = (pindexBest->nBits >> 24) & 0xff; double dDiff = (double)0x0000ffff / (double)(pindexBest->nBits & 0x00ffffff); while (nShift < 29) { dDiff *= 256.0; nShift++; } while (nShift > 29) { dDiff /= 256.0; nShift--; } return dDiff; } QDateTime ClientModel::getLastBlockDate() const { return QDateTime::fromTime_t(pindexBest->GetBlockTime()); } void ClientModel::updateTimer() { // Some quantities (such as number of blocks) change so fast that we don't want to be notified for each change. // Periodically check and update with a timer. int newNumBlocks = getNumBlocks(); int newNumBlocksOfPeers = getNumBlocksOfPeers(); if(cachedNumBlocks != newNumBlocks || cachedNumBlocksOfPeers != newNumBlocksOfPeers) emit numBlocksChanged(newNumBlocks, newNumBlocksOfPeers); cachedNumBlocks = newNumBlocks; cachedNumBlocksOfPeers = newNumBlocksOfPeers; // Only need to update if solo mining. When pool mining, stats are pushed. if (miningType == SoloMining) { int newHashrate = getHashrate(); if (cachedHashrate != newHashrate) emit miningChanged(miningStarted, newHashrate); cachedHashrate = newHashrate; } } void ClientModel::updateNumConnections(int numConnections) { emit numConnectionsChanged(numConnections); } void ClientModel::updateAlert(const QString &hash, int status) { // Show error message notification for new alert if(status == CT_NEW) { uint256 hash_256; hash_256.SetHex(hash.toStdString()); CAlert alert = CAlert::getAlertByHash(hash_256); if(!alert.IsNull()) { emit error(tr("Network Alert"), QString::fromStdString(alert.strStatusBar), false); } } // Emit a numBlocksChanged when the status message changes, // so that the view recomputes and updates the status bar. emit numBlocksChanged(getNumBlocks(), getNumBlocksOfPeers()); } bool ClientModel::isTestNet() const { return fTestNet; } bool ClientModel::inInitialBlockDownload() const { return IsInitialBlockDownload(); } int ClientModel::getNumBlocksOfPeers() const { return GetNumBlocksOfPeers(); } void ClientModel::setMining(MiningType type, bool mining, int threads, int hashrate) { if (type == SoloMining && mining != miningStarted) { GenerateBitcoins(mining ? 1 : 0, pwalletMain); } miningType = type; miningStarted = mining; // WriteSetting("miningStarted", mining); // WriteSetting("fLimitProcessors", 1); // WriteSetting("nLimitProcessors", threads); emit miningChanged(mining, hashrate); } QString ClientModel::getStatusBarWarnings() const { return QString::fromStdString(GetWarnings("statusbar")); } OptionsModel *ClientModel::getOptionsModel() { return optionsModel; } QString ClientModel::formatFullVersion() const { return QString::fromStdString(FormatFullVersion()); } QString ClientModel::formatBuildDate() const { return QString::fromStdString(CLIENT_DATE); } QString ClientModel::clientName() const { return QString::fromStdString(CLIENT_NAME); } QString ClientModel::formatClientStartupTime() const { return QDateTime::fromTime_t(nClientStartupTime).toString(); } // Handlers for core signals static void NotifyBlocksChanged(ClientModel *clientmodel) { // This notification is too frequent. Don't trigger a signal. // Don't remove it, though, as it might be useful later. } static void NotifyNumConnectionsChanged(ClientModel *clientmodel, int newNumConnections) { // Too noisy: OutputDebugStringF("NotifyNumConnectionsChanged %i\n", newNumConnections); QMetaObject::invokeMethod(clientmodel, "updateNumConnections", Qt::QueuedConnection, Q_ARG(int, newNumConnections)); } static void NotifyAlertChanged(ClientModel *clientmodel, const uint256 &hash, ChangeType status) { OutputDebugStringF("NotifyAlertChanged %s status=%i\n", hash.GetHex().c_str(), status); QMetaObject::invokeMethod(clientmodel, "updateAlert", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(hash.GetHex())), Q_ARG(int, status)); } void ClientModel::subscribeToCoreSignals() { // Connect signals to client uiInterface.NotifyBlocksChanged.connect(boost::bind(NotifyBlocksChanged, this)); uiInterface.NotifyNumConnectionsChanged.connect(boost::bind(NotifyNumConnectionsChanged, this, _1)); uiInterface.NotifyAlertChanged.connect(boost::bind(NotifyAlertChanged, this, _1, _2)); } void ClientModel::unsubscribeFromCoreSignals() { // Disconnect signals from client uiInterface.NotifyBlocksChanged.disconnect(boost::bind(NotifyBlocksChanged, this)); uiInterface.NotifyNumConnectionsChanged.disconnect(boost::bind(NotifyNumConnectionsChanged, this, _1)); uiInterface.NotifyAlertChanged.disconnect(boost::bind(NotifyAlertChanged, this, _1, _2)); }
{ "content_hash": "1e57bcf5e87c2b26daa0ba1912a88fe9", "timestamp": "", "source": "github", "line_count": 340, "max_line_length": 115, "avg_line_length": 26.53529411764706, "alnum_prop": 0.7098204389270671, "repo_name": "Aphrodite-coin/Aphrodite-coin", "id": "a444d1d6e79cf34618837efb3463388aee2e2806", "size": "9022", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/qt/clientmodel.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "78857" }, { "name": "C++", "bytes": "1373969" }, { "name": "IDL", "bytes": "11012" }, { "name": "Objective-C", "bytes": "2463" }, { "name": "Python", "bytes": "18144" }, { "name": "Shell", "bytes": "1144" }, { "name": "TypeScript", "bytes": "3810608" } ], "symlink_target": "" }
<?php namespace Symfony\Component\Serializer\Tests\Fixtures; final class AbstractDummyThirdChild extends AbstractDummyFirstChild { }
{ "content_hash": "d17298aa3ed982c63bb67a368c3bc010", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 67, "avg_line_length": 15.222222222222221, "alnum_prop": 0.8321167883211679, "repo_name": "lyrixx/symfony", "id": "3701e8c3f3bed00fddf4d9ef4ba923cb52e6bb4d", "size": "366", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "src/Symfony/Component/Serializer/Tests/Fixtures/AbstractDummyThirdChild.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "49607" }, { "name": "HTML", "bytes": "367195" }, { "name": "Hack", "bytes": "26" }, { "name": "JavaScript", "bytes": "27651" }, { "name": "Lua", "bytes": "1813" }, { "name": "PHP", "bytes": "20761306" }, { "name": "Shell", "bytes": "3136" } ], "symlink_target": "" }
cask "deskreen" do version "2.0.4" sha256 "43b9a49d0ff70211a88cfd23bf660dac9f3609063dde3ccf6d07f5307050e443" url "https://github.com/pavlobu/deskreen/releases/download/v#{version}/Deskreen-#{version}.dmg", verified: "https://github.com/pavlobu/deskreen/" name "Deskreen" desc "Turns any device with a web browser into a secondary screen" homepage "https://deskreen.com/" livecheck do url :url strategy :github_latest end app "Deskreen.app" zap trash: [ "~/Library/Application Support/Deskreen", "~/Library/Logs/Deskreen", "~/Library/Preferences/com.pavlobu.Deskreen.plist", "~/Library/Saved Application State/com.pavlobu.Deskreen.savedState", ] end
{ "content_hash": "213357e8df8c9a9fd3143fe93c70859f", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 98, "avg_line_length": 29.375, "alnum_prop": 0.7205673758865249, "repo_name": "chrisfinazzo/homebrew-cask", "id": "021a2148dc34efe81919ad155b39dcde68faee65", "size": "705", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "Casks/deskreen.rb", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Python", "bytes": "3630" }, { "name": "Ruby", "bytes": "3123311" }, { "name": "Shell", "bytes": "32035" } ], "symlink_target": "" }
''' SPDX-License-Identifier: Apache-2.0 Copyright 2017 Massachusetts Institute of Technology. ''' import traceback import sys import functools import asyncio import simplejson as json from sqlalchemy.exc import SQLAlchemyError from sqlalchemy.orm.exc import NoResultFound import tornado.ioloop import tornado.web from keylime import config from keylime.agentstates import AgentAttestStates from keylime.common import states from keylime.db.verifier_db import VerfierMain from keylime.db.verifier_db import VerifierAllowlist from keylime.db.keylime_db import DBEngineManager, SessionManager from keylime import keylime_logging from keylime import cloud_verifier_common from keylime import revocation_notifier from keylime import tornado_requests from keylime import api_version as keylime_api_version from keylime.ima_ast import START_HASH logger = keylime_logging.init_logging('cloudverifier') try: engine = DBEngineManager().make_engine('cloud_verifier') except SQLAlchemyError as err: logger.error('Error creating SQL engine or session: %s', err) sys.exit(1) def get_session(): return SessionManager().make_session(engine) def get_AgentAttestStates(): return AgentAttestStates.get_instance() # The "exclude_db" dict values are removed from the response before adding the dict to the DB # This is because we want these values to remain ephemeral and not stored in the database. exclude_db = { 'registrar_data': '', 'nonce': '', 'b64_encrypted_V': '', 'provide_V': True, 'num_retries': 0, 'pending_event': None, 'first_verified': False, # the following 3 items are updated to VerifierDB only when the AgentState is stored 'boottime': '', 'ima_pcrs': [], 'pcr10': '', 'next_ima_ml_entry': 0 } def _from_db_obj(agent_db_obj): fields = [ 'agent_id', \ 'v', \ 'ip', \ 'port', \ 'operational_state', \ 'public_key', \ 'tpm_policy', \ 'vtpm_policy', \ 'meta_data', \ 'mb_refstate', \ 'allowlist', \ 'ima_sign_verification_keys', \ 'revocation_key', \ 'accept_tpm_hash_algs', \ 'accept_tpm_encryption_algs', \ 'accept_tpm_signing_algs', \ 'hash_alg', \ 'enc_alg', \ 'sign_alg', \ 'boottime', \ 'ima_pcrs', \ 'pcr10', \ 'next_ima_ml_entry'] agent_dict = {} for field in fields: agent_dict[field] = getattr(agent_db_obj, field, None) return agent_dict def verifier_db_delete_agent(session, agent_id): get_AgentAttestStates().delete_by_agent_id(agent_id) session.query(VerfierMain).filter_by( agent_id=agent_id).delete() session.commit() def store_attestation_state(agentAttestState): # Only store if IMA log was evaluated if len(agentAttestState.get_ima_pcrs()): session = get_session() try: update_agent = session.query(VerfierMain).get(agentAttestState.get_agent_id()) update_agent.boottime = agentAttestState.get_boottime() update_agent.next_ima_ml_entry = agentAttestState.get_next_ima_ml_entry() ima_pcrs_dict = agentAttestState.get_ima_pcrs() update_agent.ima_pcrs = list(ima_pcrs_dict.keys()) for pcr_num, value in ima_pcrs_dict.items(): setattr(update_agent, 'pcr%d' % pcr_num, value) try: session.add(update_agent) except SQLAlchemyError as e: logger.error('SQLAlchemy Error on storing attestation state: %s', e) session.commit() except SQLAlchemyError as e: logger.error('SQLAlchemy Error on storing attestation state: %s', e) class BaseHandler(tornado.web.RequestHandler): def prepare(self): # pylint: disable=W0235 super().prepare() def write_error(self, status_code, **kwargs): self.set_header('Content-Type', 'text/json') if self.settings.get("serve_traceback") and "exc_info" in kwargs: # in debug mode, try to send a traceback lines = [] for line in traceback.format_exception(*kwargs["exc_info"]): lines.append(line) self.finish(json.dumps({ 'code': status_code, 'status': self._reason, 'traceback': lines, 'results': {}, })) else: self.finish(json.dumps({ 'code': status_code, 'status': self._reason, 'results': {}, })) def data_received(self, chunk): raise NotImplementedError() class MainHandler(tornado.web.RequestHandler): def head(self): config.echo_json_response( self, 405, "Not Implemented: Use /agents/ interface instead") def get(self): config.echo_json_response( self, 405, "Not Implemented: Use /agents/ interface instead") def delete(self): config.echo_json_response( self, 405, "Not Implemented: Use /agents/ interface instead") def post(self): config.echo_json_response( self, 405, "Not Implemented: Use /agents/ interface instead") def put(self): config.echo_json_response( self, 405, "Not Implemented: Use /agents/ interface instead") def data_received(self, chunk): raise NotImplementedError() class VersionHandler(BaseHandler): def head(self): config.echo_json_response( self, 405, "Not Implemented: Use GET interface instead") def get(self): rest_params = config.get_restful_params(self.request.uri) if rest_params is None: config.echo_json_response(self, 405, "Not Implemented") return if "version" not in rest_params: config.echo_json_response(self, 400, "URI not supported") logger.warning('GET returning 400 response. URI not supported: %s', self.request.path) return version_info = { "current_version": keylime_api_version.current_version(), "supported_versions": keylime_api_version.all_versions(), } config.echo_json_response(self, 200, "Success", version_info) def delete(self): config.echo_json_response( self, 405, "Not Implemented: Use GET interface instead") def post(self): config.echo_json_response( self, 405, "Not Implemented: Use GET interface instead") def put(self): config.echo_json_response( self, 405, "Not Implemented: Use GET interface instead") def data_received(self, chunk): raise NotImplementedError() class AgentsHandler(BaseHandler): def head(self): """HEAD not supported""" config.echo_json_response(self, 405, "HEAD not supported") def get(self): """This method handles the GET requests to retrieve status on agents from the Cloud Verifier. Currently, only agents resources are available for GETing, i.e. /agents. All other GET uri's will return errors. Agents requests require a single agent_id parameter which identifies the agent to be returned. If the agent_id is not found, a 404 response is returned. If the agent_id was not found, it either completed successfully, or failed. If found, the agent_id is still polling to contact the Cloud Agent. """ session = get_session() rest_params = config.get_restful_params(self.request.uri) if rest_params is None: config.echo_json_response( self, 405, "Not Implemented: Use /agents/ interface") return if not rest_params["api_version"]: config.echo_json_response(self, 400, "API Version not supported") return if "agents" not in rest_params: config.echo_json_response(self, 400, "uri not supported") logger.warning('GET returning 400 response. uri not supported: %s', self.request.path) return agent_id = rest_params["agents"] if (agent_id is not None) and (agent_id != ''): try: agent = session.query(VerfierMain).filter_by( agent_id=agent_id).one_or_none() except SQLAlchemyError as e: logger.error('SQLAlchemy Error: %s', e) if agent is not None: response = cloud_verifier_common.process_get_status(agent) config.echo_json_response(self, 200, "Success", response) else: config.echo_json_response(self, 404, "agent id not found") else: json_response = None if "bulk" in rest_params.keys(): agent_list = None if ("verifier" in rest_params.keys()) and (rest_params["verifier"] != ''): agent_list = session.query(VerfierMain).filter_by(verifier_id=rest_params["verifier"]).all() else: agent_list = session.query(VerfierMain).all() json_response = {} for agent in agent_list: json_response[agent.agent_id] = cloud_verifier_common.process_get_status(agent) config.echo_json_response(self, 200, "Success", json_response) else: if ("verifier" in rest_params.keys()) and (rest_params["verifier"] != ''): json_response = session.query(VerfierMain.agent_id).filter_by( verifier_id=rest_params["verifier"]).all() else: json_response = session.query(VerfierMain.agent_id).all() config.echo_json_response(self, 200, "Success", { 'uuids': json_response}) logger.info('GET returning 200 response for agent_id list') def delete(self): """This method handles the DELETE requests to remove agents from the Cloud Verifier. Currently, only agents resources are available for DELETEing, i.e. /agents. All other DELETE uri's will return errors. agents requests require a single agent_id parameter which identifies the agent to be deleted. """ session = get_session() rest_params = config.get_restful_params(self.request.uri) if rest_params is None: config.echo_json_response( self, 405, "Not Implemented: Use /agents/ interface") return if not rest_params["api_version"]: config.echo_json_response(self, 400, "API Version not supported") return if "agents" not in rest_params: config.echo_json_response(self, 400, "uri not supported") return agent_id = rest_params["agents"] if agent_id is None: config.echo_json_response(self, 400, "uri not supported") logger.warning('DELETE returning 400 response. uri not supported: %s', self.request.path) return try: agent = session.query(VerfierMain).filter_by( agent_id=agent_id).first() except SQLAlchemyError as e: logger.error('SQLAlchemy Error: %s', e) if agent is None: config.echo_json_response(self, 404, "agent id not found") logger.info('DELETE returning 404 response. agent id: %s not found.', agent_id) return verifier_id = config.get('cloud_verifier', 'cloudverifier_id', cloud_verifier_common.DEFAULT_VERIFIER_ID) if verifier_id != agent.verifier_id: config.echo_json_response(self, 404, "agent id associated to this verifier") logger.info('DELETE returning 404 response. agent id: %s not associated to this verifer.', agent_id) return op_state = agent.operational_state if op_state in (states.SAVED, states.FAILED, states.TERMINATED, states.TENANT_FAILED, states.INVALID_QUOTE): try: verifier_db_delete_agent(session, agent_id) except SQLAlchemyError as e: logger.error('SQLAlchemy Error: %s', e) config.echo_json_response(self, 200, "Success") logger.info('DELETE returning 200 response for agent id: %s', agent_id) else: try: update_agent = session.query(VerfierMain).get(agent_id) update_agent.operational_state = states.TERMINATED try: session.add(update_agent) except SQLAlchemyError as e: logger.error('SQLAlchemy Error: %s', e) session.commit() config.echo_json_response(self, 202, "Accepted") logger.info('DELETE returning 202 response for agent id: %s', agent_id) except SQLAlchemyError as e: logger.error('SQLAlchemy Error: %s', e) def post(self): """This method handles the POST requests to add agents to the Cloud Verifier. Currently, only agents resources are available for POSTing, i.e. /agents. All other POST uri's will return errors. agents requests require a json block sent in the body """ session = get_session() try: rest_params = config.get_restful_params(self.request.uri) if rest_params is None: config.echo_json_response( self, 405, "Not Implemented: Use /agents/ interface") return if not rest_params["api_version"]: config.echo_json_response(self, 400, "API Version not supported") return if "agents" not in rest_params: config.echo_json_response(self, 400, "uri not supported") logger.warning('POST returning 400 response. uri not supported: %s', self.request.path) return agent_id = rest_params["agents"] if agent_id is not None: content_length = len(self.request.body) if content_length == 0: config.echo_json_response( self, 400, "Expected non zero content length") logger.warning('POST returning 400 response. Expected non zero content length.') else: json_body = json.loads(self.request.body) agent_data = {} agent_data['v'] = json_body['v'] agent_data['ip'] = json_body['cloudagent_ip'] agent_data['port'] = int(json_body['cloudagent_port']) agent_data['operational_state'] = states.START agent_data['public_key'] = "" agent_data['tpm_policy'] = json_body['tpm_policy'] agent_data['vtpm_policy'] = json_body['vtpm_policy'] agent_data['meta_data'] = json_body['metadata'] agent_data['allowlist'] = json_body['allowlist'] agent_data['mb_refstate'] = json_body['mb_refstate'] agent_data['ima_sign_verification_keys'] = json_body['ima_sign_verification_keys'] agent_data['revocation_key'] = json_body['revocation_key'] agent_data['accept_tpm_hash_algs'] = json_body['accept_tpm_hash_algs'] agent_data['accept_tpm_encryption_algs'] = json_body['accept_tpm_encryption_algs'] agent_data['accept_tpm_signing_algs'] = json_body['accept_tpm_signing_algs'] agent_data['hash_alg'] = "" agent_data['enc_alg'] = "" agent_data['sign_alg'] = "" agent_data['agent_id'] = agent_id agent_data['boottime'] = 0 agent_data['ima_pcrs'] = [] agent_data['pcr10'] = START_HASH agent_data['next_ima_ml_entry'] = 0 agent_data['verifier_id'] = config.get('cloud_verifier', 'cloudverifier_id', cloud_verifier_common.DEFAULT_VERIFIER_ID) agent_data['verifier_ip'] = config.get('cloud_verifier', 'cloudverifier_ip') agent_data['verifier_port'] = config.get('cloud_verifier', 'cloudverifier_port') is_valid, err_msg = cloud_verifier_common.validate_agent_data(agent_data) if not is_valid: config.echo_json_response(self, 400, err_msg) logger.warning(err_msg) return try: new_agent_count = session.query( VerfierMain).filter_by(agent_id=agent_id).count() except SQLAlchemyError as e: logger.error('SQLAlchemy Error: %s', e) # don't allow overwriting if new_agent_count > 0: config.echo_json_response( self, 409, "Agent of uuid %s already exists" % (agent_id)) logger.warning("Agent of uuid %s already exists", agent_id) else: try: # Add the agent and data session.add(VerfierMain(**agent_data)) session.commit() except SQLAlchemyError as e: logger.error('SQLAlchemy Error: %s', e) for key in list(exclude_db.keys()): agent_data[key] = exclude_db[key] asyncio.ensure_future( process_agent(agent_data, states.GET_QUOTE)) config.echo_json_response(self, 200, "Success") logger.info('POST returning 200 response for adding agent id: %s', agent_id) else: config.echo_json_response(self, 400, "uri not supported") logger.warning("POST returning 400 response. uri not supported") except Exception as e: config.echo_json_response(self, 400, "Exception error: %s" % e) logger.warning("POST returning 400 response. Exception error: %s", e) logger.exception(e) self.finish() def put(self): """This method handles the PUT requests to add agents to the Cloud Verifier. Currently, only agents resources are available for PUTing, i.e. /agents. All other PUT uri's will return errors. agents requests require a json block sent in the body """ session = get_session() try: rest_params = config.get_restful_params(self.request.uri) if rest_params is None: config.echo_json_response( self, 405, "Not Implemented: Use /agents/ interface") return if not rest_params["api_version"]: config.echo_json_response(self, 400, "API Version not supported") return if "agents" not in rest_params: config.echo_json_response(self, 400, "uri not supported") logger.warning('PUT returning 400 response. uri not supported: %s', self.request.path) return agent_id = rest_params["agents"] if agent_id is None: config.echo_json_response(self, 400, "uri not supported") logger.warning("PUT returning 400 response. uri not supported") try: verifier_id = config.get('cloud_verifier', 'cloudverifier_id', cloud_verifier_common.DEFAULT_VERIFIER_ID) agent = session.query(VerfierMain).filter_by( agent_id=agent_id, verifier_id=verifier_id).one() except SQLAlchemyError as e: logger.error('SQLAlchemy Error: %s', e) if agent is None: config.echo_json_response(self, 404, "agent id not found") logger.info('PUT returning 404 response. agent id: %s not found.', agent_id) return if "reactivate" in rest_params: agent.operational_state = states.START asyncio.ensure_future( process_agent(agent, states.GET_QUOTE)) config.echo_json_response(self, 200, "Success") logger.info('PUT returning 200 response for agent id: %s', agent_id) elif "stop" in rest_params: # do stuff for terminate logger.debug("Stopping polling on %s", agent_id) try: session.query(VerfierMain).filter(VerfierMain.agent_id == agent_id).update( {'operational_state': states.TENANT_FAILED}) session.commit() except SQLAlchemyError as e: logger.error('SQLAlchemy Error: %s', e) config.echo_json_response(self, 200, "Success") logger.info('PUT returning 200 response for agent id: %s', agent_id) else: config.echo_json_response(self, 400, "uri not supported") logger.warning("PUT returning 400 response. uri not supported") except Exception as e: config.echo_json_response(self, 400, "Exception error: %s" % e) logger.warning("PUT returning 400 response. Exception error: %s", e) logger.exception(e) self.finish() def data_received(self, chunk): raise NotImplementedError() class AllowlistHandler(BaseHandler): def head(self): config.echo_json_response( self, 400, "Allowlist handler: HEAD Not Implemented") def get(self): """Get an allowlist GET /allowlists/{name} """ rest_params = config.get_restful_params(self.request.uri) if rest_params is None or 'allowlists' not in rest_params: config.echo_json_response(self, 400, "Invalid URL") return if not rest_params["api_version"]: config.echo_json_response(self, 400, "API Version not supported") return allowlist_name = rest_params['allowlists'] if allowlist_name is None: config.echo_json_response(self, 400, "Invalid URL") logger.warning( 'GET returning 400 response: ' + self.request.path) return session = get_session() try: allowlist = session.query(VerifierAllowlist).filter_by( name=allowlist_name).one() except NoResultFound: config.echo_json_response(self, 404, "Allowlist %s not found" % allowlist_name) return except SQLAlchemyError as e: logger.error(f'SQLAlchemy Error: {e}') config.echo_json_response(self, 500, "Failed to get allowlist") raise response = {} for field in ('name', 'tpm_policy', 'vtpm_policy', 'ima_policy'): response[field] = getattr(allowlist, field, None) config.echo_json_response(self, 200, 'Success', response) def delete(self): """Delete an allowlist DELETE /allowlists/{name} """ rest_params = config.get_restful_params(self.request.uri) if rest_params is None or 'allowlists' not in rest_params: config.echo_json_response(self, 400, "Invalid URL") return if not rest_params["api_version"]: config.echo_json_response(self, 400, "API Version not supported") return allowlist_name = rest_params['allowlists'] if allowlist_name is None: config.echo_json_response(self, 400, "Invalid URL") logger.warning( 'DELETE returning 400 response: ' + self.request.path) return session = get_session() try: session.query(VerifierAllowlist).filter_by( name=allowlist_name).one() except NoResultFound: config.echo_json_response(self, 404, "Allowlist %s not found" % allowlist_name) return except SQLAlchemyError as e: logger.error(f'SQLAlchemy Error: {e}') config.echo_json_response(self, 500, "Failed to get allowlist") raise try: session.query(VerifierAllowlist).filter_by( name=allowlist_name).delete() session.commit() except SQLAlchemyError as e: logger.error(f'SQLAlchemy Error: {e}') config.echo_json_response(self, 500, "Failed to get allowlist") raise # NOTE(kaifeng) 204 Can not have response body, but current helper # doesn't support this case. self.set_status(204) self.set_header('Content-Type', 'application/json') self.finish() logger.info( 'DELETE returning 204 response for allowlist: ' + allowlist_name) def post(self): """Create an allowlist POST /allowlists/{name} body: {"tpm_policy": {..}, "vtpm_policy": {..} """ rest_params = config.get_restful_params(self.request.uri) if rest_params is None or 'allowlists' not in rest_params: config.echo_json_response(self, 400, "Invalid URL") return if not rest_params["api_version"]: config.echo_json_response(self, 400, "API Version not supported") return allowlist_name = rest_params['allowlists'] if allowlist_name is None: config.echo_json_response(self, 400, "Invalid URL") return content_length = len(self.request.body) if content_length == 0: config.echo_json_response( self, 400, "Expected non zero content length") logger.warning( 'POST returning 400 response. Expected non zero content length.') return allowlist = {} json_body = json.loads(self.request.body) allowlist['name'] = allowlist_name tpm_policy = json_body.get('tpm_policy') if tpm_policy: allowlist['tpm_policy'] = tpm_policy vtpm_policy = json_body.get('vtpm_policy') if vtpm_policy: allowlist['vtpm_policy'] = vtpm_policy ima_policy = json_body.get('ima_policy') if ima_policy: allowlist['ima_policy'] = ima_policy session = get_session() # don't allow overwritting try: al_count = session.query( VerifierAllowlist).filter_by(name=allowlist_name).count() if al_count > 0: config.echo_json_response( self, 409, "Allowlist with name %s already exists" % allowlist_name) logger.warning( "Allowlist with name %s already exists" % allowlist_name) return except SQLAlchemyError as e: logger.error(f'SQLAlchemy Error: {e}') raise try: # Add the agent and data session.add(VerifierAllowlist(**allowlist)) session.commit() except SQLAlchemyError as e: logger.error(f'SQLAlchemy Error: {e}') raise config.echo_json_response(self, 201) logger.info('POST returning 201') def put(self): config.echo_json_response( self, 400, "Allowlist handler: PUT Not Implemented") def data_received(self, chunk): raise NotImplementedError() async def invoke_get_quote(agent, need_pubkey): if agent is None: raise Exception("agent deleted while being processed") params = cloud_verifier_common.prepare_get_quote(agent) partial_req = "1" if need_pubkey: partial_req = "0" version = keylime_api_version.current_version() res = tornado_requests.request("GET", "http://%s:%d/v%s/quotes/integrity?nonce=%s&mask=%s&vmask=%s&partial=%s&ima_ml_entry=%d" % (agent['ip'], agent['port'], version, params["nonce"], params["mask"], params['vmask'], partial_req, params['ima_ml_entry']), context=None) response = await res if response.status_code != 200: # this is a connection error, retry get quote if response.status_code == 599: asyncio.ensure_future(process_agent( agent, states.GET_QUOTE_RETRY)) else: # catastrophic error, do not continue logger.critical("Unexpected Get Quote response error for cloud agent %s, Error: %s", agent['agent_id'], response.status_code) asyncio.ensure_future(process_agent(agent, states.FAILED)) else: try: json_response = json.loads(response.body) # validate the cloud agent response if 'provide_V' not in agent : agent['provide_V'] = True agentAttestState = get_AgentAttestStates().get_by_agent_id(agent['agent_id']) if cloud_verifier_common.process_quote_response(agent, json_response['results'], agentAttestState): if agent['provide_V']: asyncio.ensure_future(process_agent(agent, states.PROVIDE_V)) else: asyncio.ensure_future(process_agent(agent, states.GET_QUOTE)) else: asyncio.ensure_future(process_agent(agent, states.INVALID_QUOTE)) # store the attestation state store_attestation_state(agentAttestState) except Exception as e: logger.exception(e) async def invoke_provide_v(agent): if agent is None: raise Exception("Agent deleted while being processed") try: if agent['pending_event'] is not None: agent['pending_event'] = None except KeyError: pass v_json_message = cloud_verifier_common.prepare_v(agent) version = keylime_api_version.current_version() res = tornado_requests.request( "POST", "http://%s:%d/%s/keys/vkey" % (agent['ip'], agent['port'], version), data=v_json_message) response = await res if response.status_code != 200: if response.status_code == 599: asyncio.ensure_future( process_agent(agent, states.PROVIDE_V_RETRY)) else: # catastrophic error, do not continue logger.critical("Unexpected Provide V response error for cloud agent %s, Error: %s", agent['agent_id'], response.error) asyncio.ensure_future(process_agent(agent, states.FAILED)) else: asyncio.ensure_future(process_agent(agent, states.GET_QUOTE)) async def process_agent(agent, new_operational_state): # Convert to dict if the agent arg is a db object if not isinstance(agent, dict): agent = _from_db_obj(agent) session = get_session() try: main_agent_operational_state = agent['operational_state'] try: stored_agent = session.query(VerfierMain).filter_by( agent_id=str(agent['agent_id'])).first() except SQLAlchemyError as e: logger.error('SQLAlchemy Error: %s', e) # if the user did terminated this agent if stored_agent.operational_state == states.TERMINATED: logger.warning("Agent %s terminated by user.", agent['agent_id']) if agent['pending_event'] is not None: tornado.ioloop.IOLoop.current().remove_timeout( agent['pending_event']) verifier_db_delete_agent(session, agent['agent_id']) return # if the user tells us to stop polling because the tenant quote check failed if stored_agent.operational_state == states.TENANT_FAILED: logger.warning("Agent %s has failed tenant quote. Stopping polling", agent['agent_id']) if agent['pending_event'] is not None: tornado.ioloop.IOLoop.current().remove_timeout( agent['pending_event']) return # If failed during processing, log regardless and drop it on the floor # The administration application (tenant) can GET the status and act accordingly (delete/retry/etc). if new_operational_state in (states.FAILED, states.INVALID_QUOTE): agent['operational_state'] = new_operational_state # issue notification for invalid quotes if new_operational_state == states.INVALID_QUOTE: cloud_verifier_common.notify_error(agent) if agent['pending_event'] is not None: tornado.ioloop.IOLoop.current().remove_timeout( agent['pending_event']) for key in exclude_db: if key in agent: del agent[key] session.query(VerfierMain).filter_by( agent_id=agent['agent_id']).update(agent) session.commit() logger.warning("Agent %s failed, stopping polling", agent['agent_id']) return # propagate all state, but remove none DB keys first (using exclude_db) try: agent_db = dict(agent) for key in exclude_db: if key in agent_db: del agent_db[key] session.query(VerfierMain).filter_by( agent_id=agent_db['agent_id']).update(agent_db) session.commit() except SQLAlchemyError as e: logger.error('SQLAlchemy Error: %s', e) # if new, get a quote if (main_agent_operational_state == states.START and new_operational_state == states.GET_QUOTE): agent['num_retries'] = 0 agent['operational_state'] = states.GET_QUOTE await invoke_get_quote(agent, True) return if (main_agent_operational_state == states.GET_QUOTE and new_operational_state == states.PROVIDE_V): agent['num_retries'] = 0 agent['operational_state'] = states.PROVIDE_V await invoke_provide_v(agent) return if (main_agent_operational_state in (states.PROVIDE_V, states.GET_QUOTE) and new_operational_state == states.GET_QUOTE): agent['num_retries'] = 0 interval = config.getfloat('cloud_verifier', 'quote_interval') agent['operational_state'] = states.GET_QUOTE if interval == 0: await invoke_get_quote(agent, False) else: logger.debug("Setting up callback to check again in %f seconds", interval) # set up a call back to check again cb = functools.partial(invoke_get_quote, agent, False) pending = tornado.ioloop.IOLoop.current().call_later(interval, cb) agent['pending_event'] = pending return maxr = config.getint('cloud_verifier', 'max_retries') retry = config.getfloat('cloud_verifier', 'retry_interval') if (main_agent_operational_state == states.GET_QUOTE and new_operational_state == states.GET_QUOTE_RETRY): if agent['num_retries'] >= maxr: logger.warning("Agent %s was not reachable for quote in %d tries, setting state to FAILED", agent['agent_id'], maxr) if agent['first_verified']: # only notify on previously good agents cloud_verifier_common.notify_error( agent, msgtype='comm_error') else: logger.debug("Communication error for new agent. No notification will be sent") await process_agent(agent, states.FAILED) else: agent['operational_state'] = states.GET_QUOTE cb = functools.partial(invoke_get_quote, agent, True) agent['num_retries'] += 1 logger.info("Connection to %s refused after %d/%d tries, trying again in %f seconds", agent['ip'], agent['num_retries'], maxr, retry) tornado.ioloop.IOLoop.current().call_later(retry, cb) return if (main_agent_operational_state == states.PROVIDE_V and new_operational_state == states.PROVIDE_V_RETRY): if agent['num_retries'] >= maxr: logger.warning("Agent %s was not reachable to provide v in %d tries, setting state to FAILED", agent['agent_id'], maxr) cloud_verifier_common.notify_error( agent, msgtype='comm_error') await process_agent(agent, states.FAILED) else: agent['operational_state'] = states.PROVIDE_V cb = functools.partial(invoke_provide_v, agent) agent['num_retries'] += 1 logger.info("Connection to %s refused after %d/%d tries, trying again in %f seconds", agent['ip'], agent['num_retries'], maxr, retry) tornado.ioloop.IOLoop.current().call_later(retry, cb) return raise Exception("nothing should ever fall out of this!") except Exception as e: logger.error("Polling thread error: %s", e) logger.exception(e) async def activate_agents(verifier_id, verifier_ip, verifier_port): session = get_session() aas = get_AgentAttestStates() try: agents = session.query(VerfierMain).filter_by( verifier_id=verifier_id).all() for agent in agents: agent.verifier_ip = verifier_ip agent.verifier_host = verifier_port if agent.operational_state == states.START: asyncio.ensure_future(process_agent(agent, states.GET_QUOTE)) if agent.boottime: ima_pcrs_dict = {} for pcr_num in agent.ima_pcrs: ima_pcrs_dict[pcr_num] = getattr(agent, 'pcr%d' % pcr_num) aas.add(agent.agent_id, agent.boottime, ima_pcrs_dict, agent.next_ima_ml_entry) session.commit() except SQLAlchemyError as e: logger.error('SQLAlchemy Error: %s', e) def start_tornado(tornado_server, port): tornado_server.listen(port) print("Starting Torando on port " + str(port)) tornado.ioloop.IOLoop.instance().start() print("Tornado finished") def main(): """Main method of the Cloud Verifier Server. This method is encapsulated in a function for packaging to allow it to be called as a function by an external program.""" cloudverifier_port = config.get('cloud_verifier', 'cloudverifier_port') cloudverifier_host = config.get('cloud_verifier', 'cloudverifier_ip') cloudverifier_id = config.get('cloud_verifier', 'cloudverifier_id', cloud_verifier_common.DEFAULT_VERIFIER_ID) # allow tornado's max upload size to be configurable max_upload_size = None if config.has_option('cloud_verifier', 'max_upload_size'): max_upload_size = int(config.get('cloud_verifier', 'max_upload_size')) VerfierMain.metadata.create_all(engine, checkfirst=True) session = get_session() try: query_all = session.query(VerfierMain).all() for row in query_all: if row.operational_state in states.APPROVED_REACTIVATE_STATES: row.operational_state = states.START session.commit() except SQLAlchemyError as e: logger.error('SQLAlchemy Error: %s', e) num = session.query(VerfierMain.agent_id).count() if num > 0: agent_ids = session.query(VerfierMain.agent_id).all() logger.info("Agent ids in db loaded from file: %s", agent_ids) logger.info('Starting Cloud Verifier (tornado) on port %s, use <Ctrl-C> to stop', cloudverifier_port) # print out API versions we support keylime_api_version.log_api_versions(logger) app = tornado.web.Application([ (r"/v?[0-9]+(?:\.[0-9]+)?/agents/.*", AgentsHandler), (r"/v?[0-9]+(?:\.[0-9]+)?/allowlists/.*", AllowlistHandler), (r"/versions?", VersionHandler), (r".*", MainHandler), ]) context = cloud_verifier_common.init_mtls() # after TLS is up, start revocation notifier if config.getboolean('cloud_verifier', 'revocation_notifier'): logger.info("Starting service for revocation notifications on port %s", config.getint('cloud_verifier', 'revocation_notifier_port')) revocation_notifier.start_broker() sockets = tornado.netutil.bind_sockets( int(cloudverifier_port), address=cloudverifier_host) task_id = tornado.process.fork_processes(config.getint( 'cloud_verifier', 'multiprocessing_pool_num_workers')) asyncio.set_event_loop(asyncio.new_event_loop()) # Auto reactivate agent if task_id == 0: asyncio.ensure_future(activate_agents(cloudverifier_id, cloudverifier_host, cloudverifier_port)) server = tornado.httpserver.HTTPServer(app, ssl_options=context, max_buffer_size=max_upload_size) server.add_sockets(sockets) try: tornado.ioloop.IOLoop.instance().start() except KeyboardInterrupt: tornado.ioloop.IOLoop.instance().stop() if config.getboolean('cloud_verifier', 'revocation_notifier'): revocation_notifier.stop_broker()
{ "content_hash": "7c5f3a581c61338faa9b12797e66b7cf", "timestamp": "", "source": "github", "line_count": 1006, "max_line_length": 174, "avg_line_length": 41.35487077534791, "alnum_prop": 0.5814484532365455, "repo_name": "mit-ll/python-keylime", "id": "cfcb59f556094b20442dbc68eda467acad8028cf", "size": "41622", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "keylime/cloud_verifier_tornado.py", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C", "bytes": "3128" }, { "name": "CSS", "bytes": "4767" }, { "name": "JavaScript", "bytes": "18188" }, { "name": "Python", "bytes": "617887" }, { "name": "Shell", "bytes": "51983" } ], "symlink_target": "" }
import os import setuptools VERSION = '0.1.1' README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read() setuptools.setup( name='pyglib', author='Benjamin Staffin', author_email='benley@gmail.com', url='https://github.com/benley/pyglib', install_requires=[ 'python-gflags', 'glog>=0.3', ], description='Opinionated but handy app startup wrapper.', long_description=README, packages=['pyglib'], license='BSD', version=VERSION, classifiers=[ 'Programming Language :: Python', 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Topic :: System :: Logging', 'Topic :: Software Development :: Libraries :: Python Modules', ], platforms='any', )
{ "content_hash": "3d1fd1ab3db07978603657e1fcb09315", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 75, "avg_line_length": 27.129032258064516, "alnum_prop": 0.6076099881093936, "repo_name": "benley/pyglib", "id": "43cb28b47c5faf4602af4057e03636bafa1ffbb9", "size": "864", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "setup.py", "mode": "33261", "license": "bsd-2-clause", "language": [ { "name": "Python", "bytes": "6126" } ], "symlink_target": "" }
""" Note: Django 1.4 support was dropped in #107 https://github.com/pydanny/dj-stripe/pull/107 """ from django.contrib import admin from .models import Event, EventProcessingException, Transfer, Charge#, Plan from .models import Invoice, InvoiceItem, CurrentSubscription, Customer class CustomerHasCardListFilter(admin.SimpleListFilter): title = "card presence" parameter_name = "has_card" def lookups(self, request, model_admin): return [ ["yes", "Has Card"], ["no", "Does Not Have a Card"] ] def queryset(self, request, queryset): if self.value() == "yes": return queryset.exclude(card_fingerprint="") if self.value() == "no": return queryset.filter(card_fingerprint="") class InvoiceCustomerHasCardListFilter(admin.SimpleListFilter): title = "card presence" parameter_name = "has_card" def lookups(self, request, model_admin): return [ ["yes", "Has Card"], ["no", "Does Not Have a Card"] ] def queryset(self, request, queryset): if self.value() == "yes": return queryset.exclude(customer__card_fingerprint="") if self.value() == "no": return queryset.filter(customer__card_fingerprint="") class CustomerSubscriptionStatusListFilter(admin.SimpleListFilter): title = "subscription status" parameter_name = "sub_status" def lookups(self, request, model_admin): statuses = [ [x, x.replace("_", " ").title()] for x in CurrentSubscription.objects.all().values_list( "status", flat=True ).distinct() ] statuses.append(["none", "No Subscription"]) return statuses def queryset(self, request, queryset): if self.value() is None: return queryset.all() else: return queryset.filter(current_subscription__status=self.value()) def send_charge_receipt(modeladmin, request, queryset): """ Function for sending receipts from the admin if a receipt is not sent for a specific charge. """ for charge in queryset: charge.send_receipt() admin.site.register( Charge, readonly_fields=('created',), list_display=[ "stripe_id", "customer", "amount", "description", "paid", "disputed", "refunded", "fee", "receipt_sent", "created" ], search_fields=[ "stripe_id", "customer__stripe_id", "customer__subscriber__email", "card_last_4", "invoice__stripe_id" ], list_filter=[ "paid", "disputed", "refunded", "card_kind", "created" ], raw_id_fields=[ "customer", "invoice" ], actions=(send_charge_receipt,), ) admin.site.register( EventProcessingException, readonly_fields=('created',), list_display=[ "message", "event", "created" ], search_fields=[ "message", "traceback", "data" ], ) admin.site.register( Event, raw_id_fields=["customer"], readonly_fields=('created',), list_display=[ "stripe_id", "kind", "livemode", "valid", "processed", "created" ], list_filter=[ "kind", "created", "valid", "processed" ], search_fields=[ "stripe_id", "customer__stripe_id", "customer__subscriber__email", "validated_message" ], ) class CurrentSubscriptionInline(admin.TabularInline): model = CurrentSubscription def subscription_status(obj): return obj.current_subscription.status subscription_status.short_description = "Subscription Status" admin.site.register( Customer, #raw_id_fields=["subscriber"], readonly_fields=('created',), list_display=[ "stripe_id", #"subscriber", "card_kind", "card_last_4", subscription_status, "created" ], list_filter=[ "card_kind", CustomerHasCardListFilter, CustomerSubscriptionStatusListFilter ], search_fields=[ "stripe_id", "subscriber__email" ], inlines=[CurrentSubscriptionInline] ) class InvoiceItemInline(admin.TabularInline): model = InvoiceItem def customer_has_card(obj): """ Returns True if the customer has a card attached to its account.""" return obj.customer.card_fingerprint != "" customer_has_card.short_description = "Customer Has Card" def customer_email(obj): """ Returns a string representation of the customer's email.""" return str(obj.customer.subscriber.email) customer_email.short_description = "Customer" admin.site.register( Invoice, raw_id_fields=["customer"], readonly_fields=('created',), list_display=[ "stripe_id", "paid", "closed", customer_email, customer_has_card, "period_start", "period_end", "subtotal", "total", "created" ], search_fields=[ "stripe_id", "customer__stripe_id", "customer__subscriber__email" ], list_filter=[ InvoiceCustomerHasCardListFilter, "paid", "closed", "attempted", "attempts", "created", "date", "period_end", "total" ], inlines=[InvoiceItemInline] ) admin.site.register( Transfer, raw_id_fields=["event"], readonly_fields=('created',), list_display=[ "stripe_id", "amount", "status", "date", "description", "created" ], search_fields=[ "stripe_id", "event__stripe_id" ] ) # class PlanAdmin(admin.ModelAdmin): # # def save_model(self, request, obj, form, change): # """Update or create objects using our custom methods that # sync with Stripe.""" # # if change: # obj.update_name() # # else: # Plan.get_or_create(**form.cleaned_data) # # def get_readonly_fields(self, request, obj=None): # readonly_fields = list(self.readonly_fields) # if obj: # readonly_fields.extend([ # 'stripe_id', # 'amount', # 'currency', # 'interval', # 'interval_count', # 'trial_period_days']) # # return readonly_fields # # admin.site.register(Plan, PlanAdmin)
{ "content_hash": "a230291a54f32fba6c0b35b48725504c", "timestamp": "", "source": "github", "line_count": 285, "max_line_length": 77, "avg_line_length": 23.23859649122807, "alnum_prop": 0.5582062509436811, "repo_name": "rawjam/dj-stripe", "id": "fbedf2d89b79450e7ba0ed8e37ee0b81065db280", "size": "6647", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "djstripe/admin.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "HTML", "bytes": "22023" }, { "name": "Makefile", "bytes": "226" }, { "name": "Python", "bytes": "189353" } ], "symlink_target": "" }